blob: 20d960611020178635d12e4b3d6bba05fe83db8b [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerac161bf2009-01-02 07:01:27 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/None.h"
16#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000019#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000020#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000045#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000046#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000047#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000048#include <algorithm>
49#include <cassert>
50#include <cstring>
51#include <iterator>
52#include <vector>
53
Chris Lattnerac161bf2009-01-02 07:01:27 +000054using namespace llvm;
55
Chris Lattner229907c2011-07-18 04:54:35 +000056static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000057 std::string Result;
58 raw_string_ostream Tmp(Result);
59 Tmp << *T;
60 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000061}
62
Chris Lattner3822f632009-01-02 08:05:26 +000063/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000064bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000065 // Prime the lexer.
66 Lex.Lex();
67
Mehdi Amini50af49f2016-04-02 03:46:17 +000068 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069 return Error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
72
Teresa Johnson63ee0e72018-06-26 13:56:49 +000073 return ParseTopLevelEntities() || ValidateEndOfModule() ||
74 ValidateEndOfIndex();
Chris Lattnerac161bf2009-01-02 07:01:27 +000075}
76
Alex Lorenz1de2acd2015-08-21 21:32:39 +000077bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000080 Lex.Lex();
81
82 Type *Ty = nullptr;
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
84 return true;
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
87 return false;
88}
89
Quentin Colombetdafed5d2016-03-08 00:37:07 +000090bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000092 restoreParsingState(Slots);
93 Lex.Lex();
94
Quentin Colombetdafed5d2016-03-08 00:37:07 +000095 Read = 0;
96 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000097 Ty = nullptr;
98 if (ParseType(Ty))
99 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
102
Quentin Colombet81e72b42016-03-07 22:09:05 +0000103 return false;
104}
105
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000106void LLParser::restoreParsingState(const SlotMapping *Slots) {
107 if (!Slots)
108 return;
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
112 NamedTypes.insert(
113 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114 for (const auto &I : Slots->Types)
115 NumberedTypes.insert(
116 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
117}
118
Chris Lattnerac161bf2009-01-02 07:01:27 +0000119/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
120/// module.
121bool LLParser::ValidateEndOfModule() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000122 if (!M)
123 return false;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000124 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000128 AttrBuilder B;
129
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000132
133 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000134 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000147 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
148 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000151 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000157 CI->setAttributes(AS);
158 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000159 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000162 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000165 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000166 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
167 AttrBuilder Attrs(GV->getAttributes());
168 Attrs.merge(B);
169 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000170 } else {
171 llvm_unreachable("invalid object with forward attribute group reference");
172 }
173 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000174
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000175 // If there are entries in ForwardRefBlockAddresses at this point, the
176 // function was never defined.
177 if (!ForwardRefBlockAddresses.empty())
178 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
179 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000180
David Majnemer19b51052015-02-11 07:43:56 +0000181 for (const auto &NT : NumberedTypes)
182 if (NT.second.second.isValid())
183 return Error(NT.second.second,
184 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000185
186 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
187 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
188 if (I->second.second.isValid())
189 return Error(I->second.second,
190 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000191
David Majnemerdad0a642014-06-27 18:19:56 +0000192 if (!ForwardRefComdats.empty())
193 return Error(ForwardRefComdats.begin()->second,
194 "use of undefined comdat '$" +
195 ForwardRefComdats.begin()->first + "'");
196
Chris Lattnerac161bf2009-01-02 07:01:27 +0000197 if (!ForwardRefVals.empty())
198 return Error(ForwardRefVals.begin()->second.second,
199 "use of undefined value '@" + ForwardRefVals.begin()->first +
200 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000201
Chris Lattnerac161bf2009-01-02 07:01:27 +0000202 if (!ForwardRefValIDs.empty())
203 return Error(ForwardRefValIDs.begin()->second.second,
204 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000205 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000206
Devang Pateld2541152009-07-08 19:23:54 +0000207 if (!ForwardRefMDNodes.empty())
208 return Error(ForwardRefMDNodes.begin()->second.second,
209 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000210 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000211
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000212 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000213 for (auto &N : NumberedMetadata) {
214 if (N.second && !N.second->isResolved())
215 N.second->resolveCycles();
216 }
Devang Pateld2541152009-07-08 19:23:54 +0000217
Mehdi Aminie4709272016-09-14 22:29:59 +0000218 for (auto *Inst : InstsWithTBAATag) {
219 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
220 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
221 auto *UpgradedMD = UpgradeTBAANode(*MD);
222 if (MD != UpgradedMD)
223 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
224 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000225
Chris Lattnerac161bf2009-01-02 07:01:27 +0000226 // Look for intrinsic functions and CallInst that need to be upgraded
227 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000228 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000229
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000230 // Some types could be renamed during loading if several modules are
231 // loaded in the same LLVMContext (LTO scenario). In this case we should
232 // remangle intrinsics names as well.
233 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
234 Function *F = &*FI++;
235 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
236 F->replaceAllUsesWith(Remangled.getValue());
237 F->eraseFromParent();
238 }
239 }
240
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000241 if (UpgradeDebugInfo)
242 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000243
Manman Renb5d7ff42016-05-25 23:14:48 +0000244 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000245 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000246
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000247 if (!Slots)
248 return false;
249 // Initialize the slot mapping.
250 // Because by this point we've parsed and validated everything, we can "steal"
251 // the mapping from LLParser as it doesn't need it anymore.
252 Slots->GlobalValues = std::move(NumberedVals);
253 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000254 for (const auto &I : NamedTypes)
255 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
256 for (const auto &I : NumberedTypes)
257 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000258
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 return false;
260}
261
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000262/// Do final validity and sanity checks at the end of the index.
263bool LLParser::ValidateEndOfIndex() {
264 if (!Index)
265 return false;
266
267 if (!ForwardRefValueInfos.empty())
268 return Error(ForwardRefValueInfos.begin()->second.front().second,
269 "use of undefined summary '^" +
270 Twine(ForwardRefValueInfos.begin()->first) + "'");
271
272 if (!ForwardRefAliasees.empty())
273 return Error(ForwardRefAliasees.begin()->second.front().second,
274 "use of undefined summary '^" +
275 Twine(ForwardRefAliasees.begin()->first) + "'");
276
277 if (!ForwardRefTypeIds.empty())
278 return Error(ForwardRefTypeIds.begin()->second.front().second,
279 "use of undefined type id summary '^" +
280 Twine(ForwardRefTypeIds.begin()->first) + "'");
281
282 return false;
283}
284
Chris Lattnerac161bf2009-01-02 07:01:27 +0000285//===----------------------------------------------------------------------===//
286// Top-Level Entities
287//===----------------------------------------------------------------------===//
288
289bool LLParser::ParseTopLevelEntities() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000290 // If there is no Module, then parse just the summary index entries.
291 if (!M) {
292 while (true) {
293 switch (Lex.getKind()) {
294 case lltok::Eof:
295 return false;
296 case lltok::SummaryID:
297 if (ParseSummaryEntry())
298 return true;
299 break;
300 case lltok::kw_source_filename:
301 if (ParseSourceFileName())
302 return true;
303 break;
304 default:
305 // Skip everything else
306 Lex.Lex();
307 }
308 }
309 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000310 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000311 switch (Lex.getKind()) {
312 default: return TokError("expected top-level entity");
313 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 case lltok::kw_declare: if (ParseDeclare()) return true; break;
315 case lltok::kw_define: if (ParseDefine()) return true; break;
316 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
317 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000318 case lltok::kw_source_filename:
319 if (ParseSourceFileName())
320 return true;
321 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000322 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000323 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000325 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000326 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000327 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000328 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000329 case lltok::SummaryID:
330 if (ParseSummaryEntry())
331 return true;
332 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000333 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000334 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000335 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
336 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000337 if (ParseUseListOrderBB())
338 return true;
339 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000340 }
341 }
342}
343
Chris Lattnerac161bf2009-01-02 07:01:27 +0000344/// toplevelentity
345/// ::= 'module' 'asm' STRINGCONSTANT
346bool LLParser::ParseModuleAsm() {
347 assert(Lex.getKind() == lltok::kw_module);
348 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000349
350 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000351 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
352 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000353
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000354 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000355 return false;
356}
357
358/// toplevelentity
359/// ::= 'target' 'triple' '=' STRINGCONSTANT
360/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
361bool LLParser::ParseTargetDefinition() {
362 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000363 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000364 switch (Lex.Lex()) {
365 default: return TokError("unknown target property");
366 case lltok::kw_triple:
367 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000368 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
369 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000371 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000372 return false;
373 case lltok::kw_datalayout:
374 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000375 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
376 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000378 if (DataLayoutStr.empty())
379 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380 return false;
381 }
382}
383
Bill Wendling706d3d62012-11-28 08:41:48 +0000384/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000385/// ::= 'source_filename' '=' STRINGCONSTANT
386bool LLParser::ParseSourceFileName() {
387 assert(Lex.getKind() == lltok::kw_source_filename);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000388 Lex.Lex();
389 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000390 ParseStringConstant(SourceFileName))
Teresa Johnson83c517c2016-03-30 18:15:08 +0000391 return true;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000392 if (M)
393 M->setSourceFileName(SourceFileName);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000394 return false;
395}
396
397/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000398/// ::= 'deplibs' '=' '[' ']'
399/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
400/// FIXME: Remove in 4.0. Currently parse, but ignore.
401bool LLParser::ParseDepLibs() {
402 assert(Lex.getKind() == lltok::kw_deplibs);
403 Lex.Lex();
404 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
405 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
406 return true;
407
408 if (EatIfPresent(lltok::rsquare))
409 return false;
410
411 do {
412 std::string Str;
413 if (ParseStringConstant(Str)) return true;
414 } while (EatIfPresent(lltok::comma));
415
416 return ParseToken(lltok::rsquare, "expected ']' at end of list");
417}
418
Dan Gohman466876b2009-08-12 23:32:33 +0000419/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000420/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000421bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000422 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000423 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000424 Lex.Lex(); // eat LocalVarID;
425
426 if (ParseToken(lltok::equal, "expected '=' after name") ||
427 ParseToken(lltok::kw_type, "expected 'type' after '='"))
428 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429
Craig Topper2617dcc2014-04-15 06:32:26 +0000430 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000431 if (ParseStructDefinition(TypeLoc, "",
432 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000433
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000434 if (!isa<StructType>(Result)) {
435 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
436 if (Entry.first)
437 return Error(TypeLoc, "non-struct types may not be recursive");
438 Entry.first = Result;
439 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000441
Chris Lattnerac161bf2009-01-02 07:01:27 +0000442 return false;
443}
444
445/// toplevelentity
446/// ::= LocalVar '=' 'type' type
447bool LLParser::ParseNamedType() {
448 std::string Name = Lex.getStrVal();
449 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000450 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Chris Lattner3822f632009-01-02 08:05:26 +0000452 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000453 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000454 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000455
Craig Topper2617dcc2014-04-15 06:32:26 +0000456 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000457 if (ParseStructDefinition(NameLoc, Name,
458 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000459
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000460 if (!isa<StructType>(Result)) {
461 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
462 if (Entry.first)
463 return Error(NameLoc, "non-struct types may not be recursive");
464 Entry.first = Result;
465 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000466 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000467
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000468 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000469}
470
Chris Lattnerac161bf2009-01-02 07:01:27 +0000471/// toplevelentity
472/// ::= 'declare' FunctionHeader
473bool LLParser::ParseDeclare() {
474 assert(Lex.getKind() == lltok::kw_declare);
475 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000476
Peter Collingbourne21521892016-06-21 23:42:48 +0000477 std::vector<std::pair<unsigned, MDNode *>> MDs;
478 while (Lex.getKind() == lltok::MetadataVar) {
479 unsigned MDK;
480 MDNode *N;
481 if (ParseMetadataAttachment(MDK, N))
482 return true;
483 MDs.push_back({MDK, N});
484 }
485
Chris Lattnerac161bf2009-01-02 07:01:27 +0000486 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000487 if (ParseFunctionHeader(F, false))
488 return true;
489 for (auto &MD : MDs)
490 F->addMetadata(MD.first, *MD.second);
491 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000492}
493
494/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000495/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000496bool LLParser::ParseDefine() {
497 assert(Lex.getKind() == lltok::kw_define);
498 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000499
Chris Lattnerac161bf2009-01-02 07:01:27 +0000500 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000501 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000502 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000503 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000504}
505
Chris Lattner3822f632009-01-02 08:05:26 +0000506/// ParseGlobalType
507/// ::= 'constant'
508/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000509bool LLParser::ParseGlobalType(bool &IsConstant) {
510 if (Lex.getKind() == lltok::kw_constant)
511 IsConstant = true;
512 else if (Lex.getKind() == lltok::kw_global)
513 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000514 else {
515 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000516 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000517 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000518 Lex.Lex();
519 return false;
520}
521
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000522bool LLParser::ParseOptionalUnnamedAddr(
523 GlobalVariable::UnnamedAddr &UnnamedAddr) {
524 if (EatIfPresent(lltok::kw_unnamed_addr))
525 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
526 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
527 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
528 else
529 UnnamedAddr = GlobalValue::UnnamedAddr::None;
530 return false;
531}
532
Dan Gohman466876b2009-08-12 23:32:33 +0000533/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000534/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000535/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
536/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000537/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000538/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000539/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
540/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000541/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000542bool LLParser::ParseUnnamedGlobal() {
543 unsigned VarID = NumberedVals.size();
544 std::string Name;
545 LocTy NameLoc = Lex.getLoc();
546
547 // Handle the GlobalID form.
548 if (Lex.getKind() == lltok::GlobalID) {
549 if (Lex.getUIntVal() != VarID)
550 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000551 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000552 Lex.Lex(); // eat GlobalID;
553
554 if (ParseToken(lltok::equal, "expected '=' after name"))
555 return true;
556 }
557
558 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000559 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000560 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000561 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000562 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000563 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
564 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000565 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000566 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000567
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000568 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000569 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000570 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000571
572 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000573 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000574}
575
Chris Lattnerac161bf2009-01-02 07:01:27 +0000576/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000577/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000578/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
579/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000580/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000581bool LLParser::ParseNamedGlobal() {
582 assert(Lex.getKind() == lltok::GlobalVar);
583 LocTy NameLoc = Lex.getLoc();
584 std::string Name = Lex.getStrVal();
585 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000586
Chris Lattnerac161bf2009-01-02 07:01:27 +0000587 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000588 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000589 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000590 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000591 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000592 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000593 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
594 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000595 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000596 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000597
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000598 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000599 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000600 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000601
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000602 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000603 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000604}
605
David Majnemerdad0a642014-06-27 18:19:56 +0000606bool LLParser::parseComdat() {
607 assert(Lex.getKind() == lltok::ComdatVar);
608 std::string Name = Lex.getStrVal();
609 LocTy NameLoc = Lex.getLoc();
610 Lex.Lex();
611
612 if (ParseToken(lltok::equal, "expected '=' here"))
613 return true;
614
615 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
616 return TokError("expected comdat type");
617
618 Comdat::SelectionKind SK;
619 switch (Lex.getKind()) {
620 default:
621 return TokError("unknown selection kind");
622 case lltok::kw_any:
623 SK = Comdat::Any;
624 break;
625 case lltok::kw_exactmatch:
626 SK = Comdat::ExactMatch;
627 break;
628 case lltok::kw_largest:
629 SK = Comdat::Largest;
630 break;
631 case lltok::kw_noduplicates:
632 SK = Comdat::NoDuplicates;
633 break;
634 case lltok::kw_samesize:
635 SK = Comdat::SameSize;
636 break;
637 }
638 Lex.Lex();
639
640 // See if the comdat was forward referenced, if so, use the comdat.
641 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
642 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
643 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
644 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
645
646 Comdat *C;
647 if (I != ComdatSymTab.end())
648 C = &I->second;
649 else
650 C = M->getOrInsertComdat(Name);
651 C->setSelectionKind(SK);
652
653 return false;
654}
655
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000656// MDString:
657// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000658bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000659 std::string Str;
660 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000661 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000662 return false;
663}
664
665// MDNode:
666// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000667bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000668 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000669 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000670 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000671 if (ParseUInt32(MID))
672 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000673
Chris Lattner8eff0152010-04-01 05:14:45 +0000674 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000675 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000676 Result = NumberedMetadata[MID];
677 return false;
678 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000679
Chris Lattner8eff0152010-04-01 05:14:45 +0000680 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000681 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000682 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000683
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000684 Result = FwdRef.first.get();
685 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000686 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000688
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000689/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000690/// !foo = !{ !1, !2 }
691bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000692 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000693 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000694 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000695
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000696 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000697 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000698 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000699 return true;
700
Dan Gohman2637cc12010-07-21 23:38:33 +0000701 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000702 if (Lex.getKind() != lltok::rbrace)
703 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000704 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000705 // Parse DIExpressions inline as a special case. They are still MDNodes,
706 // so they can still appear in named metadata. Remove this logic if they
707 // become plain Metadata.
708 if (Lex.getKind() == lltok::MetadataVar &&
709 Lex.getStrVal() == "DIExpression") {
710 if (ParseDIExpression(N, /*IsDistinct=*/false))
711 return true;
712 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
713 ParseMDNodeID(N)) {
714 return true;
715 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000716 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000717 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000718
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000719 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000720}
721
Devang Patel39e64d42009-07-01 19:21:12 +0000722/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000724bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000725 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000726 Lex.Lex();
727 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000728
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000729 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000730 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000731 ParseToken(lltok::equal, "expected '=' here"))
732 return true;
733
734 // Detect common error, from old metadata syntax.
735 if (Lex.getKind() == lltok::Type)
736 return TokError("unexpected type in metadata definition");
737
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000738 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000739 if (Lex.getKind() == lltok::MetadataVar) {
740 if (ParseSpecializedMDNode(Init, IsDistinct))
741 return true;
742 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
743 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000744 return true;
745
Chris Lattnerfc58af22009-12-30 04:51:58 +0000746 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000747 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000748 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000749 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000750 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000751
Chris Lattnerfc58af22009-12-30 04:51:58 +0000752 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
753 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000754 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000755 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000756 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000757 }
758
Devang Patel39e64d42009-07-01 19:21:12 +0000759 return false;
760}
761
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000762// Skips a single module summary entry.
763bool LLParser::SkipModuleSummaryEntry() {
764 // Each module summary entry consists of a tag for the entry
765 // type, followed by a colon, then the fields surrounded by nested sets of
766 // parentheses. The "tag:" looks like a Label. Once parsing support is
767 // in place we will look for the tokens corresponding to the expected tags.
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000768 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
769 Lex.getKind() != lltok::kw_typeid)
770 return TokError(
771 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
772 Lex.Lex();
773 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000774 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
775 return true;
776 // Now walk through the parenthesized entry, until the number of open
777 // parentheses goes back down to 0 (the first '(' was parsed above).
778 unsigned NumOpenParen = 1;
779 do {
780 switch (Lex.getKind()) {
781 case lltok::lparen:
782 NumOpenParen++;
783 break;
784 case lltok::rparen:
785 NumOpenParen--;
786 break;
787 case lltok::Eof:
788 return TokError("found end of file while parsing summary entry");
789 default:
790 // Skip everything in between parentheses.
791 break;
792 }
793 Lex.Lex();
794 } while (NumOpenParen > 0);
795 return false;
796}
797
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000798/// SummaryEntry
799/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000800bool LLParser::ParseSummaryEntry() {
801 assert(Lex.getKind() == lltok::SummaryID);
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000802 unsigned SummaryID = Lex.getUIntVal();
803
804 // For summary entries, colons should be treated as distinct tokens,
805 // not an indication of the end of a label token.
806 Lex.setIgnoreColonInIdentifiers(true);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000807
808 Lex.Lex();
809 if (ParseToken(lltok::equal, "expected '=' here"))
810 return true;
811
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000812 // If we don't have an index object, skip the summary entry.
813 if (!Index)
814 return SkipModuleSummaryEntry();
815
816 switch (Lex.getKind()) {
817 case lltok::kw_gv:
818 return ParseGVEntry(SummaryID);
819 case lltok::kw_module:
820 return ParseModuleEntry(SummaryID);
821 case lltok::kw_typeid:
822 return ParseTypeIdEntry(SummaryID);
823 break;
824 default:
825 return Error(Lex.getLoc(), "unexpected summary kind");
826 }
827 Lex.setIgnoreColonInIdentifiers(false);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000828 return false;
829}
830
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000831static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
832 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
833 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
834}
835
Rafael Espindolae4b02312018-01-11 22:15:05 +0000836// If there was an explicit dso_local, update GV. In the absence of an explicit
837// dso_local we keep the default value.
838static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
839 if (DSOLocal)
840 GV.setDSOLocal(true);
841}
842
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000843/// parseIndirectSymbol:
Fangrui Songf78650a2018-07-30 19:41:25 +0000844/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertilec70d28b2017-10-26 15:00:26 +0000845/// OptionalVisibility OptionalDLLStorageClass
846/// OptionalThreadLocal OptionalUnnamedAddr
847// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000848///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000849/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000850/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000851///
Eric Christopher536f0a92015-05-28 23:07:39 +0000852/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000853///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000854bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
855 unsigned L, unsigned Visibility,
856 unsigned DLLStorageClass, bool DSOLocal,
857 GlobalVariable::ThreadLocalMode TLM,
858 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000859 bool IsAlias;
860 if (Lex.getKind() == lltok::kw_alias)
861 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000862 else if (Lex.getKind() == lltok::kw_ifunc)
863 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000864 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000865 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867
Rafael Espindola78527052013-10-06 15:10:43 +0000868 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
869
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000870 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000871 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000872
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000873 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000874 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000875 "symbol with local linkage must have default visibility");
876
David Blaikie2f408302015-09-11 03:22:04 +0000877 Type *Ty;
878 LocTy ExplicitTypeLoc = Lex.getLoc();
879 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000880 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000881 return true;
882
Rafael Espindola64c1e182014-06-03 02:41:57 +0000883 Constant *Aliasee;
884 LocTy AliaseeLoc = Lex.getLoc();
885 if (Lex.getKind() != lltok::kw_bitcast &&
886 Lex.getKind() != lltok::kw_getelementptr &&
887 Lex.getKind() != lltok::kw_addrspacecast &&
888 Lex.getKind() != lltok::kw_inttoptr) {
889 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000890 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000891 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000892 // The bitcast dest type is not present, it is implied by the dest type.
893 ValID ID;
894 if (ParseValID(ID))
895 return true;
896 if (ID.Kind != ValID::t_Constant)
897 return Error(AliaseeLoc, "invalid aliasee");
898 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000900
Rafael Espindola64c1e182014-06-03 02:41:57 +0000901 Type *AliaseeType = Aliasee->getType();
902 auto *PTy = dyn_cast<PointerType>(AliaseeType);
903 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000904 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000905 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000906
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000907 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000908 return Error(
909 ExplicitTypeLoc,
910 "explicit pointee type doesn't match operand's pointee type");
911
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000912 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
913 return Error(
914 ExplicitTypeLoc,
915 "explicit pointee type should be a function type");
916
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000917 GlobalValue *GVal = nullptr;
918
919 // See if the alias was forward referenced, if so, prepare to replace the
920 // forward reference.
921 if (!Name.empty()) {
922 GVal = M->getNamedValue(Name);
923 if (GVal) {
924 if (!ForwardRefVals.erase(Name))
925 return Error(NameLoc, "redefinition of global '@" + Name + "'");
926 }
927 } else {
928 auto I = ForwardRefValIDs.find(NumberedVals.size());
929 if (I != ForwardRefValIDs.end()) {
930 GVal = I->second.first;
931 ForwardRefValIDs.erase(I);
932 }
933 }
934
Chris Lattnerac161bf2009-01-02 07:01:27 +0000935 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000936 std::unique_ptr<GlobalIndirectSymbol> GA;
937 if (IsAlias)
938 GA.reset(GlobalAlias::create(Ty, AddrSpace,
939 (GlobalValue::LinkageTypes)Linkage, Name,
940 Aliasee, /*Parent*/ nullptr));
941 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000942 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
943 (GlobalValue::LinkageTypes)Linkage, Name,
944 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000945 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000946 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000947 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000948 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000949 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000950
Rafael Espindola54fc2982015-06-17 17:53:31 +0000951 if (Name.empty())
952 NumberedVals.push_back(GA.get());
953
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000954 if (GVal) {
955 // Verify that types agree.
956 if (GVal->getType() != GA->getType())
957 return Error(
958 ExplicitTypeLoc,
959 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000960
Chris Lattnerac161bf2009-01-02 07:01:27 +0000961 // If they agree, just RAUW the old value with the alias and remove the
962 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000963 GVal->replaceAllUsesWith(GA.get());
964 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000965 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000966
Chris Lattnerac161bf2009-01-02 07:01:27 +0000967 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000968 if (IsAlias)
969 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
970 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000971 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000972 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000973
Rafael Espindolaaa273822014-05-09 21:49:17 +0000974 // The module owns this now
975 GA.release();
976
Chris Lattnerac161bf2009-01-02 07:01:27 +0000977 return false;
978}
979
980/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000981/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
982/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000983/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000984/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000985/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
986/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
987/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
988/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000989///
Eric Christopher536f0a92015-05-28 23:07:39 +0000990/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000991/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000992///
993bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
994 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000995 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000996 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000997 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000998 if (!isValidVisibilityForLinkage(Visibility, Linkage))
999 return Error(NameLoc,
1000 "symbol with local linkage must have default visibility");
1001
Chris Lattnerac161bf2009-01-02 07:01:27 +00001002 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001003 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001004 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001005 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001006
Craig Topper2617dcc2014-04-15 06:32:26 +00001007 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001008 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001009 ParseOptionalToken(lltok::kw_externally_initialized,
1010 IsExternallyInitialized,
1011 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001012 ParseGlobalType(IsConstant) ||
1013 ParseType(Ty, TyLoc))
1014 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001015
Chris Lattnerac161bf2009-01-02 07:01:27 +00001016 // If the linkage is specified and is external, then no initializer is
1017 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +00001018 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +00001019 if (!HasLinkage ||
1020 !GlobalValue::isValidDeclarationLinkage(
1021 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001022 if (ParseGlobalValue(Ty, Init))
1023 return true;
1024 }
1025
David Majnemer49b3d9b2015-02-16 08:41:08 +00001026 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +00001027 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001028
David Majnemer598bd052014-12-09 05:56:09 +00001029 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001030
1031 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +00001032 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +00001033 GVal = M->getNamedValue(Name);
1034 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +00001035 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +00001036 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00001037 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +00001039 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00001040 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +00001041 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001042 ForwardRefValIDs.erase(I);
1043 }
1044 }
1045
David Majnemer598bd052014-12-09 05:56:09 +00001046 GlobalVariable *GV;
1047 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001048 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1049 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001050 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001051 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +00001052 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 return Error(TyLoc,
1054 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001055
David Majnemer598bd052014-12-09 05:56:09 +00001056 GV = cast<GlobalVariable>(GVal);
1057
Chris Lattnerac161bf2009-01-02 07:01:27 +00001058 // Move the forward-reference to the correct spot in the module.
1059 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1060 }
1061
1062 if (Name.empty())
1063 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001064
Chris Lattnerac161bf2009-01-02 07:01:27 +00001065 // Set the parsed properties on the global.
1066 if (Init)
1067 GV->setInitializer(Init);
1068 GV->setConstant(IsConstant);
1069 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00001070 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001071 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001072 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001073 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001074 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001075 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001076
Chris Lattnerac161bf2009-01-02 07:01:27 +00001077 // Parse attributes on the global.
1078 while (Lex.getKind() == lltok::comma) {
1079 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001080
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 if (Lex.getKind() == lltok::kw_section) {
1082 Lex.Lex();
1083 GV->setSection(Lex.getStrVal());
1084 if (ParseToken(lltok::StringConstant, "expected global section string"))
1085 return true;
1086 } else if (Lex.getKind() == lltok::kw_align) {
1087 unsigned Alignment;
1088 if (ParseOptionalAlignment(Alignment)) return true;
1089 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001090 } else if (Lex.getKind() == lltok::MetadataVar) {
1091 if (ParseGlobalObjectMetadataAttachment(*GV))
1092 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001093 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001094 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001095 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +00001096 return true;
1097 if (C)
1098 GV->setComdat(C);
1099 else
1100 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001101 }
1102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001103
Javed Absarf3d79042017-05-11 12:28:08 +00001104 AttrBuilder Attrs;
1105 LocTy BuiltinLoc;
1106 std::vector<unsigned> FwdRefAttrGrps;
1107 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1108 return true;
1109 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1110 GV->setAttributes(AttributeSet::get(Context, Attrs));
1111 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1112 }
1113
Chris Lattnerac161bf2009-01-02 07:01:27 +00001114 return false;
1115}
1116
Bill Wendling63b88192013-02-06 06:52:58 +00001117/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001118/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001119bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001120 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001121 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001122 Lex.Lex();
1123
David Majnemerb39e22b2014-12-09 18:33:57 +00001124 if (Lex.getKind() != lltok::AttrGrpID)
1125 return TokError("expected attribute group id");
1126
Bill Wendling63b88192013-02-06 06:52:58 +00001127 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001128 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001129 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001130 Lex.Lex();
1131
1132 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001133 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001134 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001135 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001136 ParseToken(lltok::rbrace, "expected end of attribute group"))
1137 return true;
1138
Bill Wendlingb32b0412013-02-08 06:32:06 +00001139 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001140 return Error(AttrGrpLoc, "attribute group has no attributes");
1141
1142 return false;
1143}
1144
Bill Wendling8b0321d2013-02-08 00:52:31 +00001145/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001146/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001147bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1148 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001149 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001150 bool HaveError = false;
1151
1152 B.clear();
1153
Bill Wendling63b88192013-02-06 06:52:58 +00001154 while (true) {
1155 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001156 if (Token == lltok::kw_builtin)
1157 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001158 switch (Token) {
1159 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001160 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001161 return Error(Lex.getLoc(), "unterminated attribute group");
1162 case lltok::rbrace:
1163 // Finished.
1164 return false;
1165
Bill Wendlingb32b0412013-02-08 06:32:06 +00001166 case lltok::AttrGrpID: {
1167 // Allow a function to reference an attribute group:
1168 //
1169 // define void @foo() #1 { ... }
1170 if (inAttrGrp)
1171 HaveError |=
1172 Error(Lex.getLoc(),
1173 "cannot have an attribute group reference in an attribute group");
1174
1175 unsigned AttrGrpNum = Lex.getUIntVal();
1176 if (inAttrGrp) break;
1177
1178 // Save the reference to the attribute group. We'll fill it in later.
1179 FwdRefAttrGrps.push_back(AttrGrpNum);
1180 break;
1181 }
Bill Wendling63b88192013-02-06 06:52:58 +00001182 // Target-dependent attributes:
1183 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001184 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001185 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001186 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001187 }
1188
1189 // Target-independent attributes:
1190 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001191 // As a hack, we allow function alignment to be initially parsed as an
1192 // attribute on a function declaration/definition or added to an attribute
1193 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001194 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001195 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001196 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001197 if (ParseToken(lltok::equal, "expected '=' here") ||
1198 ParseUInt32(Alignment))
1199 return true;
1200 } else {
1201 if (ParseOptionalAlignment(Alignment))
1202 return true;
1203 }
Bill Wendling63b88192013-02-06 06:52:58 +00001204 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001205 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001206 }
1207 case lltok::kw_alignstack: {
1208 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001209 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001210 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001211 if (ParseToken(lltok::equal, "expected '=' here") ||
1212 ParseUInt32(Alignment))
1213 return true;
1214 } else {
1215 if (ParseOptionalStackAlignment(Alignment))
1216 return true;
1217 }
Bill Wendling63b88192013-02-06 06:52:58 +00001218 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001219 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001220 }
George Burgess IV278199f2016-04-12 01:05:35 +00001221 case lltok::kw_allocsize: {
1222 unsigned ElemSizeArg;
1223 Optional<unsigned> NumElemsArg;
1224 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1225 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1226 return true;
1227 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1228 continue;
1229 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001230 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1231 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1232 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1233 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1234 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001235 case lltok::kw_inaccessiblememonly:
1236 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1237 case lltok::kw_inaccessiblemem_or_argmemonly:
1238 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001239 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1240 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1241 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1242 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1243 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1244 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1245 case lltok::kw_noimplicitfloat:
1246 B.addAttribute(Attribute::NoImplicitFloat); break;
1247 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1248 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1249 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1250 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001251 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001252 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001253 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001254 case lltok::kw_optforfuzzing:
1255 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001256 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1257 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1258 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1259 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1260 case lltok::kw_returns_twice:
1261 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001262 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001263 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1264 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1265 case lltok::kw_sspstrong:
1266 B.addAttribute(Attribute::StackProtectStrong); break;
1267 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001268 case lltok::kw_shadowcallstack:
1269 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001270 case lltok::kw_sanitize_address:
1271 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001272 case lltok::kw_sanitize_hwaddress:
1273 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001274 case lltok::kw_sanitize_thread:
1275 B.addAttribute(Attribute::SanitizeThread); break;
1276 case lltok::kw_sanitize_memory:
1277 B.addAttribute(Attribute::SanitizeMemory); break;
Chandler Carruth664aa862018-09-04 12:38:00 +00001278 case lltok::kw_speculative_load_hardening:
1279 B.addAttribute(Attribute::SpeculativeLoadHardening);
1280 break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001281 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001282 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001283 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001284
1285 // Error handling.
1286 case lltok::kw_inreg:
1287 case lltok::kw_signext:
1288 case lltok::kw_zeroext:
1289 HaveError |=
1290 Error(Lex.getLoc(),
1291 "invalid use of attribute on a function");
1292 break;
1293 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001294 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001295 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001296 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001297 case lltok::kw_nest:
1298 case lltok::kw_noalias:
1299 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001300 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001301 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001302 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001303 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001304 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001305 HaveError |=
1306 Error(Lex.getLoc(),
1307 "invalid use of parameter-only attribute on a function");
1308 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001309 }
1310
1311 Lex.Lex();
1312 }
1313}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001314
1315//===----------------------------------------------------------------------===//
1316// GlobalValue Reference/Resolution Routines.
1317//===----------------------------------------------------------------------===//
1318
Karl Schimpf77729782015-09-03 18:06:44 +00001319static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1320 const std::string &Name) {
1321 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001322 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1323 PTy->getAddressSpace(), Name, M);
Karl Schimpf77729782015-09-03 18:06:44 +00001324 else
1325 return new GlobalVariable(*M, PTy->getElementType(), false,
1326 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1327 nullptr, GlobalVariable::NotThreadLocal,
1328 PTy->getAddressSpace());
1329}
1330
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001331Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1332 Value *Val, bool IsCall) {
1333 if (Val->getType() == Ty)
1334 return Val;
1335 // For calls we also accept variables in the program address space.
1336 Type *SuggestedTy = Ty;
1337 if (IsCall && isa<PointerType>(Ty)) {
1338 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1339 M->getDataLayout().getProgramAddressSpace());
1340 SuggestedTy = TyInProgAS;
1341 if (Val->getType() == TyInProgAS)
1342 return Val;
1343 }
1344 if (Ty->isLabelTy())
1345 Error(Loc, "'" + Name + "' is not a basic block");
1346 else
1347 Error(Loc, "'" + Name + "' defined with type '" +
1348 getTypeString(Val->getType()) + "' but expected '" +
1349 getTypeString(SuggestedTy) + "'");
1350 return nullptr;
1351}
1352
Chris Lattnerac161bf2009-01-02 07:01:27 +00001353/// GetGlobalVal - Get a value with the specified name or ID, creating a
1354/// forward reference record if needed. This can return null if the value
1355/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001356GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001357 LocTy Loc, bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001358 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001359 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001360 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001361 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001363
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364 // Look this name up in the normal function symbol table.
1365 GlobalValue *Val =
1366 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001367
Chris Lattnerac161bf2009-01-02 07:01:27 +00001368 // If this is a forward reference for the value, see if we already created a
1369 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001370 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001371 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372 if (I != ForwardRefVals.end())
1373 Val = I->second.first;
1374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001375
Chris Lattnerac161bf2009-01-02 07:01:27 +00001376 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001377 if (Val)
1378 return cast_or_null<GlobalValue>(
1379 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001380
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001382 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001383 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1384 return FwdVal;
1385}
1386
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001387GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1388 bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001389 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001390 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001392 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001393 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001394
Craig Topper2617dcc2014-04-15 06:32:26 +00001395 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001396
Chris Lattnerac161bf2009-01-02 07:01:27 +00001397 // If this is a forward reference for the value, see if we already created a
1398 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001399 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001400 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001401 if (I != ForwardRefValIDs.end())
1402 Val = I->second.first;
1403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001404
Chris Lattnerac161bf2009-01-02 07:01:27 +00001405 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001406 if (Val)
1407 return cast_or_null<GlobalValue>(
1408 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001409
Chris Lattnerac161bf2009-01-02 07:01:27 +00001410 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001411 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001412 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1413 return FwdVal;
1414}
1415
Chris Lattnerac161bf2009-01-02 07:01:27 +00001416//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001417// Comdat Reference/Resolution Routines.
1418//===----------------------------------------------------------------------===//
1419
1420Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1421 // Look this name up in the comdat symbol table.
1422 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1423 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1424 if (I != ComdatSymTab.end())
1425 return &I->second;
1426
1427 // Otherwise, create a new forward reference for this value and remember it.
1428 Comdat *C = M->getOrInsertComdat(Name);
1429 ForwardRefComdats[Name] = Loc;
1430 return C;
1431}
1432
David Majnemerdad0a642014-06-27 18:19:56 +00001433//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001434// Helper Routines.
1435//===----------------------------------------------------------------------===//
1436
1437/// ParseToken - If the current token has the specified kind, eat it and return
1438/// success. Otherwise, emit the specified error and return failure.
1439bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1440 if (Lex.getKind() != T)
1441 return TokError(ErrMsg);
1442 Lex.Lex();
1443 return false;
1444}
1445
Chris Lattner3822f632009-01-02 08:05:26 +00001446/// ParseStringConstant
1447/// ::= StringConstant
1448bool LLParser::ParseStringConstant(std::string &Result) {
1449 if (Lex.getKind() != lltok::StringConstant)
1450 return TokError("expected string constant");
1451 Result = Lex.getStrVal();
1452 Lex.Lex();
1453 return false;
1454}
1455
1456/// ParseUInt32
1457/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001458bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001459 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1460 return TokError("expected integer");
1461 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1462 if (Val64 != unsigned(Val64))
1463 return TokError("expected 32-bit integer (too large)");
1464 Val = Val64;
1465 Lex.Lex();
1466 return false;
1467}
1468
Hal Finkelb0407ba2014-07-18 15:51:28 +00001469/// ParseUInt64
1470/// ::= uint64
1471bool LLParser::ParseUInt64(uint64_t &Val) {
1472 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1473 return TokError("expected integer");
1474 Val = Lex.getAPSIntVal().getLimitedValue();
1475 Lex.Lex();
1476 return false;
1477}
1478
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001479/// ParseTLSModel
1480/// := 'localdynamic'
1481/// := 'initialexec'
1482/// := 'localexec'
1483bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1484 switch (Lex.getKind()) {
1485 default:
1486 return TokError("expected localdynamic, initialexec or localexec");
1487 case lltok::kw_localdynamic:
1488 TLM = GlobalVariable::LocalDynamicTLSModel;
1489 break;
1490 case lltok::kw_initialexec:
1491 TLM = GlobalVariable::InitialExecTLSModel;
1492 break;
1493 case lltok::kw_localexec:
1494 TLM = GlobalVariable::LocalExecTLSModel;
1495 break;
1496 }
1497
1498 Lex.Lex();
1499 return false;
1500}
1501
1502/// ParseOptionalThreadLocal
1503/// := /*empty*/
1504/// := 'thread_local'
1505/// := 'thread_local' '(' tlsmodel ')'
1506bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1507 TLM = GlobalVariable::NotThreadLocal;
1508 if (!EatIfPresent(lltok::kw_thread_local))
1509 return false;
1510
1511 TLM = GlobalVariable::GeneralDynamicTLSModel;
1512 if (Lex.getKind() == lltok::lparen) {
1513 Lex.Lex();
1514 return ParseTLSModel(TLM) ||
1515 ParseToken(lltok::rparen, "expected ')' after thread local model");
1516 }
1517 return false;
1518}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001519
1520/// ParseOptionalAddrSpace
1521/// := /*empty*/
1522/// := 'addrspace' '(' uint32 ')'
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001523bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1524 AddrSpace = DefaultAS;
Chris Lattner3822f632009-01-02 08:05:26 +00001525 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001526 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001527 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001528 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001529 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001530}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001531
Artur Pilipenko17376c42015-08-03 14:31:49 +00001532/// ParseStringAttribute
1533/// := StringConstant
1534/// := StringConstant '=' StringConstant
1535bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1536 std::string Attr = Lex.getStrVal();
1537 Lex.Lex();
1538 std::string Val;
1539 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1540 return true;
1541 B.addAttribute(Attr, Val);
1542 return false;
1543}
1544
Bill Wendling34c2eb22012-12-04 23:40:58 +00001545/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1546bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1547 bool HaveError = false;
1548
1549 B.clear();
1550
Eugene Zelenko1804a772016-08-25 00:45:04 +00001551 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001552 lltok::Kind Token = Lex.getKind();
1553 switch (Token) {
1554 default: // End of attributes.
1555 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001556 case lltok::StringConstant: {
1557 if (ParseStringAttribute(B))
1558 return true;
1559 continue;
1560 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001561 case lltok::kw_align: {
1562 unsigned Alignment;
1563 if (ParseOptionalAlignment(Alignment))
1564 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001565 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001566 continue;
1567 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001568 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001569 case lltok::kw_dereferenceable: {
1570 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001571 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001572 return true;
1573 B.addDereferenceableAttr(Bytes);
1574 continue;
1575 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001576 case lltok::kw_dereferenceable_or_null: {
1577 uint64_t Bytes;
1578 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1579 return true;
1580 B.addDereferenceableOrNullAttr(Bytes);
1581 continue;
1582 }
Reid Klecknera534a382013-12-19 02:14:12 +00001583 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001584 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1585 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1586 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1587 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001588 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001589 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1590 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001591 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001592 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1593 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001594 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001595 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001596 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001597 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001598
Stephen Lin7577ed52013-04-20 13:16:13 +00001599 case lltok::kw_alignstack:
1600 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001601 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001602 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001603 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001604 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001605 case lltok::kw_minsize:
1606 case lltok::kw_naked:
1607 case lltok::kw_nobuiltin:
1608 case lltok::kw_noduplicate:
1609 case lltok::kw_noimplicitfloat:
1610 case lltok::kw_noinline:
1611 case lltok::kw_nonlazybind:
1612 case lltok::kw_noredzone:
1613 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001614 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001615 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001616 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001617 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001618 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001619 case lltok::kw_returns_twice:
1620 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001621 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001622 case lltok::kw_sanitize_memory:
1623 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001624 case lltok::kw_speculative_load_hardening:
Stephen Lin7577ed52013-04-20 13:16:13 +00001625 case lltok::kw_ssp:
1626 case lltok::kw_sspreq:
1627 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001628 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001629 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001630 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001631 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001632 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1633 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001634 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001635
Bill Wendling34c2eb22012-12-04 23:40:58 +00001636 Lex.Lex();
1637 }
1638}
1639
1640/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1641bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1642 bool HaveError = false;
1643
1644 B.clear();
1645
Eugene Zelenko1804a772016-08-25 00:45:04 +00001646 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001647 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001648 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001649 default: // End of attributes.
1650 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001651 case lltok::StringConstant: {
1652 if (ParseStringAttribute(B))
1653 return true;
1654 continue;
1655 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001656 case lltok::kw_dereferenceable: {
1657 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001658 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001659 return true;
1660 B.addDereferenceableAttr(Bytes);
1661 continue;
1662 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001663 case lltok::kw_dereferenceable_or_null: {
1664 uint64_t Bytes;
1665 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1666 return true;
1667 B.addDereferenceableOrNullAttr(Bytes);
1668 continue;
1669 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001670 case lltok::kw_align: {
1671 unsigned Alignment;
1672 if (ParseOptionalAlignment(Alignment))
1673 return true;
1674 B.addAlignmentAttr(Alignment);
1675 continue;
1676 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001677 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1678 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001679 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001680 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1681 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001682
Bill Wendling34c2eb22012-12-04 23:40:58 +00001683 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001684 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001685 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001686 case lltok::kw_nest:
1687 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001688 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001689 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001690 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001691 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001692 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001693 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001694
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001695 case lltok::kw_alignstack:
1696 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001697 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001698 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001699 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001700 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001701 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001702 case lltok::kw_minsize:
1703 case lltok::kw_naked:
1704 case lltok::kw_nobuiltin:
1705 case lltok::kw_noduplicate:
1706 case lltok::kw_noimplicitfloat:
1707 case lltok::kw_noinline:
1708 case lltok::kw_nonlazybind:
1709 case lltok::kw_noredzone:
1710 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001711 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001712 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001713 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001714 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001715 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001716 case lltok::kw_returns_twice:
1717 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001718 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001719 case lltok::kw_sanitize_memory:
1720 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001721 case lltok::kw_speculative_load_hardening:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001722 case lltok::kw_ssp:
1723 case lltok::kw_sspreq:
1724 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001725 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001726 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001727 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001728 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001729 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001730 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001731
1732 case lltok::kw_readnone:
1733 case lltok::kw_readonly:
1734 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001735 }
1736
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 Lex.Lex();
1738 }
1739}
1740
Rafael Espindolac6269912016-05-10 17:16:45 +00001741static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1742 HasLinkage = true;
1743 switch (Kind) {
1744 default:
1745 HasLinkage = false;
1746 return GlobalValue::ExternalLinkage;
1747 case lltok::kw_private:
1748 return GlobalValue::PrivateLinkage;
1749 case lltok::kw_internal:
1750 return GlobalValue::InternalLinkage;
1751 case lltok::kw_weak:
1752 return GlobalValue::WeakAnyLinkage;
1753 case lltok::kw_weak_odr:
1754 return GlobalValue::WeakODRLinkage;
1755 case lltok::kw_linkonce:
1756 return GlobalValue::LinkOnceAnyLinkage;
1757 case lltok::kw_linkonce_odr:
1758 return GlobalValue::LinkOnceODRLinkage;
1759 case lltok::kw_available_externally:
1760 return GlobalValue::AvailableExternallyLinkage;
1761 case lltok::kw_appending:
1762 return GlobalValue::AppendingLinkage;
1763 case lltok::kw_common:
1764 return GlobalValue::CommonLinkage;
1765 case lltok::kw_extern_weak:
1766 return GlobalValue::ExternalWeakLinkage;
1767 case lltok::kw_external:
1768 return GlobalValue::ExternalLinkage;
1769 }
1770}
1771
Chris Lattnerac161bf2009-01-02 07:01:27 +00001772/// ParseOptionalLinkage
1773/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001774/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001775/// ::= 'internal'
1776/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001777/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001778/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001779/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001780/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001781/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001783/// ::= 'extern_weak'
1784/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001785bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1786 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001787 unsigned &DLLStorageClass,
1788 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001789 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1790 if (HasLinkage)
1791 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001792 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001793 ParseOptionalVisibility(Visibility);
1794 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001795
1796 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1797 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1798 }
1799
Chris Lattnerac161bf2009-01-02 07:01:27 +00001800 return false;
1801}
1802
Sean Fertilec70d28b2017-10-26 15:00:26 +00001803void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1804 switch (Lex.getKind()) {
1805 default:
1806 DSOLocal = false;
1807 break;
1808 case lltok::kw_dso_local:
1809 DSOLocal = true;
1810 Lex.Lex();
1811 break;
1812 case lltok::kw_dso_preemptable:
1813 DSOLocal = false;
1814 Lex.Lex();
1815 break;
1816 }
1817}
1818
Chris Lattnerac161bf2009-01-02 07:01:27 +00001819/// ParseOptionalVisibility
1820/// ::= /*empty*/
1821/// ::= 'default'
1822/// ::= 'hidden'
1823/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001824///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001825void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001826 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001827 default:
1828 Res = GlobalValue::DefaultVisibility;
1829 return;
1830 case lltok::kw_default:
1831 Res = GlobalValue::DefaultVisibility;
1832 break;
1833 case lltok::kw_hidden:
1834 Res = GlobalValue::HiddenVisibility;
1835 break;
1836 case lltok::kw_protected:
1837 Res = GlobalValue::ProtectedVisibility;
1838 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839 }
1840 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001841}
1842
Nico Rieck7157bb72014-01-14 15:22:47 +00001843/// ParseOptionalDLLStorageClass
1844/// ::= /*empty*/
1845/// ::= 'dllimport'
1846/// ::= 'dllexport'
1847///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001848void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001849 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001850 default:
1851 Res = GlobalValue::DefaultStorageClass;
1852 return;
1853 case lltok::kw_dllimport:
1854 Res = GlobalValue::DLLImportStorageClass;
1855 break;
1856 case lltok::kw_dllexport:
1857 Res = GlobalValue::DLLExportStorageClass;
1858 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001859 }
1860 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001861}
1862
Chris Lattnerac161bf2009-01-02 07:01:27 +00001863/// ParseOptionalCallingConv
1864/// ::= /*empty*/
1865/// ::= 'ccc'
1866/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001867/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868/// ::= 'coldcc'
1869/// ::= 'x86_stdcallcc'
1870/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001871/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001872/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001873/// ::= 'arm_apcscc'
1874/// ::= 'arm_aapcscc'
1875/// ::= 'arm_aapcs_vfpcc'
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001876/// ::= 'aarch64_vector_pcs'
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;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001920 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001921 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001922 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1923 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001924 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1925 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001926 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1927 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001928 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001929 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001930 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001931 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001932 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001933 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1934 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001935 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001936 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001937 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001938 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1939 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001940 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001941 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001942 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001943 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001944 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001945 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1946 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1947 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001948 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001949 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001950 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001951 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001952 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001953 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001954
Chris Lattnerac161bf2009-01-02 07:01:27 +00001955 Lex.Lex();
1956 return false;
1957}
1958
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001959/// ParseMetadataAttachment
1960/// ::= !dbg !42
1961bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1962 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1963
1964 std::string Name = Lex.getStrVal();
1965 Kind = M->getMDKindID(Name);
1966 Lex.Lex();
1967
1968 return ParseMDNode(MD);
1969}
1970
Chris Lattner5c427632009-12-30 05:31:19 +00001971/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001972/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001973bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001974 do {
1975 if (Lex.getKind() != lltok::MetadataVar)
1976 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001977
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001978 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001979 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001980 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001981 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001982
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001983 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001984 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001985 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001986
Chris Lattner596760d2009-12-29 21:25:40 +00001987 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001988 } while (EatIfPresent(lltok::comma));
1989 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001990}
1991
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001992/// ParseGlobalObjectMetadataAttachment
1993/// ::= !dbg !57
1994bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1995 unsigned MDK;
1996 MDNode *N;
1997 if (ParseMetadataAttachment(MDK, N))
1998 return true;
1999
Peter Collingbourne382d81c2016-06-01 01:17:57 +00002000 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002001 return false;
2002}
2003
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002004/// ParseOptionalFunctionMetadata
2005/// ::= (!dbg !57)*
2006bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002007 while (Lex.getKind() == lltok::MetadataVar)
2008 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002009 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002010 return false;
2011}
2012
Chris Lattnerac161bf2009-01-02 07:01:27 +00002013/// ParseOptionalAlignment
2014/// ::= /* empty */
2015/// ::= 'align' 4
2016bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2017 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002018 if (!EatIfPresent(lltok::kw_align))
2019 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00002020 LocTy AlignLoc = Lex.getLoc();
2021 if (ParseUInt32(Alignment)) return true;
2022 if (!isPowerOf2_32(Alignment))
2023 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00002024 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00002025 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00002026 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002027}
2028
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002029/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00002030/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002031/// ::= AttrKind '(' 4 ')'
2032///
2033/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2034bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2035 uint64_t &Bytes) {
2036 assert((AttrKind == lltok::kw_dereferenceable ||
2037 AttrKind == lltok::kw_dereferenceable_or_null) &&
2038 "contract!");
2039
Hal Finkelb0407ba2014-07-18 15:51:28 +00002040 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002041 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00002042 return false;
2043 LocTy ParenLoc = Lex.getLoc();
2044 if (!EatIfPresent(lltok::lparen))
2045 return Error(ParenLoc, "expected '('");
2046 LocTy DerefLoc = Lex.getLoc();
2047 if (ParseUInt64(Bytes)) return true;
2048 ParenLoc = Lex.getLoc();
2049 if (!EatIfPresent(lltok::rparen))
2050 return Error(ParenLoc, "expected ')'");
2051 if (!Bytes)
2052 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2053 return false;
2054}
2055
Chris Lattnerb2f39502009-12-30 05:44:30 +00002056/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002057/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00002058/// ::= ',' align 4
2059///
2060/// This returns with AteExtraComma set to true if it ate an excess comma at the
2061/// end.
2062bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2063 bool &AteExtraComma) {
2064 AteExtraComma = false;
2065 while (EatIfPresent(lltok::comma)) {
2066 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00002067 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00002068 AteExtraComma = true;
2069 return false;
2070 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002071
Chris Lattner95b0ff42010-04-23 00:50:50 +00002072 if (Lex.getKind() != lltok::kw_align)
2073 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00002074
Chris Lattner95b0ff42010-04-23 00:50:50 +00002075 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00002076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002077
Devang Patelea8a4b92009-09-17 23:04:48 +00002078 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079}
2080
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002081/// ParseOptionalCommaAddrSpace
2082/// ::=
2083/// ::= ',' addrspace(1)
2084///
2085/// This returns with AteExtraComma set to true if it ate an excess comma at the
2086/// end.
2087bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2088 LocTy &Loc,
2089 bool &AteExtraComma) {
2090 AteExtraComma = false;
2091 while (EatIfPresent(lltok::comma)) {
2092 // Metadata at the end is an early exit.
2093 if (Lex.getKind() == lltok::MetadataVar) {
2094 AteExtraComma = true;
2095 return false;
2096 }
2097
2098 Loc = Lex.getLoc();
2099 if (Lex.getKind() != lltok::kw_addrspace)
2100 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2101
2102 if (ParseOptionalAddrSpace(AddrSpace))
2103 return true;
2104 }
2105
2106 return false;
2107}
2108
George Burgess IV278199f2016-04-12 01:05:35 +00002109bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2110 Optional<unsigned> &HowManyArg) {
2111 Lex.Lex();
2112
2113 auto StartParen = Lex.getLoc();
2114 if (!EatIfPresent(lltok::lparen))
2115 return Error(StartParen, "expected '('");
2116
2117 if (ParseUInt32(BaseSizeArg))
2118 return true;
2119
2120 if (EatIfPresent(lltok::comma)) {
2121 auto HowManyAt = Lex.getLoc();
2122 unsigned HowMany;
2123 if (ParseUInt32(HowMany))
2124 return true;
2125 if (HowMany == BaseSizeArg)
2126 return Error(HowManyAt,
2127 "'allocsize' indices can't refer to the same parameter");
2128 HowManyArg = HowMany;
2129 } else
2130 HowManyArg = None;
2131
2132 auto EndParen = Lex.getLoc();
2133 if (!EatIfPresent(lltok::rparen))
2134 return Error(EndParen, "expected ')'");
2135 return false;
2136}
2137
Eli Friedmanfee02c62011-07-25 23:16:38 +00002138/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002139/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002140/// else: ::=
2141///
2142/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002143bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002144 AtomicOrdering &Ordering) {
2145 if (!isAtomic)
2146 return false;
2147
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002148 return ParseScope(SSID) || ParseOrdering(Ordering);
2149}
Tim Northovere94a5182014-03-11 10:48:52 +00002150
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002151/// ParseScope
2152/// ::= syncscope("singlethread" | "<target scope>")?
2153///
2154/// This sets synchronization scope ID to the ID of the parsed value.
2155bool LLParser::ParseScope(SyncScope::ID &SSID) {
2156 SSID = SyncScope::System;
2157 if (EatIfPresent(lltok::kw_syncscope)) {
2158 auto StartParenAt = Lex.getLoc();
2159 if (!EatIfPresent(lltok::lparen))
2160 return Error(StartParenAt, "Expected '(' in syncscope");
2161
2162 std::string SSN;
2163 auto SSNAt = Lex.getLoc();
2164 if (ParseStringConstant(SSN))
2165 return Error(SSNAt, "Expected synchronization scope name");
2166
2167 auto EndParenAt = Lex.getLoc();
2168 if (!EatIfPresent(lltok::rparen))
2169 return Error(EndParenAt, "Expected ')' in syncscope");
2170
2171 SSID = Context.getOrInsertSyncScopeID(SSN);
2172 }
2173
2174 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002175}
2176
2177/// ParseOrdering
2178/// ::= AtomicOrdering
2179///
2180/// This sets Ordering to the parsed value.
2181bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002182 switch (Lex.getKind()) {
2183 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002184 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2185 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2186 // Not specified yet:
2187 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2188 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2189 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2190 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2191 case lltok::kw_seq_cst:
2192 Ordering = AtomicOrdering::SequentiallyConsistent;
2193 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002194 }
2195 Lex.Lex();
2196 return false;
2197}
2198
Charles Davisbe5557e2010-02-12 00:31:15 +00002199/// ParseOptionalStackAlignment
2200/// ::= /* empty */
2201/// ::= 'alignstack' '(' 4 ')'
2202bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2203 Alignment = 0;
2204 if (!EatIfPresent(lltok::kw_alignstack))
2205 return false;
2206 LocTy ParenLoc = Lex.getLoc();
2207 if (!EatIfPresent(lltok::lparen))
2208 return Error(ParenLoc, "expected '('");
2209 LocTy AlignLoc = Lex.getLoc();
2210 if (ParseUInt32(Alignment)) return true;
2211 ParenLoc = Lex.getLoc();
2212 if (!EatIfPresent(lltok::rparen))
2213 return Error(ParenLoc, "expected ')'");
2214 if (!isPowerOf2_32(Alignment))
2215 return Error(AlignLoc, "stack alignment is not a power of two");
2216 return false;
2217}
Devang Patelea8a4b92009-09-17 23:04:48 +00002218
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002219/// ParseIndexList - This parses the index list for an insert/extractvalue
2220/// instruction. This sets AteExtraComma in the case where we eat an extra
2221/// comma at the end of the line and find that it is followed by metadata.
2222/// Clients that don't allow metadata can call the version of this function that
2223/// only takes one argument.
2224///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225/// ParseIndexList
2226/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002227///
2228bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2229 bool &AteExtraComma) {
2230 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002231
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 if (Lex.getKind() != lltok::comma)
2233 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Chris Lattner3822f632009-01-02 08:05:26 +00002235 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002236 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002237 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002238 AteExtraComma = true;
2239 return false;
2240 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002241 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002242 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 Indices.push_back(Idx);
2244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002245
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 return false;
2247}
2248
2249//===----------------------------------------------------------------------===//
2250// Type Parsing.
2251//===----------------------------------------------------------------------===//
2252
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002253/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002254bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002255 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256 switch (Lex.getKind()) {
2257 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002258 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002260 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002262 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002265 // Type ::= StructType
2266 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 return true;
2268 break;
2269 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002270 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 Lex.Lex(); // eat the lsquare.
2272 if (ParseArrayVectorType(Result, false))
2273 return true;
2274 break;
2275 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002276 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002277 Lex.Lex();
2278 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002279 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002280 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 } else if (ParseArrayVectorType(Result, true))
2283 return true;
2284 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002285 case lltok::LocalVar: {
2286 // Type ::= %foo
2287 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002288
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289 // If the type hasn't been defined yet, create a forward definition and
2290 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002291 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002292 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002293 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002295 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296 Lex.Lex();
2297 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002298 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 case lltok::LocalVarID: {
2301 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002302 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002303
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002304 // If the type hasn't been defined yet, create a forward definition and
2305 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002306 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002307 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002310 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311 Lex.Lex();
2312 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 }
2314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
2316 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002317 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002318 switch (Lex.getKind()) {
2319 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002320 default:
2321 if (!AllowVoid && Result->isVoidTy())
2322 return Error(TypeLoc, "void type only allowed for function results");
2323 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002325 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002327 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002329 if (Result->isVoidTy())
2330 return TokError("pointers to void are invalid - use i8* instead");
2331 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002332 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002333 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 Lex.Lex();
2335 break;
2336
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002337 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002339 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002340 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002342 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002343 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002344 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002345 unsigned AddrSpace;
2346 if (ParseOptionalAddrSpace(AddrSpace) ||
2347 ParseToken(lltok::star, "expected '*' in address space"))
2348 return true;
2349
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002350 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351 break;
2352 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002353
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2355 case lltok::lparen:
2356 if (ParseFunctionType(Result))
2357 return true;
2358 break;
2359 }
2360 }
2361}
2362
2363/// ParseParameterList
2364/// ::= '(' ')'
2365/// ::= '(' Arg (',' Arg)* ')'
2366/// Arg
2367/// ::= Type OptionalAttributes Value OptionalAttributes
2368bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002369 PerFunctionState &PFS, bool IsMustTailCall,
2370 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 if (ParseToken(lltok::lparen, "expected '(' in call"))
2372 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002373
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 while (Lex.getKind() != lltok::rparen) {
2375 // If this isn't the first argument, we need a comma.
2376 if (!ArgList.empty() &&
2377 ParseToken(lltok::comma, "expected ',' in argument list"))
2378 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002379
Reid Kleckner83498642014-08-26 00:33:28 +00002380 // Parse an ellipsis if this is a musttail call in a variadic function.
2381 if (Lex.getKind() == lltok::dotdotdot) {
2382 const char *Msg = "unexpected ellipsis in argument list for ";
2383 if (!IsMustTailCall)
2384 return TokError(Twine(Msg) + "non-musttail call");
2385 if (!InVarArgsFunc)
2386 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2387 Lex.Lex(); // Lex the '...', it is purely for readability.
2388 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2389 }
2390
Chris Lattnerac161bf2009-01-02 07:01:27 +00002391 // Parse the argument.
2392 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002393 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002394 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002396 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002398
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002399 if (ArgTy->isMetadataTy()) {
2400 if (ParseMetadataAsValue(V, PFS))
2401 return true;
2402 } else {
2403 // Otherwise, handle normal operands.
2404 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2405 return true;
2406 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002407 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002408 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409 }
2410
Reid Kleckner83498642014-08-26 00:33:28 +00002411 if (IsMustTailCall && InVarArgsFunc)
2412 return TokError("expected '...' at end of argument list for musttail call "
2413 "in varargs function");
2414
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 Lex.Lex(); // Lex the ')'.
2416 return false;
2417}
2418
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002419/// ParseOptionalOperandBundles
2420/// ::= /*empty*/
2421/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2422///
2423/// OperandBundle
2424/// ::= bundle-tag '(' ')'
2425/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2426///
2427/// bundle-tag ::= String Constant
2428bool LLParser::ParseOptionalOperandBundles(
2429 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2430 LocTy BeginLoc = Lex.getLoc();
2431 if (!EatIfPresent(lltok::lsquare))
2432 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002434 while (Lex.getKind() != lltok::rsquare) {
2435 // If this isn't the first operand bundle, we need a comma.
2436 if (!BundleList.empty() &&
2437 ParseToken(lltok::comma, "expected ',' in input list"))
2438 return true;
2439
2440 std::string Tag;
2441 if (ParseStringConstant(Tag))
2442 return true;
2443
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002444 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2445 return true;
2446
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002447 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002448 while (Lex.getKind() != lltok::rparen) {
2449 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002450 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002451 ParseToken(lltok::comma, "expected ',' in input list"))
2452 return true;
2453
2454 Type *Ty = nullptr;
2455 Value *Input = nullptr;
2456 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2457 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002458 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002459 }
2460
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002461 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2462
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002463 Lex.Lex(); // Lex the ')'.
2464 }
2465
2466 if (BundleList.empty())
2467 return Error(BeginLoc, "operand bundle set must not be empty");
2468
2469 Lex.Lex(); // Lex the ']'.
2470 return false;
2471}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472
Chris Lattner2ed06b42009-01-05 18:34:07 +00002473/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002474/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475/// ::= '(' ArgTypeListI ')'
2476/// ArgTypeListI
2477/// ::= /*empty*/
2478/// ::= '...'
2479/// ::= ArgTypeList ',' '...'
2480/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002481///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002482bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2483 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484 isVarArg = false;
2485 assert(Lex.getKind() == lltok::lparen);
2486 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 if (Lex.getKind() == lltok::rparen) {
2489 // empty
2490 } else if (Lex.getKind() == lltok::dotdotdot) {
2491 isVarArg = true;
2492 Lex.Lex();
2493 } else {
2494 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002495 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002496 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002499 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002500 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002501
Chris Lattnerfdd87902009-10-05 05:54:46 +00002502 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002503 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerdef19492011-06-17 06:36:20 +00002505 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002506 Name = Lex.getStrVal();
2507 Lex.Lex();
2508 }
Chris Lattner3822f632009-01-02 08:05:26 +00002509
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002510 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002511 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002512
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002513 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002514 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002515 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002516
Chris Lattner3822f632009-01-02 08:05:26 +00002517 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002518 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002519 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 break;
2522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002523
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 // Otherwise must be an argument type.
2525 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002526 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002527
Chris Lattnerfdd87902009-10-05 05:54:46 +00002528 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002529 return Error(TypeLoc, "argument can not have void type");
2530
Chris Lattnerdef19492011-06-17 06:36:20 +00002531 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002532 Name = Lex.getStrVal();
2533 Lex.Lex();
2534 } else {
2535 Name = "";
2536 }
Chris Lattner3822f632009-01-02 08:05:26 +00002537
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002538 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002539 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002540
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002541 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002542 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002543 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 }
2545 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002546
Chris Lattner3822f632009-01-02 08:05:26 +00002547 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002549
Chris Lattnerac161bf2009-01-02 07:01:27 +00002550/// ParseFunctionType
2551/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002552bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 assert(Lex.getKind() == lltok::lparen);
2554
Chris Lattnerce473c72009-01-05 08:04:33 +00002555 if (!FunctionType::isValidReturnType(Result))
2556 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002557
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002558 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002560 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002562
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 // Reject names on the arguments lists.
2564 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2565 if (!ArgList[i].Name.empty())
2566 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002567 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002568 return Error(ArgList[i].Loc,
2569 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002571
Jay Foadb804a2b2011-07-12 14:06:48 +00002572 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002573 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002574 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002576 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 return false;
2578}
2579
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002580/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2581/// other structs.
2582bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2583 SmallVector<Type*, 8> Elts;
2584 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002585
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002586 Result = StructType::get(Context, Elts, Packed);
2587 return false;
2588}
2589
2590/// ParseStructDefinition - Parse a struct in a 'type' definition.
2591bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2592 std::pair<Type*, LocTy> &Entry,
2593 Type *&ResultTy) {
2594 // If the type was already defined, diagnose the redefinition.
2595 if (Entry.first && !Entry.second.isValid())
2596 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002597
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002598 // If we have opaque, just return without filling in the definition for the
2599 // struct. This counts as a definition as far as the .ll file goes.
2600 if (EatIfPresent(lltok::kw_opaque)) {
2601 // This type is being defined, so clear the location to indicate this.
2602 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002603
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002604 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002605 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002606 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002607 ResultTy = Entry.first;
2608 return false;
2609 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002610
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002611 // If the type starts with '<', then it is either a packed struct or a vector.
2612 bool isPacked = EatIfPresent(lltok::less);
2613
2614 // If we don't have a struct, then we have a random type alias, which we
2615 // accept for compatibility with old files. These types are not allowed to be
2616 // forward referenced and not allowed to be recursive.
2617 if (Lex.getKind() != lltok::lbrace) {
2618 if (Entry.first)
2619 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002620
Craig Topper2617dcc2014-04-15 06:32:26 +00002621 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002622 if (isPacked)
2623 return ParseArrayVectorType(ResultTy, true);
2624 return ParseType(ResultTy);
2625 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002626
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002627 // This type is being defined, so clear the location to indicate this.
2628 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002629
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002630 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002631 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002632 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002634 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002635
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002636 SmallVector<Type*, 8> Body;
2637 if (ParseStructBody(Body) ||
2638 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2639 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002640
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002641 STy->setBody(Body, isPacked);
2642 ResultTy = STy;
2643 return false;
2644}
2645
Chris Lattnerac161bf2009-01-02 07:01:27 +00002646/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002647/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002649/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002651/// ::= '<' '{' Type (',' Type)* '}' '>'
2652bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 assert(Lex.getKind() == lltok::lbrace);
2654 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002655
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002656 // Handle the empty struct.
2657 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659
Chris Lattnerf880ca22009-03-09 04:49:14 +00002660 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002661 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002662 if (ParseType(Ty)) return true;
2663 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002664
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002665 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002666 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002667
Chris Lattner3822f632009-01-02 08:05:26 +00002668 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002669 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002670 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002671
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002672 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002673 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002674
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002675 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002676 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002677
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002678 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002679}
2680
2681/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2682/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002683/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002684/// ::= '[' APSINTVAL 'x' Types ']'
2685/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002686bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2688 Lex.getAPSIntVal().getBitWidth() > 64)
2689 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 LocTy SizeLoc = Lex.getLoc();
2692 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002693 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002694
Chris Lattner3822f632009-01-02 08:05:26 +00002695 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2696 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002697
2698 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002699 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002700 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002701
Chris Lattner3822f632009-01-02 08:05:26 +00002702 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2703 "expected end of sequential type"))
2704 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002707 if (Size == 0)
2708 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 if ((unsigned)Size != Size)
2710 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002711 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002712 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002713 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002714 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002715 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002717 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002718 }
2719 return false;
2720}
2721
2722//===----------------------------------------------------------------------===//
2723// Function Semantic Analysis.
2724//===----------------------------------------------------------------------===//
2725
Chris Lattner3432c622009-10-28 03:39:23 +00002726LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2727 int functionNumber)
2728 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002729
2730 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002731 for (Argument &A : F.args())
2732 if (!A.hasName())
2733 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734}
2735
2736LLParser::PerFunctionState::~PerFunctionState() {
2737 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002738
David Blaikie9ebdc692015-09-21 21:07:50 +00002739 for (const auto &P : ForwardRefVals) {
2740 if (isa<BasicBlock>(P.second.first))
2741 continue;
2742 P.second.first->replaceAllUsesWith(
2743 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002744 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002745 }
2746
2747 for (const auto &P : ForwardRefValIDs) {
2748 if (isa<BasicBlock>(P.second.first))
2749 continue;
2750 P.second.first->replaceAllUsesWith(
2751 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002752 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002753 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002754}
2755
Chris Lattner3432c622009-10-28 03:39:23 +00002756bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002757 if (!ForwardRefVals.empty())
2758 return P.Error(ForwardRefVals.begin()->second.second,
2759 "use of undefined value '%" + ForwardRefVals.begin()->first +
2760 "'");
2761 if (!ForwardRefValIDs.empty())
2762 return P.Error(ForwardRefValIDs.begin()->second.second,
2763 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002764 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 return false;
2766}
2767
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768/// GetVal - Get a value with the specified name or ID, creating a
2769/// forward reference record if needed. This can return null if the value
2770/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002771Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002772 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002773 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002774 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 // If this is a forward reference for the value, see if we already created a
2777 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002778 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002779 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 if (I != ForwardRefVals.end())
2781 Val = I->second.first;
2782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002783
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002785 if (Val)
2786 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002789 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002791 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002793
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794 // Otherwise, create a new forward reference for this value and remember it.
2795 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002796 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002797 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002798 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002799 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002800 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002801
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2803 return FwdVal;
2804}
2805
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002806Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2807 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002809 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002810
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 // If this is a forward reference for the value, see if we already created a
2812 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002813 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002814 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 if (I != ForwardRefValIDs.end())
2816 Val = I->second.first;
2817 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002818
Chris Lattnerac161bf2009-01-02 07:01:27 +00002819 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002820 if (Val)
2821 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002822
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002823 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002825 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002827
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 // Otherwise, create a new forward reference for this value and remember it.
2829 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002830 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002831 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002832 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002833 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002834 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002835
Chris Lattnerac161bf2009-01-02 07:01:27 +00002836 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2837 return FwdVal;
2838}
2839
2840/// SetInstName - After an instruction is parsed and inserted into its
2841/// basic block, this installs its name.
2842bool LLParser::PerFunctionState::SetInstName(int NameID,
2843 const std::string &NameStr,
2844 LocTy NameLoc, Instruction *Inst) {
2845 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002846 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 if (NameID != -1 || !NameStr.empty())
2848 return P.Error(NameLoc, "instructions returning void cannot have a name");
2849 return false;
2850 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002851
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 // If this was a numbered instruction, verify that the instruction is the
2853 // expected value and resolve any forward references.
2854 if (NameStr.empty()) {
2855 // If neither a name nor an ID was specified, just use the next ID.
2856 if (NameID == -1)
2857 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002858
Chris Lattnerac161bf2009-01-02 07:01:27 +00002859 if (unsigned(NameID) != NumberedVals.size())
2860 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002861 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002862
David Blaikie9ebdc692015-09-21 21:07:50 +00002863 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002864 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002865 Value *Sentinel = FI->second.first;
2866 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002867 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002868 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002869
2870 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002871 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002872 ForwardRefValIDs.erase(FI);
2873 }
2874
2875 NumberedVals.push_back(Inst);
2876 return false;
2877 }
2878
2879 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002880 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002881 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002882 Value *Sentinel = FI->second.first;
2883 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002884 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002885 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002886
2887 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002888 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 ForwardRefVals.erase(FI);
2890 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002891
Chris Lattnerac161bf2009-01-02 07:01:27 +00002892 // Set the name on the instruction.
2893 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002894
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002895 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002896 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 NameStr + "'");
2898 return false;
2899}
2900
2901/// GetBB - Get a basic block with the specified name or ID, creating a
2902/// forward reference record if needed.
2903BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2904 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002905 return dyn_cast_or_null<BasicBlock>(
2906 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002907}
2908
2909BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002910 return dyn_cast_or_null<BasicBlock>(
2911 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002912}
2913
2914/// DefineBB - Define the specified basic block, which is either named or
2915/// unnamed. If there is an error, this returns null otherwise it returns
2916/// the block being defined.
2917BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2918 LocTy Loc) {
2919 BasicBlock *BB;
2920 if (Name.empty())
2921 BB = GetBB(NumberedVals.size(), Loc);
2922 else
2923 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002924 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002925
Chris Lattnerac161bf2009-01-02 07:01:27 +00002926 // Move the block to the end of the function. Forward ref'd blocks are
2927 // inserted wherever they happen to be referenced.
2928 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002929
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 // Remove the block from forward ref sets.
2931 if (Name.empty()) {
2932 ForwardRefValIDs.erase(NumberedVals.size());
2933 NumberedVals.push_back(BB);
2934 } else {
2935 // BB forward references are already in the function symbol table.
2936 ForwardRefVals.erase(Name);
2937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002938
Chris Lattnerac161bf2009-01-02 07:01:27 +00002939 return BB;
2940}
2941
2942//===----------------------------------------------------------------------===//
2943// Constants.
2944//===----------------------------------------------------------------------===//
2945
2946/// ParseValID - Parse an abstract value that doesn't necessarily have a
2947/// type implied. For example, if we parse "4" we don't know what integer type
2948/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002949/// sanity. PFS is used to convert function-local operands of metadata (since
2950/// metadata operands are not just parsed here but also converted to values).
2951/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002952bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002953 ID.Loc = Lex.getLoc();
2954 switch (Lex.getKind()) {
2955 default: return TokError("expected value token");
2956 case lltok::GlobalID: // @42
2957 ID.UIntVal = Lex.getUIntVal();
2958 ID.Kind = ValID::t_GlobalID;
2959 break;
2960 case lltok::GlobalVar: // @foo
2961 ID.StrVal = Lex.getStrVal();
2962 ID.Kind = ValID::t_GlobalName;
2963 break;
2964 case lltok::LocalVarID: // %42
2965 ID.UIntVal = Lex.getUIntVal();
2966 ID.Kind = ValID::t_LocalID;
2967 break;
2968 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 ID.StrVal = Lex.getStrVal();
2970 ID.Kind = ValID::t_LocalName;
2971 break;
2972 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002973 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974 ID.Kind = ValID::t_APSInt;
2975 break;
2976 case lltok::APFloat:
2977 ID.APFloatVal = Lex.getAPFloatVal();
2978 ID.Kind = ValID::t_APFloat;
2979 break;
2980 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002981 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002982 ID.Kind = ValID::t_Constant;
2983 break;
2984 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002985 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 ID.Kind = ValID::t_Constant;
2987 break;
2988 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2989 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2990 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002991 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002992
Chris Lattnerac161bf2009-01-02 07:01:27 +00002993 case lltok::lbrace: {
2994 // ValID ::= '{' ConstVector '}'
2995 Lex.Lex();
2996 SmallVector<Constant*, 16> Elts;
2997 if (ParseGlobalValueVector(Elts) ||
2998 ParseToken(lltok::rbrace, "expected end of struct constant"))
2999 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003000
David Blaikieadbda4b2015-08-03 20:08:41 +00003001 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003002 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00003003 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3004 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003005 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 return false;
3007 }
3008 case lltok::less: {
3009 // ValID ::= '<' ConstVector '>' --> Vector.
3010 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3011 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00003012 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003013
Chris Lattnerac161bf2009-01-02 07:01:27 +00003014 SmallVector<Constant*, 16> Elts;
3015 LocTy FirstEltLoc = Lex.getLoc();
3016 if (ParseGlobalValueVector(Elts) ||
3017 (isPackedStruct &&
3018 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3019 ParseToken(lltok::greater, "expected end of constant"))
3020 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003021
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00003023 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3024 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3025 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003026 ID.UIntVal = Elts.size();
3027 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003028 return false;
3029 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003030
Chris Lattnerac161bf2009-01-02 07:01:27 +00003031 if (Elts.empty())
3032 return Error(ID.Loc, "constant vector must not be empty");
3033
Duncan Sands9dff9be2010-02-15 16:12:20 +00003034 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003035 !Elts[0]->getType()->isFloatingPointTy() &&
3036 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003038 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003039
Chris Lattnerac161bf2009-01-02 07:01:27 +00003040 // Verify that all the vector elements have the same type.
3041 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3042 if (Elts[i]->getType() != Elts[0]->getType())
3043 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003044 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003045 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003046
Chris Lattner69229312011-02-15 00:14:00 +00003047 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003048 ID.Kind = ValID::t_Constant;
3049 return false;
3050 }
3051 case lltok::lsquare: { // Array Constant
3052 Lex.Lex();
3053 SmallVector<Constant*, 16> Elts;
3054 LocTy FirstEltLoc = Lex.getLoc();
3055 if (ParseGlobalValueVector(Elts) ||
3056 ParseToken(lltok::rsquare, "expected end of array constant"))
3057 return true;
3058
3059 // Handle empty element.
3060 if (Elts.empty()) {
3061 // Use undef instead of an array because it's inconvenient to determine
3062 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003063 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064 return false;
3065 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003066
Chris Lattnerac161bf2009-01-02 07:01:27 +00003067 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003068 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003069 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003070
Owen Anderson4056ca92009-07-29 22:17:13 +00003071 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003072
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003074 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075 if (Elts[i]->getType() != Elts[0]->getType())
3076 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003077 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003078 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003080
Jay Foad83be3612011-06-22 09:24:39 +00003081 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003082 ID.Kind = ValID::t_Constant;
3083 return false;
3084 }
3085 case lltok::kw_c: // c "foo"
3086 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003087 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3088 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003089 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3090 ID.Kind = ValID::t_Constant;
3091 return false;
3092
3093 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003094 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3095 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003096 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 Lex.Lex();
3098 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003099 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003100 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003101 ParseStringConstant(ID.StrVal) ||
3102 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003103 ParseToken(lltok::StringConstant, "expected constraint string"))
3104 return true;
3105 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003106 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003107 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003108 ID.Kind = ValID::t_InlineAsm;
3109 return false;
3110 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003111
Chris Lattner3432c622009-10-28 03:39:23 +00003112 case lltok::kw_blockaddress: {
3113 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3114 Lex.Lex();
3115
3116 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003117
Chris Lattner3432c622009-10-28 03:39:23 +00003118 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3119 ParseValID(Fn) ||
3120 ParseToken(lltok::comma, "expected comma in block address expression")||
3121 ParseValID(Label) ||
3122 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3123 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003124
Chris Lattner3432c622009-10-28 03:39:23 +00003125 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3126 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003127 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003128 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003129
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003130 // Try to find the function (but skip it if it's forward-referenced).
3131 GlobalValue *GV = nullptr;
3132 if (Fn.Kind == ValID::t_GlobalID) {
3133 if (Fn.UIntVal < NumberedVals.size())
3134 GV = NumberedVals[Fn.UIntVal];
3135 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3136 GV = M->getNamedValue(Fn.StrVal);
3137 }
3138 Function *F = nullptr;
3139 if (GV) {
3140 // Confirm that it's actually a function with a definition.
3141 if (!isa<Function>(GV))
3142 return Error(Fn.Loc, "expected function name in blockaddress");
3143 F = cast<Function>(GV);
3144 if (F->isDeclaration())
3145 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3146 }
3147
3148 if (!F) {
3149 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003150 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003151 ForwardRefBlockAddresses.insert(std::make_pair(
3152 std::move(Fn),
3153 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003154 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3155 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003156 if (!FwdRef)
3157 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3158 GlobalValue::InternalLinkage, nullptr, "");
3159 ID.ConstantVal = FwdRef;
3160 ID.Kind = ValID::t_Constant;
3161 return false;
3162 }
3163
3164 // We found the function; now find the basic block. Don't use PFS, since we
3165 // might be inside a constant expression.
3166 BasicBlock *BB;
3167 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3168 if (Label.Kind == ValID::t_LocalID)
3169 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3170 else
3171 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3172 if (!BB)
3173 return Error(Label.Loc, "referenced value is not a basic block");
3174 } else {
3175 if (Label.Kind == ValID::t_LocalID)
3176 return Error(Label.Loc, "cannot take address of numeric label after "
3177 "the function is defined");
3178 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003179 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003180 if (!BB)
3181 return Error(Label.Loc, "referenced value is not a basic block");
3182 }
3183
3184 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003185 ID.Kind = ValID::t_Constant;
3186 return false;
3187 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003188
Chris Lattnerac161bf2009-01-02 07:01:27 +00003189 case lltok::kw_trunc:
3190 case lltok::kw_zext:
3191 case lltok::kw_sext:
3192 case lltok::kw_fptrunc:
3193 case lltok::kw_fpext:
3194 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003195 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003196 case lltok::kw_uitofp:
3197 case lltok::kw_sitofp:
3198 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003199 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003201 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003202 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003203 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003204 Constant *SrcVal;
3205 Lex.Lex();
3206 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3207 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003208 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003209 ParseType(DestTy) ||
3210 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3211 return true;
3212 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3213 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003214 getTypeString(SrcVal->getType()) + "' to '" +
3215 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003217 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 ID.Kind = ValID::t_Constant;
3219 return false;
3220 }
3221 case lltok::kw_extractvalue: {
3222 Lex.Lex();
3223 Constant *Val;
3224 SmallVector<unsigned, 4> Indices;
3225 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3226 ParseGlobalTypeAndValue(Val) ||
3227 ParseIndexList(Indices) ||
3228 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3229 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003230
Chris Lattner392be582010-02-12 20:49:41 +00003231 if (!Val->getType()->isAggregateType())
3232 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003233 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003234 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003235 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003236 ID.Kind = ValID::t_Constant;
3237 return false;
3238 }
3239 case lltok::kw_insertvalue: {
3240 Lex.Lex();
3241 Constant *Val0, *Val1;
3242 SmallVector<unsigned, 4> Indices;
3243 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3244 ParseGlobalTypeAndValue(Val0) ||
3245 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3246 ParseGlobalTypeAndValue(Val1) ||
3247 ParseIndexList(Indices) ||
3248 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3249 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003250 if (!Val0->getType()->isAggregateType())
3251 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003252 Type *IndexedType =
3253 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3254 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003256 if (IndexedType != Val1->getType())
3257 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3258 getTypeString(Val1->getType()) +
3259 "' instead of '" + getTypeString(IndexedType) +
3260 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003261 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003262 ID.Kind = ValID::t_Constant;
3263 return false;
3264 }
3265 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003266 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 unsigned PredVal, Opc = Lex.getUIntVal();
3268 Constant *Val0, *Val1;
3269 Lex.Lex();
3270 if (ParseCmpPredicate(PredVal, Opc) ||
3271 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3272 ParseGlobalTypeAndValue(Val0) ||
3273 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3274 ParseGlobalTypeAndValue(Val1) ||
3275 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3276 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003277
Chris Lattnerac161bf2009-01-02 07:01:27 +00003278 if (Val0->getType() != Val1->getType())
3279 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003280
Chris Lattnerac161bf2009-01-02 07:01:27 +00003281 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003282
Chris Lattnerac161bf2009-01-02 07:01:27 +00003283 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003284 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003285 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003286 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003287 } else {
3288 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003289 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003290 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003291 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003292 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003293 }
3294 ID.Kind = ValID::t_Constant;
3295 return false;
3296 }
Cameron McInallycbde0d92018-11-13 18:15:47 +00003297
3298 // Unary Operators.
3299 case lltok::kw_fneg: {
3300 unsigned Opc = Lex.getUIntVal();
3301 Constant *Val;
3302 Lex.Lex();
3303 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3304 ParseGlobalTypeAndValue(Val) ||
3305 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3306 return true;
3307
3308 // Check that the type is valid for the operator.
3309 switch (Opc) {
3310 case Instruction::FNeg:
3311 if (!Val->getType()->isFPOrFPVectorTy())
3312 return Error(ID.Loc, "constexpr requires fp operands");
3313 break;
3314 default: llvm_unreachable("Unknown unary operator!");
3315 }
3316 unsigned Flags = 0;
3317 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3318 ID.ConstantVal = C;
3319 ID.Kind = ValID::t_Constant;
3320 return false;
3321 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003322 // Binary Operators.
3323 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003324 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003325 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003326 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003327 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003328 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003329 case lltok::kw_udiv:
3330 case lltok::kw_sdiv:
3331 case lltok::kw_fdiv:
3332 case lltok::kw_urem:
3333 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003334 case lltok::kw_frem:
3335 case lltok::kw_shl:
3336 case lltok::kw_lshr:
3337 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003338 bool NUW = false;
3339 bool NSW = false;
3340 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003341 unsigned Opc = Lex.getUIntVal();
3342 Constant *Val0, *Val1;
3343 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003344 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003345 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3346 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003347 if (EatIfPresent(lltok::kw_nuw))
3348 NUW = true;
3349 if (EatIfPresent(lltok::kw_nsw)) {
3350 NSW = true;
3351 if (EatIfPresent(lltok::kw_nuw))
3352 NUW = true;
3353 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003354 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3355 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003356 if (EatIfPresent(lltok::kw_exact))
3357 Exact = true;
3358 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003359 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3360 ParseGlobalTypeAndValue(Val0) ||
3361 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3362 ParseGlobalTypeAndValue(Val1) ||
3363 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3364 return true;
3365 if (Val0->getType() != Val1->getType())
3366 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003367 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003368 if (NUW)
3369 return Error(ModifierLoc, "nuw only applies to integer operations");
3370 if (NSW)
3371 return Error(ModifierLoc, "nsw only applies to integer operations");
3372 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003373 // Check that the type is valid for the operator.
3374 switch (Opc) {
3375 case Instruction::Add:
3376 case Instruction::Sub:
3377 case Instruction::Mul:
3378 case Instruction::UDiv:
3379 case Instruction::SDiv:
3380 case Instruction::URem:
3381 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003382 case Instruction::Shl:
3383 case Instruction::AShr:
3384 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003385 if (!Val0->getType()->isIntOrIntVectorTy())
3386 return Error(ID.Loc, "constexpr requires integer operands");
3387 break;
3388 case Instruction::FAdd:
3389 case Instruction::FSub:
3390 case Instruction::FMul:
3391 case Instruction::FDiv:
3392 case Instruction::FRem:
3393 if (!Val0->getType()->isFPOrFPVectorTy())
3394 return Error(ID.Loc, "constexpr requires fp operands");
3395 break;
3396 default: llvm_unreachable("Unknown binary operator!");
3397 }
Dan Gohman1b849082009-09-07 23:54:19 +00003398 unsigned Flags = 0;
3399 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3400 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003401 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003402 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003403 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003404 ID.Kind = ValID::t_Constant;
3405 return false;
3406 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003407
Chris Lattnerac161bf2009-01-02 07:01:27 +00003408 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003409 case lltok::kw_and:
3410 case lltok::kw_or:
3411 case lltok::kw_xor: {
3412 unsigned Opc = Lex.getUIntVal();
3413 Constant *Val0, *Val1;
3414 Lex.Lex();
3415 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3416 ParseGlobalTypeAndValue(Val0) ||
3417 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3418 ParseGlobalTypeAndValue(Val1) ||
3419 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3420 return true;
3421 if (Val0->getType() != Val1->getType())
3422 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003423 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003424 return Error(ID.Loc,
3425 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003426 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003427 ID.Kind = ValID::t_Constant;
3428 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003429 }
3430
Chris Lattnerac161bf2009-01-02 07:01:27 +00003431 case lltok::kw_getelementptr:
3432 case lltok::kw_shufflevector:
3433 case lltok::kw_insertelement:
3434 case lltok::kw_extractelement:
3435 case lltok::kw_select: {
3436 unsigned Opc = Lex.getUIntVal();
3437 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003438 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003439 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003440 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003441
Dan Gohman1639c392009-07-27 21:53:46 +00003442 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003443 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003444
3445 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3446 return true;
3447
3448 LocTy ExplicitTypeLoc = Lex.getLoc();
3449 if (Opc == Instruction::GetElementPtr) {
3450 if (ParseType(Ty) ||
3451 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3452 return true;
3453 }
3454
Peter Collingbourned93620b2016-11-10 22:34:55 +00003455 Optional<unsigned> InRangeOp;
3456 if (ParseGlobalValueVector(
3457 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003458 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3459 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003460
Chris Lattnerac161bf2009-01-02 07:01:27 +00003461 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003462 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003463 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003464 return Error(ID.Loc, "base of getelementptr must be a pointer");
3465
3466 Type *BaseType = Elts[0]->getType();
3467 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003468 if (Ty != BasePointerType->getElementType())
3469 return Error(
3470 ExplicitTypeLoc,
3471 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003472
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003473 unsigned GEPWidth =
3474 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3475
Jay Foaded8db7d2011-07-21 14:31:17 +00003476 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003477 for (Constant *Val : Indices) {
3478 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003479 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003480 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003481 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003482 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003483 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003484 return Error(
3485 ID.Loc,
3486 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003487 // GEPWidth may have been unknown because the base is a scalar,
3488 // but it is known now.
3489 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003490 }
3491 }
3492
Craig Toppere3dcce92015-08-01 22:20:21 +00003493 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003494 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003495 return Error(ID.Loc, "base element of getelementptr must be sized");
3496
David Blaikie4a2e73b2015-04-02 18:55:32 +00003497 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003498 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003499
3500 if (InRangeOp) {
3501 if (*InRangeOp == 0)
3502 return Error(ID.Loc,
3503 "inrange keyword may not appear on pointer operand");
3504 --*InRangeOp;
3505 }
3506
3507 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3508 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003509 } else if (Opc == Instruction::Select) {
3510 if (Elts.size() != 3)
3511 return Error(ID.Loc, "expected three operands to select");
3512 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3513 Elts[2]))
3514 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003515 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003516 } else if (Opc == Instruction::ShuffleVector) {
3517 if (Elts.size() != 3)
3518 return Error(ID.Loc, "expected three operands to shufflevector");
3519 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3520 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003521 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003522 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003523 } else if (Opc == Instruction::ExtractElement) {
3524 if (Elts.size() != 2)
3525 return Error(ID.Loc, "expected two operands to extractelement");
3526 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3527 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003528 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 } else {
3530 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3531 if (Elts.size() != 3)
3532 return Error(ID.Loc, "expected three operands to insertelement");
3533 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3534 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003535 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003536 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003537 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003538
Chris Lattnerac161bf2009-01-02 07:01:27 +00003539 ID.Kind = ValID::t_Constant;
3540 return false;
3541 }
3542 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003543
Chris Lattnerac161bf2009-01-02 07:01:27 +00003544 Lex.Lex();
3545 return false;
3546}
3547
3548/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003549bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003550 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003551 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003552 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003553 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003554 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003555 if (V && !(C = dyn_cast<Constant>(V)))
3556 return Error(ID.Loc, "global values must be constants");
3557 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003558}
3559
Victor Hernandez9d75c962010-01-11 22:31:58 +00003560bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003561 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003562 return ParseType(Ty) ||
3563 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003564}
3565
Rafael Espindola83a362c2015-01-06 22:55:16 +00003566bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003567 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003568
3569 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003570 if (!EatIfPresent(lltok::kw_comdat))
3571 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003572
3573 if (EatIfPresent(lltok::lparen)) {
3574 if (Lex.getKind() != lltok::ComdatVar)
3575 return TokError("expected comdat variable");
3576 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3577 Lex.Lex();
3578 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3579 return true;
3580 } else {
3581 if (GlobalName.empty())
3582 return TokError("comdat cannot be unnamed");
3583 C = getComdat(GlobalName, KwLoc);
3584 }
3585
David Majnemerdad0a642014-06-27 18:19:56 +00003586 return false;
3587}
3588
Victor Hernandez9d75c962010-01-11 22:31:58 +00003589/// ParseGlobalValueVector
3590/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003591/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3592bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3593 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003594 // Empty list.
3595 if (Lex.getKind() == lltok::rbrace ||
3596 Lex.getKind() == lltok::rsquare ||
3597 Lex.getKind() == lltok::greater ||
3598 Lex.getKind() == lltok::rparen)
3599 return false;
3600
Peter Collingbourned93620b2016-11-10 22:34:55 +00003601 do {
3602 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3603 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003604
Peter Collingbourned93620b2016-11-10 22:34:55 +00003605 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003606 if (ParseGlobalTypeAndValue(C)) return true;
3607 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003608 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003609
3610 return false;
3611}
3612
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003613bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003614 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003615 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003616 return true;
3617
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003618 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003619 return false;
3620}
3621
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003622/// MDNode:
3623/// ::= !{ ... }
3624/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003625/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003626bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003627 if (Lex.getKind() == lltok::MetadataVar)
3628 return ParseSpecializedMDNode(N);
3629
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003630 return ParseToken(lltok::exclaim, "expected '!' here") ||
3631 ParseMDNodeTail(N);
3632}
3633
3634bool LLParser::ParseMDNodeTail(MDNode *&N) {
3635 // !{ ... }
3636 if (Lex.getKind() == lltok::lbrace)
3637 return ParseMDTuple(N);
3638
3639 // !42
3640 return ParseMDNodeID(N);
3641}
3642
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003643namespace {
3644
3645/// Structure to represent an optional metadata field.
3646template <class FieldTy> struct MDFieldImpl {
3647 typedef MDFieldImpl ImplTy;
3648 FieldTy Val;
3649 bool Seen;
3650
3651 void assign(FieldTy Val) {
3652 Seen = true;
3653 this->Val = std::move(Val);
3654 }
3655
3656 explicit MDFieldImpl(FieldTy Default)
3657 : Val(std::move(Default)), Seen(false) {}
3658};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003659
Sander de Smalenfdf40912018-01-24 09:56:07 +00003660/// Structure to represent an optional metadata field that
3661/// can be of either type (A or B) and encapsulates the
3662/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3663/// to reimplement the specifics for representing each Field.
3664template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3665 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3666 FieldTypeA A;
3667 FieldTypeB B;
3668 bool Seen;
3669
3670 enum {
3671 IsInvalid = 0,
3672 IsTypeA = 1,
3673 IsTypeB = 2
3674 } WhatIs;
3675
3676 void assign(FieldTypeA A) {
3677 Seen = true;
3678 this->A = std::move(A);
3679 WhatIs = IsTypeA;
3680 }
3681
3682 void assign(FieldTypeB B) {
3683 Seen = true;
3684 this->B = std::move(B);
3685 WhatIs = IsTypeB;
3686 }
3687
3688 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3689 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3690 WhatIs(IsInvalid) {}
3691};
3692
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003693struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3694 uint64_t Max;
3695
3696 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3697 : ImplTy(Default), Max(Max) {}
3698};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003699
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003700struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003701 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003702};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003703
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003704struct ColumnField : public MDUnsignedField {
3705 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3706};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003707
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003708struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003709 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003710 DwarfTagField(dwarf::Tag DefaultTag)
3711 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003712};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003713
Amjad Abouda9bcf162015-12-10 12:56:35 +00003714struct DwarfMacinfoTypeField : public MDUnsignedField {
3715 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3716 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3717 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3718};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003719
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003720struct DwarfAttEncodingField : public MDUnsignedField {
3721 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3722};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003723
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003724struct DwarfVirtualityField : public MDUnsignedField {
3725 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3726};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003727
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003728struct DwarfLangField : public MDUnsignedField {
3729 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3730};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003731
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003732struct DwarfCCField : public MDUnsignedField {
3733 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3734};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003735
Adrian Prantlb939a252016-03-31 23:56:58 +00003736struct EmissionKindField : public MDUnsignedField {
3737 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3738};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003739
David Blaikie66cf14d2018-08-16 21:29:55 +00003740struct NameTableKindField : public MDUnsignedField {
3741 NameTableKindField()
3742 : MDUnsignedField(
3743 0, (unsigned)
3744 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3745};
3746
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003747struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3748 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003749};
3750
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00003751struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3752 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3753};
3754
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003755struct MDSignedField : public MDFieldImpl<int64_t> {
3756 int64_t Min;
3757 int64_t Max;
3758
3759 MDSignedField(int64_t Default = 0)
3760 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3761 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3762 : ImplTy(Default), Min(Min), Max(Max) {}
3763};
3764
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003765struct MDBoolField : public MDFieldImpl<bool> {
3766 MDBoolField(bool Default = false) : ImplTy(Default) {}
3767};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003768
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003769struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003770 bool AllowNull;
3771
3772 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003773};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003774
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003775struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3776 MDConstant() : ImplTy(nullptr) {}
3777};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003778
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003779struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003780 bool AllowEmpty;
3781 MDStringField(bool AllowEmpty = true)
3782 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003783};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003784
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003785struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3786 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3787};
3788
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003789struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003790 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3791};
3792
Sander de Smalenfdf40912018-01-24 09:56:07 +00003793struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3794 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3795 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3796
3797 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3798 bool AllowNull = true)
3799 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3800
3801 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3802 bool isMDField() const { return WhatIs == IsTypeB; }
3803 int64_t getMDSignedValue() const {
3804 assert(isMDSignedField() && "Wrong field type");
3805 return A.Val;
3806 }
3807 Metadata *getMDFieldValue() const {
3808 assert(isMDField() && "Wrong field type");
3809 return B.Val;
3810 }
3811};
3812
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003813struct MDSignedOrUnsignedField
3814 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3815 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3816
3817 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3818 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3819 int64_t getMDSignedValue() const {
3820 assert(isMDSignedField() && "Wrong field type");
3821 return A.Val;
3822 }
3823 uint64_t getMDUnsignedValue() const {
3824 assert(isMDUnsignedField() && "Wrong field type");
3825 return B.Val;
3826 }
3827};
3828
Eugene Zelenko1804a772016-08-25 00:45:04 +00003829} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003830
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003831namespace llvm {
3832
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003833template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003834bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003835 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003836 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3837 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003838
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003839 auto &U = Lex.getAPSIntVal();
3840 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003841 return TokError("value for '" + Name + "' too large, limit is " +
3842 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003843 Result.assign(U.getZExtValue());
3844 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003845 Lex.Lex();
3846 return false;
3847}
3848
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003849template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003850bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3851 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3852}
3853template <>
3854bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3855 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3856}
3857
3858template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003859bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3860 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003861 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003862
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003863 if (Lex.getKind() != lltok::DwarfTag)
3864 return TokError("expected DWARF tag");
3865
3866 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3867 if (Tag == dwarf::DW_TAG_invalid)
3868 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003869 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003870
3871 Result.assign(Tag);
3872 Lex.Lex();
3873 return false;
3874}
3875
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003876template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003877bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003878 DwarfMacinfoTypeField &Result) {
3879 if (Lex.getKind() == lltok::APSInt)
3880 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3881
3882 if (Lex.getKind() != lltok::DwarfMacinfo)
3883 return TokError("expected DWARF macinfo type");
3884
3885 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3886 if (Macinfo == dwarf::DW_MACINFO_invalid)
3887 return TokError(
3888 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3889 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3890
3891 Result.assign(Macinfo);
3892 Lex.Lex();
3893 return false;
3894}
3895
3896template <>
3897bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003898 DwarfVirtualityField &Result) {
3899 if (Lex.getKind() == lltok::APSInt)
3900 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3901
3902 if (Lex.getKind() != lltok::DwarfVirtuality)
3903 return TokError("expected DWARF virtuality code");
3904
3905 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003906 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003907 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3908 Lex.getStrVal() + "'");
3909 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3910 Result.assign(Virtuality);
3911 Lex.Lex();
3912 return false;
3913}
3914
3915template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003916bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3917 if (Lex.getKind() == lltok::APSInt)
3918 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3919
3920 if (Lex.getKind() != lltok::DwarfLang)
3921 return TokError("expected DWARF language");
3922
3923 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3924 if (!Lang)
3925 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3926 "'");
3927 assert(Lang <= Result.Max && "Expected valid DWARF language");
3928 Result.assign(Lang);
3929 Lex.Lex();
3930 return false;
3931}
3932
3933template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003934bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3935 if (Lex.getKind() == lltok::APSInt)
3936 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3937
3938 if (Lex.getKind() != lltok::DwarfCC)
3939 return TokError("expected DWARF calling convention");
3940
3941 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3942 if (!CC)
3943 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3944 "'");
3945 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3946 Result.assign(CC);
3947 Lex.Lex();
3948 return false;
3949}
3950
3951template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003952bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3953 if (Lex.getKind() == lltok::APSInt)
3954 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3955
3956 if (Lex.getKind() != lltok::EmissionKind)
3957 return TokError("expected emission kind");
3958
3959 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3960 if (!Kind)
3961 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3962 "'");
3963 assert(*Kind <= Result.Max && "Expected valid emission kind");
3964 Result.assign(*Kind);
3965 Lex.Lex();
3966 return false;
3967}
Fangrui Songf78650a2018-07-30 19:41:25 +00003968
Adrian Prantlb939a252016-03-31 23:56:58 +00003969template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003970bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikie66cf14d2018-08-16 21:29:55 +00003971 NameTableKindField &Result) {
3972 if (Lex.getKind() == lltok::APSInt)
3973 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3974
3975 if (Lex.getKind() != lltok::NameTableKind)
3976 return TokError("expected nameTable kind");
3977
3978 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3979 if (!Kind)
3980 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3981 "'");
3982 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3983 Result.assign((unsigned)*Kind);
3984 Lex.Lex();
3985 return false;
3986}
3987
3988template <>
3989bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003990 DwarfAttEncodingField &Result) {
3991 if (Lex.getKind() == lltok::APSInt)
3992 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3993
3994 if (Lex.getKind() != lltok::DwarfAttEncoding)
3995 return TokError("expected DWARF type attribute encoding");
3996
3997 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3998 if (!Encoding)
3999 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4000 Lex.getStrVal() + "'");
4001 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4002 Result.assign(Encoding);
4003 Lex.Lex();
4004 return false;
4005}
4006
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004007/// DIFlagField
4008/// ::= uint32
4009/// ::= DIFlagVector
4010/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4011template <>
4012bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004013
4014 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004015 auto parseFlag = [&](DINode::DIFlags &Val) {
4016 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4017 uint32_t TempVal = static_cast<uint32_t>(Val);
4018 bool Res = ParseUInt32(TempVal);
4019 Val = static_cast<DINode::DIFlags>(TempVal);
4020 return Res;
4021 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004022
4023 if (Lex.getKind() != lltok::DIFlag)
4024 return TokError("expected debug info flag");
4025
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004026 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004027 if (!Val)
4028 return TokError(Twine("invalid debug info flag flag '") +
4029 Lex.getStrVal() + "'");
4030 Lex.Lex();
4031 return false;
4032 };
4033
4034 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004035 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004036 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004037 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004038 if (parseFlag(Val))
4039 return true;
4040 Combined |= Val;
4041 } while (EatIfPresent(lltok::bar));
4042
4043 Result.assign(Combined);
4044 return false;
4045}
4046
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004047/// DISPFlagField
4048/// ::= uint32
4049/// ::= DISPFlagVector
4050/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4051template <>
4052bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4053
4054 // Parser for a single flag.
4055 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4056 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4057 uint32_t TempVal = static_cast<uint32_t>(Val);
4058 bool Res = ParseUInt32(TempVal);
4059 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4060 return Res;
4061 }
4062
4063 if (Lex.getKind() != lltok::DISPFlag)
4064 return TokError("expected debug info flag");
4065
4066 Val = DISubprogram::getFlag(Lex.getStrVal());
4067 if (!Val)
4068 return TokError(Twine("invalid subprogram debug info flag '") +
4069 Lex.getStrVal() + "'");
4070 Lex.Lex();
4071 return false;
4072 };
4073
4074 // Parse the flags and combine them together.
4075 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4076 do {
4077 DISubprogram::DISPFlags Val;
4078 if (parseFlag(Val))
4079 return true;
4080 Combined |= Val;
4081 } while (EatIfPresent(lltok::bar));
4082
4083 Result.assign(Combined);
4084 return false;
4085}
4086
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004087template <>
4088bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004089 MDSignedField &Result) {
4090 if (Lex.getKind() != lltok::APSInt)
4091 return TokError("expected signed integer");
4092
4093 auto &S = Lex.getAPSIntVal();
4094 if (S < Result.Min)
4095 return TokError("value for '" + Name + "' too small, limit is " +
4096 Twine(Result.Min));
4097 if (S > Result.Max)
4098 return TokError("value for '" + Name + "' too large, limit is " +
4099 Twine(Result.Max));
4100 Result.assign(S.getExtValue());
4101 assert(Result.Val >= Result.Min && "Expected value in range");
4102 assert(Result.Val <= Result.Max && "Expected value in range");
4103 Lex.Lex();
4104 return false;
4105}
4106
4107template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004108bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4109 switch (Lex.getKind()) {
4110 default:
4111 return TokError("expected 'true' or 'false'");
4112 case lltok::kw_true:
4113 Result.assign(true);
4114 break;
4115 case lltok::kw_false:
4116 Result.assign(false);
4117 break;
4118 }
4119 Lex.Lex();
4120 return false;
4121}
4122
4123template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004124bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004125 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004126 if (!Result.AllowNull)
4127 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004128 Lex.Lex();
4129 Result.assign(nullptr);
4130 return false;
4131 }
4132
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004133 Metadata *MD;
4134 if (ParseMetadata(MD, nullptr))
4135 return true;
4136
4137 Result.assign(MD);
4138 return false;
4139}
4140
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004141template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00004142bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4143 MDSignedOrMDField &Result) {
4144 // Try to parse a signed int.
4145 if (Lex.getKind() == lltok::APSInt) {
4146 MDSignedField Res = Result.A;
4147 if (!ParseMDField(Loc, Name, Res)) {
4148 Result.assign(Res);
4149 return false;
4150 }
4151 return true;
4152 }
4153
4154 // Otherwise, try to parse as an MDField.
4155 MDField Res = Result.B;
4156 if (!ParseMDField(Loc, Name, Res)) {
4157 Result.assign(Res);
4158 return false;
4159 }
4160
4161 return true;
4162}
4163
4164template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004165bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4166 MDSignedOrUnsignedField &Result) {
4167 if (Lex.getKind() != lltok::APSInt)
4168 return false;
4169
4170 if (Lex.getAPSIntVal().isSigned()) {
4171 MDSignedField Res = Result.A;
4172 if (ParseMDField(Loc, Name, Res))
4173 return true;
4174 Result.assign(Res);
4175 return false;
4176 }
4177
4178 MDUnsignedField Res = Result.B;
4179 if (ParseMDField(Loc, Name, Res))
4180 return true;
4181 Result.assign(Res);
4182 return false;
4183}
4184
4185template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004186bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004187 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004188 std::string S;
4189 if (ParseStringConstant(S))
4190 return true;
4191
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004192 if (!Result.AllowEmpty && S.empty())
4193 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4194
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004195 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004196 return false;
4197}
4198
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004199template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004200bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4201 SmallVector<Metadata *, 4> MDs;
4202 if (ParseMDNodeVector(MDs))
4203 return true;
4204
4205 Result.assign(std::move(MDs));
4206 return false;
4207}
4208
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004209template <>
4210bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4211 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004212 Optional<DIFile::ChecksumKind> CSKind =
4213 DIFile::getChecksumKind(Lex.getStrVal());
4214
4215 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004216 return TokError(
4217 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4218
Scott Linder71603842018-02-12 19:45:54 +00004219 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004220 Lex.Lex();
4221 return false;
4222}
4223
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004224} // end namespace llvm
4225
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004226template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004227bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004228 do {
4229 if (Lex.getKind() != lltok::LabelStr)
4230 return TokError("expected field label here");
4231
4232 if (parseField())
4233 return true;
4234 } while (EatIfPresent(lltok::comma));
4235
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004236 return false;
4237}
4238
4239template <class ParserTy>
4240bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4241 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4242 Lex.Lex();
4243
4244 if (ParseToken(lltok::lparen, "expected '(' here"))
4245 return true;
4246 if (Lex.getKind() != lltok::rparen)
4247 if (ParseMDFieldsImplBody(parseField))
4248 return true;
4249
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004250 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004251 return ParseToken(lltok::rparen, "expected ')' here");
4252}
4253
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004254template <class FieldTy>
4255bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4256 if (Result.Seen)
4257 return TokError("field '" + Name + "' cannot be specified more than once");
4258
4259 LocTy Loc = Lex.getLoc();
4260 Lex.Lex();
4261 return ParseMDField(Loc, Name, Result);
4262}
4263
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004264bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4265 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004266
4267#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004268 if (Lex.getStrVal() == #CLASS) \
4269 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004270#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004271
4272 return TokError("expected metadata type");
4273}
4274
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004275#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4276#define NOP_FIELD(NAME, TYPE, INIT)
4277#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4278 if (!NAME.Seen) \
4279 return Error(ClosingLoc, "missing required field '" #NAME "'");
4280#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004281 if (Lex.getStrVal() == #NAME) \
4282 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004283#define PARSE_MD_FIELDS() \
4284 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4285 do { \
4286 LocTy ClosingLoc; \
4287 if (ParseMDFieldsImpl([&]() -> bool { \
4288 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4289 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4290 }, ClosingLoc)) \
4291 return true; \
4292 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4293 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004294#define GET_OR_DISTINCT(CLASS, ARGS) \
4295 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004296
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004297/// ParseDILocationFields:
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004298/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4299/// isImplicitCode: true)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004300bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004301#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004302 OPTIONAL(line, LineField, ); \
4303 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004304 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004305 OPTIONAL(inlinedAt, MDField, ); \
4306 OPTIONAL(isImplicitCode, MDBoolField, (false));
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004307 PARSE_MD_FIELDS();
4308#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004309
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004310 Result =
4311 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4312 inlinedAt.Val, isImplicitCode.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004313 return false;
4314}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004315
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004316/// ParseGenericDINode:
4317/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4318bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004319#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004320 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004321 OPTIONAL(header, MDStringField, ); \
4322 OPTIONAL(operands, MDFieldList, );
4323 PARSE_MD_FIELDS();
4324#undef VISIT_MD_FIELDS
4325
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004326 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004327 (Context, tag.Val, header.Val, operands.Val));
4328 return false;
4329}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004330
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004331/// ParseDISubrange:
4332/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004333/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004334bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004335#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004336 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004337 OPTIONAL(lowerBound, MDSignedField, );
4338 PARSE_MD_FIELDS();
4339#undef VISIT_MD_FIELDS
4340
Sander de Smalenfdf40912018-01-24 09:56:07 +00004341 if (count.isMDSignedField())
4342 Result = GET_OR_DISTINCT(
4343 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4344 else if (count.isMDField())
4345 Result = GET_OR_DISTINCT(
4346 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4347 else
4348 return true;
4349
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004350 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004351}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004352
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004353/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004354/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004355bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004356#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004357 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004358 REQUIRED(value, MDSignedOrUnsignedField, ); \
4359 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004360 PARSE_MD_FIELDS();
4361#undef VISIT_MD_FIELDS
4362
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004363 if (isUnsigned.Val && value.isMDSignedField())
4364 return TokError("unsigned enumerator with negative value");
4365
4366 int64_t Value = value.isMDSignedField()
4367 ? value.getMDSignedValue()
4368 : static_cast<int64_t>(value.getMDUnsignedValue());
4369 Result =
4370 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4371
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004372 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004373}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004374
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004375/// ParseDIBasicType:
Adrian Prantl55f42622018-08-14 19:35:34 +00004376/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4377/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004378bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004379#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004380 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004381 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004382 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004383 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantl55f42622018-08-14 19:35:34 +00004384 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4385 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004386 PARSE_MD_FIELDS();
4387#undef VISIT_MD_FIELDS
4388
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004389 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantl55f42622018-08-14 19:35:34 +00004390 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004391 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004392}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004393
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004394/// ParseDIDerivedType:
4395/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004396/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004397/// align: 32, offset: 0, flags: 0, extraData: !3,
4398/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004399bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004400#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4401 REQUIRED(tag, DwarfTagField, ); \
4402 OPTIONAL(name, MDStringField, ); \
4403 OPTIONAL(file, MDField, ); \
4404 OPTIONAL(line, LineField, ); \
4405 OPTIONAL(scope, MDField, ); \
4406 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004407 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004408 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004409 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004410 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004411 OPTIONAL(extraData, MDField, ); \
4412 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004413 PARSE_MD_FIELDS();
4414#undef VISIT_MD_FIELDS
4415
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004416 Optional<unsigned> DWARFAddressSpace;
4417 if (dwarfAddressSpace.Val != UINT32_MAX)
4418 DWARFAddressSpace = dwarfAddressSpace.Val;
4419
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004420 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004421 (Context, tag.Val, name.Val, file.Val, line.Val,
4422 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004423 offset.Val, DWARFAddressSpace, flags.Val,
4424 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004425 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004426}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004427
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004428bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004429#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4430 REQUIRED(tag, DwarfTagField, ); \
4431 OPTIONAL(name, MDStringField, ); \
4432 OPTIONAL(file, MDField, ); \
4433 OPTIONAL(line, LineField, ); \
4434 OPTIONAL(scope, MDField, ); \
4435 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004436 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004437 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004438 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004439 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004440 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004441 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004442 OPTIONAL(vtableHolder, MDField, ); \
4443 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004444 OPTIONAL(identifier, MDStringField, ); \
4445 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004446 PARSE_MD_FIELDS();
4447#undef VISIT_MD_FIELDS
4448
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004449 // If this has an identifier try to build an ODR type.
4450 if (identifier.Val)
4451 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004452 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4453 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4454 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004455 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004456 Result = CT;
4457 return false;
4458 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004459
4460 // Create a new node, and save it in the context if it belongs in the type
4461 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004462 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004463 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004464 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4465 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004466 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4467 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004468 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004469}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004470
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004471bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004472#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004473 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004474 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004475 REQUIRED(types, MDField, );
4476 PARSE_MD_FIELDS();
4477#undef VISIT_MD_FIELDS
4478
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004479 Result = GET_OR_DISTINCT(DISubroutineType,
4480 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004481 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004482}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004483
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004484/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004485/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004486/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004487/// checksum: "000102030405060708090a0b0c0d0e0f",
4488/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004489bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004490 // The default constructed value for checksumkind is required, but will never
4491 // be used, as the parser checks if the field was actually Seen before using
4492 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004493#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4494 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004495 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004496 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004497 OPTIONAL(checksum, MDStringField, ); \
4498 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004499 PARSE_MD_FIELDS();
4500#undef VISIT_MD_FIELDS
4501
Scott Linder71603842018-02-12 19:45:54 +00004502 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4503 if (checksumkind.Seen && checksum.Seen)
4504 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4505 else if (checksumkind.Seen || checksum.Seen)
4506 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4507
Scott Linder16c7bda2018-02-23 23:01:06 +00004508 Optional<MDString *> OptSource;
4509 if (source.Seen)
4510 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004511 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004512 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004513 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004514}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004515
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004516/// ParseDICompileUnit:
4517/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004518/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004519/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004520/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004521/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004522bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004523 if (!IsDistinct)
4524 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4525
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004526#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4527 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004528 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004529 OPTIONAL(producer, MDStringField, ); \
4530 OPTIONAL(isOptimized, MDBoolField, ); \
4531 OPTIONAL(flags, MDStringField, ); \
4532 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4533 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004534 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004535 OPTIONAL(enums, MDField, ); \
4536 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004537 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004538 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004539 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004540 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004541 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004542 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikiebb279112018-11-13 20:08:10 +00004543 OPTIONAL(nameTableKind, NameTableKindField, ); \
4544 OPTIONAL(debugBaseAddress, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004545 PARSE_MD_FIELDS();
4546#undef VISIT_MD_FIELDS
4547
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004548 Result = DICompileUnit::getDistinct(
4549 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4550 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004551 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikiebb279112018-11-13 20:08:10 +00004552 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4553 debugBaseAddress.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004554 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004555}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004556
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004557/// ParseDISubprogram:
4558/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004559/// file: !1, line: 7, type: !2, isLocal: false,
4560/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004561/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004562/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004563/// spFlags: 10, isOptimized: false, templateParams: !4,
4564/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004565bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004566 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004567#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4568 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004569 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004570 OPTIONAL(linkageName, MDStringField, ); \
4571 OPTIONAL(file, MDField, ); \
4572 OPTIONAL(line, LineField, ); \
4573 OPTIONAL(type, MDField, ); \
4574 OPTIONAL(isLocal, MDBoolField, ); \
4575 OPTIONAL(isDefinition, MDBoolField, (true)); \
4576 OPTIONAL(scopeLine, LineField, ); \
4577 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004578 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004579 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004580 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004581 OPTIONAL(flags, DIFlagField, ); \
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004582 OPTIONAL(spFlags, DISPFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004583 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004584 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004585 OPTIONAL(templateParams, MDField, ); \
4586 OPTIONAL(declaration, MDField, ); \
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004587 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004588 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004589 PARSE_MD_FIELDS();
4590#undef VISIT_MD_FIELDS
4591
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004592 // An explicit spFlags field takes precedence over individual fields in
4593 // older IR versions.
4594 DISubprogram::DISPFlags SPFlags =
4595 spFlags.Seen ? spFlags.Val
4596 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4597 isOptimized.Val, virtuality.Val);
4598 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004599 return Lex.Error(
4600 Loc,
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004601 "missing 'distinct', required for !DISubprogram that is a Definition");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004602 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004603 DISubprogram,
4604 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
Paul Robinsoncda54212018-11-19 18:29:28 +00004605 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4606 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004607 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004608 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004609}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004610
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004611/// ParseDILexicalBlock:
4612/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4613bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004614#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004615 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004616 OPTIONAL(file, MDField, ); \
4617 OPTIONAL(line, LineField, ); \
4618 OPTIONAL(column, ColumnField, );
4619 PARSE_MD_FIELDS();
4620#undef VISIT_MD_FIELDS
4621
4622 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004623 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004624 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004625}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004626
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004627/// ParseDILexicalBlockFile:
4628/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4629bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004630#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004631 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004632 OPTIONAL(file, MDField, ); \
4633 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4634 PARSE_MD_FIELDS();
4635#undef VISIT_MD_FIELDS
4636
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004637 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004638 (Context, scope.Val, file.Val, discriminator.Val));
4639 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004640}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004641
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004642/// ParseDINamespace:
4643/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4644bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004645#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4646 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004647 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004648 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004649 PARSE_MD_FIELDS();
4650#undef VISIT_MD_FIELDS
4651
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004652 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004653 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004654 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004655}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004656
Amjad Abouda9bcf162015-12-10 12:56:35 +00004657/// ParseDIMacro:
4658/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4659bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4660#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4661 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004662 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004663 REQUIRED(name, MDStringField, ); \
4664 OPTIONAL(value, MDStringField, );
4665 PARSE_MD_FIELDS();
4666#undef VISIT_MD_FIELDS
4667
4668 Result = GET_OR_DISTINCT(DIMacro,
4669 (Context, type.Val, line.Val, name.Val, value.Val));
4670 return false;
4671}
4672
4673/// ParseDIMacroFile:
4674/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4675bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4676#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4677 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004678 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004679 REQUIRED(file, MDField, ); \
4680 OPTIONAL(nodes, MDField, );
4681 PARSE_MD_FIELDS();
4682#undef VISIT_MD_FIELDS
4683
4684 Result = GET_OR_DISTINCT(DIMacroFile,
4685 (Context, type.Val, line.Val, file.Val, nodes.Val));
4686 return false;
4687}
4688
Adrian Prantlab1243f2015-06-29 23:03:47 +00004689/// ParseDIModule:
4690/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4691/// includePath: "/usr/include", isysroot: "/")
4692bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4693#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4694 REQUIRED(scope, MDField, ); \
4695 REQUIRED(name, MDStringField, ); \
4696 OPTIONAL(configMacros, MDStringField, ); \
4697 OPTIONAL(includePath, MDStringField, ); \
4698 OPTIONAL(isysroot, MDStringField, );
4699 PARSE_MD_FIELDS();
4700#undef VISIT_MD_FIELDS
4701
4702 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4703 configMacros.Val, includePath.Val, isysroot.Val));
4704 return false;
4705}
4706
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004707/// ParseDITemplateTypeParameter:
4708/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4709bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004710#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004711 OPTIONAL(name, MDStringField, ); \
4712 REQUIRED(type, MDField, );
4713 PARSE_MD_FIELDS();
4714#undef VISIT_MD_FIELDS
4715
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004716 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004717 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004718 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004719}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004720
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004721/// ParseDITemplateValueParameter:
4722/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004723/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004724bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004725#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004726 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004727 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004728 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004729 REQUIRED(value, MDField, );
4730 PARSE_MD_FIELDS();
4731#undef VISIT_MD_FIELDS
4732
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004733 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004734 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004735 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004736}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004737
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004738/// ParseDIGlobalVariable:
4739/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004740/// file: !1, line: 7, type: !2, isLocal: false,
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004741/// isDefinition: true, templateParams: !3,
4742/// declaration: !4, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004743bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004744#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004745 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004746 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004747 OPTIONAL(linkageName, MDStringField, ); \
4748 OPTIONAL(file, MDField, ); \
4749 OPTIONAL(line, LineField, ); \
4750 OPTIONAL(type, MDField, ); \
4751 OPTIONAL(isLocal, MDBoolField, ); \
4752 OPTIONAL(isDefinition, MDBoolField, (true)); \
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004753 OPTIONAL(templateParams, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004754 OPTIONAL(declaration, MDField, ); \
4755 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004756 PARSE_MD_FIELDS();
4757#undef VISIT_MD_FIELDS
4758
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004759 Result =
4760 GET_OR_DISTINCT(DIGlobalVariable,
4761 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4762 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4763 declaration.Val, templateParams.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004764 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004765}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004766
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004767/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004768/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004769/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4770/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004771/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004772/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4773/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004774bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004775#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004776 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004777 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004778 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004779 OPTIONAL(file, MDField, ); \
4780 OPTIONAL(line, LineField, ); \
4781 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004782 OPTIONAL(flags, DIFlagField, ); \
4783 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004784 PARSE_MD_FIELDS();
4785#undef VISIT_MD_FIELDS
4786
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004787 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004788 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004789 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004790 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004791}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004792
Shiva Chen2c864552018-05-09 02:40:45 +00004793/// ParseDILabel:
4794/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4795bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4796#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4797 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4798 REQUIRED(name, MDStringField, ); \
4799 REQUIRED(file, MDField, ); \
4800 REQUIRED(line, LineField, );
4801 PARSE_MD_FIELDS();
4802#undef VISIT_MD_FIELDS
4803
4804 Result = GET_OR_DISTINCT(DILabel,
4805 (Context, scope.Val, name.Val, file.Val, line.Val));
4806 return false;
4807}
4808
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004809/// ParseDIExpression:
4810/// ::= !DIExpression(0, 7, -1)
4811bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004812 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4813 Lex.Lex();
4814
4815 if (ParseToken(lltok::lparen, "expected '(' here"))
4816 return true;
4817
4818 SmallVector<uint64_t, 8> Elements;
4819 if (Lex.getKind() != lltok::rparen)
4820 do {
4821 if (Lex.getKind() == lltok::DwarfOp) {
4822 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4823 Lex.Lex();
4824 Elements.push_back(Op);
4825 continue;
4826 }
4827 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4828 }
4829
4830 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4831 return TokError("expected unsigned integer");
4832
4833 auto &U = Lex.getAPSIntVal();
4834 if (U.ugt(UINT64_MAX))
4835 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4836 Elements.push_back(U.getZExtValue());
4837 Lex.Lex();
4838 } while (EatIfPresent(lltok::comma));
4839
4840 if (ParseToken(lltok::rparen, "expected ')' here"))
4841 return true;
4842
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004843 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004844 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004845}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004846
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004847/// ParseDIGlobalVariableExpression:
4848/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4849bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4850 bool IsDistinct) {
4851#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4852 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004853 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004854 PARSE_MD_FIELDS();
4855#undef VISIT_MD_FIELDS
4856
4857 Result =
4858 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4859 return false;
4860}
4861
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004862/// ParseDIObjCProperty:
4863/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004864/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004865bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004866#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004867 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004868 OPTIONAL(file, MDField, ); \
4869 OPTIONAL(line, LineField, ); \
4870 OPTIONAL(setter, MDStringField, ); \
4871 OPTIONAL(getter, MDStringField, ); \
4872 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4873 OPTIONAL(type, MDField, );
4874 PARSE_MD_FIELDS();
4875#undef VISIT_MD_FIELDS
4876
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004877 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004878 (Context, name.Val, file.Val, line.Val, setter.Val,
4879 getter.Val, attributes.Val, type.Val));
4880 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004881}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004882
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004883/// ParseDIImportedEntity:
4884/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004885/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004886bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004887#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4888 REQUIRED(tag, DwarfTagField, ); \
4889 REQUIRED(scope, MDField, ); \
4890 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004891 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004892 OPTIONAL(line, LineField, ); \
4893 OPTIONAL(name, MDStringField, );
4894 PARSE_MD_FIELDS();
4895#undef VISIT_MD_FIELDS
4896
Adrian Prantld63bfd22017-07-19 00:09:54 +00004897 Result = GET_OR_DISTINCT(
4898 DIImportedEntity,
4899 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004900 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004901}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004902
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004903#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004904#undef NOP_FIELD
4905#undef REQUIRE_FIELD
4906#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004907
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004908/// ParseMetadataAsValue
4909/// ::= metadata i32 %local
4910/// ::= metadata i32 @global
4911/// ::= metadata i32 7
4912/// ::= metadata !0
4913/// ::= metadata !{...}
4914/// ::= metadata !"string"
4915bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4916 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004917 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004918 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004919 return true;
4920
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004921 V = MetadataAsValue::get(Context, MD);
4922 return false;
4923}
4924
4925/// ParseValueAsMetadata
4926/// ::= i32 %local
4927/// ::= i32 @global
4928/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004929bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4930 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004931 Type *Ty;
4932 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004933 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004934 return true;
4935 if (Ty->isMetadataTy())
4936 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4937
4938 Value *V;
4939 if (ParseValue(Ty, V, PFS))
4940 return true;
4941
4942 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004943 return false;
4944}
4945
4946/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004947/// ::= i32 %local
4948/// ::= i32 @global
4949/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004950/// ::= !42
4951/// ::= !{...}
4952/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004953/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004954bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004955 if (Lex.getKind() == lltok::MetadataVar) {
4956 MDNode *N;
4957 if (ParseSpecializedMDNode(N))
4958 return true;
4959 MD = N;
4960 return false;
4961 }
4962
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004963 // ValueAsMetadata:
4964 // <type> <value>
4965 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004966 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004967
4968 // '!'.
4969 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4970 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004971
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004972 // MDString:
4973 // ::= '!' STRINGCONSTANT
4974 if (Lex.getKind() == lltok::StringConstant) {
4975 MDString *S;
4976 if (ParseMDString(S))
4977 return true;
4978 MD = S;
4979 return false;
4980 }
4981
Dan Gohman8939ba332010-07-14 18:26:50 +00004982 // MDNode:
4983 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004984 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004985 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004986 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004987 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004988 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004989 return false;
4990}
4991
Victor Hernandez9d75c962010-01-11 22:31:58 +00004992//===----------------------------------------------------------------------===//
4993// Function Parsing.
4994//===----------------------------------------------------------------------===//
4995
Chris Lattner229907c2011-07-18 04:54:35 +00004996bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004997 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004998 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004999 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005000
Chris Lattnerac161bf2009-01-02 07:01:27 +00005001 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005002 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00005003 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005004 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005005 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00005007 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005008 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005009 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00005010 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00005011 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00005012 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00005013 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5014 (ID.UIntVal >> 1) & 1,
5015 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00005016 return false;
5017 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005018 case ValID::t_GlobalName:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005019 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005020 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 case ValID::t_GlobalID:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005022 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005023 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00005025 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005026 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00005027 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00005028 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005029 return false;
5030 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00005031 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5033 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005034
Dan Gohman518cda42011-12-17 00:04:22 +00005035 // The lexer has no type info, so builds all half, float, and double FP
5036 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005037 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005038 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00005039 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005040 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00005041 &Ignored);
5042 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005043 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00005044 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005045 }
Owen Anderson69c464d2009-07-27 20:59:43 +00005046 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005047
Chris Lattner8f57d29e2009-01-05 18:24:23 +00005048 if (V->getType() != Ty)
5049 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005050 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005051
Chris Lattnerac161bf2009-01-02 07:01:27 +00005052 return false;
5053 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00005054 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005055 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005056 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 return false;
5058 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00005059 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005060 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00005061 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005062 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005063 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00005064 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00005065 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00005066 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005067 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00005068 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005069 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00005070 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00005071 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00005073 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005074 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00005075 case ValID::t_None:
5076 if (!Ty->isTokenTy())
5077 return Error(ID.Loc, "invalid type for none constant");
5078 V = Constant::getNullValue(Ty);
5079 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00005081 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00005083
Chris Lattnerac161bf2009-01-02 07:01:27 +00005084 V = ID.ConstantVal;
5085 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005086 case ValID::t_ConstantStruct:
5087 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00005088 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005089 if (ST->getNumElements() != ID.UIntVal)
5090 return Error(ID.Loc,
5091 "initializer with struct type has wrong # elements");
5092 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5093 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005095 // Verify that the elements are compatible with the structtype.
5096 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5097 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5098 return Error(ID.Loc, "element " + Twine(i) +
5099 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005100
David Blaikieadbda4b2015-08-03 20:08:41 +00005101 V = ConstantStruct::get(
5102 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005103 } else
5104 return Error(ID.Loc, "constant expression type mismatch");
5105 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00005107 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005108}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005109
Alex Lorenzd2255952015-07-17 22:07:03 +00005110bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5111 C = nullptr;
5112 ValID ID;
5113 auto Loc = Lex.getLoc();
5114 if (ParseValID(ID, /*PFS=*/nullptr))
5115 return true;
5116 switch (ID.Kind) {
5117 case ValID::t_APSInt:
5118 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00005119 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00005120 case ValID::t_Constant:
5121 case ValID::t_ConstantStruct:
5122 case ValID::t_PackedConstantStruct: {
5123 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005124 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00005125 return true;
5126 assert(isa<Constant>(V) && "Expected a constant value");
5127 C = cast<Constant>(V);
5128 return false;
5129 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00005130 case ValID::t_Null:
5131 C = Constant::getNullValue(Ty);
5132 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00005133 default:
5134 return Error(Loc, "expected a constant value");
5135 }
5136}
5137
David Majnemer8a1c45d2015-12-12 05:38:55 +00005138bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005139 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005141 return ParseValID(ID, PFS) ||
5142 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005143}
5144
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005145bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005146 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005147 return ParseType(Ty) ||
5148 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149}
5150
Chris Lattner3ed871f2009-10-27 19:13:16 +00005151bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5152 PerFunctionState &PFS) {
5153 Value *V;
5154 Loc = Lex.getLoc();
5155 if (ParseTypeAndValue(V, PFS)) return true;
5156 if (!isa<BasicBlock>(V))
5157 return Error(Loc, "expected a basic block");
5158 BB = cast<BasicBlock>(V);
5159 return false;
5160}
5161
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00005163/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5164/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005165/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5166/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00005167bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5168 // Parse the linkage.
5169 LocTy LinkageLoc = Lex.getLoc();
5170 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005171 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005172 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005173 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005174 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005175 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005176 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005177 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005178 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005179 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5180 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005181 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005182 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005183 return true;
5184
5185 // Verify that the linkage is ok.
5186 switch ((GlobalValue::LinkageTypes)Linkage) {
5187 case GlobalValue::ExternalLinkage:
5188 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005189 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 if (isDefine)
5191 return Error(LinkageLoc, "invalid linkage for function definition");
5192 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005193 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005195 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005196 case GlobalValue::LinkOnceAnyLinkage:
5197 case GlobalValue::LinkOnceODRLinkage:
5198 case GlobalValue::WeakAnyLinkage:
5199 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200 if (!isDefine)
5201 return Error(LinkageLoc, "invalid linkage for function declaration");
5202 break;
5203 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005204 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005205 return Error(LinkageLoc, "invalid function linkage type");
5206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005207
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005208 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5209 return Error(LinkageLoc,
5210 "symbol with local linkage must have default visibility");
5211
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005212 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005213 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005214
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005216
5217 std::string FunctionName;
5218 if (Lex.getKind() == lltok::GlobalVar) {
5219 FunctionName = Lex.getStrVal();
5220 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5221 unsigned NameID = Lex.getUIntVal();
5222
5223 if (NameID != NumberedVals.size())
5224 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005225 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005226 } else {
5227 return TokError("expected function name");
5228 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005229
Chris Lattner3822f632009-01-02 08:05:26 +00005230 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005231
Chris Lattner3822f632009-01-02 08:05:26 +00005232 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005233 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005234
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005235 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005236 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005237 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005238 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005239 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005242 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005243 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005244 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005245 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005246 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005247 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005248 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005249
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005250 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005251 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005252 ParseOptionalProgramAddrSpace(AddrSpace) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005253 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005254 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005255 (EatIfPresent(lltok::kw_section) &&
5256 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005257 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005258 ParseOptionalAlignment(Alignment) ||
5259 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005260 ParseStringConstant(GC)) ||
5261 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005262 ParseGlobalTypeAndValue(Prefix)) ||
5263 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005264 ParseGlobalTypeAndValue(Prologue)) ||
5265 (EatIfPresent(lltok::kw_personality) &&
5266 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005267 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268
Michael Gottesman41748d72013-06-27 00:25:01 +00005269 if (FuncAttrs.contains(Attribute::Builtin))
5270 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005271
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005273 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005274 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005275 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005277
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278 // Okay, if we got here, the function is syntactically valid. Convert types
5279 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005280 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005281 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005282
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005284 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005285 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005286 }
5287
Reid Kleckner7f720332017-04-13 00:58:09 +00005288 AttributeList PAL =
5289 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5290 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005291
Bill Wendling749a43d2012-12-30 13:50:49 +00005292 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005293 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5294
Chris Lattner229907c2011-07-18 04:54:35 +00005295 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005296 FunctionType::get(RetType, ParamTypeList, isVarArg);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005297 PointerType *PFT = PointerType::get(FT, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298
Craig Topper2617dcc2014-04-15 06:32:26 +00005299 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005300 if (!FunctionName.empty()) {
5301 // If this was a definition of a forward reference, remove the definition
5302 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005303 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005304 if (FRVI != ForwardRefVals.end()) {
5305 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005306 if (!Fn)
5307 return Error(FRVI->second.second, "invalid forward reference to "
5308 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005309 if (Fn->getType() != PFT)
5310 return Error(FRVI->second.second, "invalid forward reference to "
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005311 "function '" + FunctionName + "' with wrong type: "
5312 "expected '" + getTypeString(PFT) + "' but was '" +
5313 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005314 ForwardRefVals.erase(FRVI);
5315 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005316 // Reject redefinitions.
5317 return Error(NameLoc, "invalid redefinition of function '" +
5318 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005319 } else if (M->getNamedValue(FunctionName)) {
5320 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005321 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005322
Dan Gohman399d6ae2009-08-29 23:37:49 +00005323 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005324 // If this is a definition of a forward referenced function, make sure the
5325 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005326 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327 if (I != ForwardRefValIDs.end()) {
5328 Fn = cast<Function>(I->second.first);
5329 if (Fn->getType() != PFT)
5330 return Error(NameLoc, "type of definition and forward reference of '@" +
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005331 Twine(NumberedVals.size()) + "' disagree: "
5332 "expected '" + getTypeString(PFT) + "' but was '" +
5333 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005334 ForwardRefValIDs.erase(I);
5335 }
5336 }
5337
Craig Topper2617dcc2014-04-15 06:32:26 +00005338 if (!Fn)
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005339 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5340 FunctionName, M);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005341 else // Move the forward-reference to the correct spot in the module.
5342 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5343
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005344 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5345
Chris Lattnerac161bf2009-01-02 07:01:27 +00005346 if (FunctionName.empty())
5347 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005348
Chris Lattnerac161bf2009-01-02 07:01:27 +00005349 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005350 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005351 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005352 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 Fn->setCallingConv(CC);
5354 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005355 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005356 Fn->setAlignment(Alignment);
5357 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005358 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005359 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005360 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005361 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005362 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005363 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005364
Chris Lattnerac161bf2009-01-02 07:01:27 +00005365 // Add all of the arguments we parsed to the function.
5366 Function::arg_iterator ArgIt = Fn->arg_begin();
5367 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5368 // If the argument has a name, insert it into the argument symbol table.
5369 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005370
Chris Lattnerac161bf2009-01-02 07:01:27 +00005371 // Set the name, if it conflicted, it will be auto-renamed.
5372 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005373
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005374 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5376 ArgList[i].Name + "'");
5377 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005378
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005379 if (isDefine)
5380 return false;
5381
Robin Morisset039781e2014-08-29 21:53:01 +00005382 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005383 ValID ID;
5384 if (FunctionName.empty()) {
5385 ID.Kind = ValID::t_GlobalID;
5386 ID.UIntVal = NumberedVals.size() - 1;
5387 } else {
5388 ID.Kind = ValID::t_GlobalName;
5389 ID.StrVal = FunctionName;
5390 }
5391 auto Blocks = ForwardRefBlockAddresses.find(ID);
5392 if (Blocks != ForwardRefBlockAddresses.end())
5393 return Error(Blocks->first.Loc,
5394 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005395 return false;
5396}
5397
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005398bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5399 ValID ID;
5400 if (FunctionNumber == -1) {
5401 ID.Kind = ValID::t_GlobalName;
5402 ID.StrVal = F.getName();
5403 } else {
5404 ID.Kind = ValID::t_GlobalID;
5405 ID.UIntVal = FunctionNumber;
5406 }
5407
5408 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5409 if (Blocks == P.ForwardRefBlockAddresses.end())
5410 return false;
5411
5412 for (const auto &I : Blocks->second) {
5413 const ValID &BBID = I.first;
5414 GlobalValue *GV = I.second;
5415
5416 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5417 "Expected local id or name");
5418 BasicBlock *BB;
5419 if (BBID.Kind == ValID::t_LocalName)
5420 BB = GetBB(BBID.StrVal, BBID.Loc);
5421 else
5422 BB = GetBB(BBID.UIntVal, BBID.Loc);
5423 if (!BB)
5424 return P.Error(BBID.Loc, "referenced value is not a basic block");
5425
5426 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5427 GV->eraseFromParent();
5428 }
5429
5430 P.ForwardRefBlockAddresses.erase(Blocks);
5431 return false;
5432}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005433
5434/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005435/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005436bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005437 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005438 return TokError("expected '{' in function body");
5439 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005440
Chris Lattner3432c622009-10-28 03:39:23 +00005441 int FunctionNumber = -1;
5442 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005443
Chris Lattner3432c622009-10-28 03:39:23 +00005444 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005445
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005446 // Resolve block addresses and allow basic blocks to be forward-declared
5447 // within this function.
5448 if (PFS.resolveForwardRefBlockAddresses())
5449 return true;
5450 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5451
Chris Lattnerbbddd962010-01-09 19:20:07 +00005452 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005453 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005454 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005455
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005456 while (Lex.getKind() != lltok::rbrace &&
5457 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005458 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005459
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005460 while (Lex.getKind() != lltok::rbrace)
5461 if (ParseUseListOrder(&PFS))
5462 return true;
5463
Chris Lattnerac161bf2009-01-02 07:01:27 +00005464 // Eat the }.
5465 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005466
Chris Lattnerac161bf2009-01-02 07:01:27 +00005467 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005468 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005469}
5470
5471/// ParseBasicBlock
5472/// ::= LabelStr? Instruction*
5473bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5474 // If this basic block starts out with a name, remember it.
5475 std::string Name;
5476 LocTy NameLoc = Lex.getLoc();
5477 if (Lex.getKind() == lltok::LabelStr) {
5478 Name = Lex.getStrVal();
5479 Lex.Lex();
5480 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005481
Chris Lattnerac161bf2009-01-02 07:01:27 +00005482 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005483 if (!BB)
5484 return Error(NameLoc,
5485 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005486
Chris Lattnerac161bf2009-01-02 07:01:27 +00005487 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005488
Chris Lattnerac161bf2009-01-02 07:01:27 +00005489 // Parse the instructions in this block until we get a terminator.
5490 Instruction *Inst;
5491 do {
5492 // This instruction may have three possibilities for a name: a) none
5493 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5494 LocTy NameLoc = Lex.getLoc();
5495 int NameID = -1;
5496 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005497
Chris Lattnerac161bf2009-01-02 07:01:27 +00005498 if (Lex.getKind() == lltok::LocalVarID) {
5499 NameID = Lex.getUIntVal();
5500 Lex.Lex();
5501 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5502 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005503 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005504 NameStr = Lex.getStrVal();
5505 Lex.Lex();
5506 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5507 return true;
5508 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005509
Chris Lattner77b89dc2009-12-30 05:23:43 +00005510 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005511 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005512 case InstError: return true;
5513 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005514 BB->getInstList().push_back(Inst);
5515
Chris Lattner77b89dc2009-12-30 05:23:43 +00005516 // With a normal result, we check to see if the instruction is followed by
5517 // a comma and metadata.
5518 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005519 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005520 return true;
5521 break;
5522 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005523 BB->getInstList().push_back(Inst);
5524
Chris Lattner77b89dc2009-12-30 05:23:43 +00005525 // If the instruction parser ate an extra comma at the end of it, it
5526 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005527 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005528 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005529 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005530 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005531
Chris Lattnerac161bf2009-01-02 07:01:27 +00005532 // Set the name on the instruction.
5533 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005534 } while (!Inst->isTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
Chris Lattnerac161bf2009-01-02 07:01:27 +00005536 return false;
5537}
5538
5539//===----------------------------------------------------------------------===//
5540// Instruction Parsing.
5541//===----------------------------------------------------------------------===//
5542
5543/// ParseInstruction - Parse one of the many different instructions.
5544///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005545int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5546 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547 lltok::Kind Token = Lex.getKind();
5548 if (Token == lltok::Eof)
5549 return TokError("found end of file when expecting more instructions");
5550 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005551 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005552 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005553
Chris Lattnerac161bf2009-01-02 07:01:27 +00005554 switch (Token) {
5555 default: return Error(Loc, "expected instruction opcode");
5556 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005557 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5559 case lltok::kw_br: return ParseBr(Inst, PFS);
5560 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005561 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005563 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005564 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5565 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005566 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5567 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005568 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Cameron McInallycbde0d92018-11-13 18:15:47 +00005569 // Unary Operators.
5570 case lltok::kw_fneg: {
5571 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5572 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, 2);
5573 if (Res != 0)
5574 return Res;
5575 if (FMF.any())
5576 Inst->setFastMathFlags(FMF);
5577 return false;
5578 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005579 // Binary Operators.
5580 case lltok::kw_add:
5581 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005582 case lltok::kw_mul:
5583 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005584 bool NUW = EatIfPresent(lltok::kw_nuw);
5585 bool NSW = EatIfPresent(lltok::kw_nsw);
5586 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005587
Chris Lattnera676c0f2011-02-07 16:40:21 +00005588 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005589
Chris Lattnera676c0f2011-02-07 16:40:21 +00005590 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5591 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5592 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005593 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005594 case lltok::kw_fadd:
5595 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005596 case lltok::kw_fmul:
5597 case lltok::kw_fdiv:
5598 case lltok::kw_frem: {
5599 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5600 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5601 if (Res != 0)
5602 return Res;
5603 if (FMF.any())
5604 Inst->setFastMathFlags(FMF);
5605 return 0;
5606 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005607
Chris Lattner35315d02011-02-06 21:44:57 +00005608 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005609 case lltok::kw_udiv:
5610 case lltok::kw_lshr:
5611 case lltok::kw_ashr: {
5612 bool Exact = EatIfPresent(lltok::kw_exact);
5613
5614 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5615 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5616 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005617 }
5618
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005620 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005621 case lltok::kw_and:
5622 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005623 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005624 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5625 case lltok::kw_fcmp: {
5626 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5627 int Res = ParseCompare(Inst, PFS, KeywordVal);
5628 if (Res != 0)
5629 return Res;
5630 if (FMF.any())
5631 Inst->setFastMathFlags(FMF);
5632 return 0;
5633 }
5634
Chris Lattnerac161bf2009-01-02 07:01:27 +00005635 // Casts.
5636 case lltok::kw_trunc:
5637 case lltok::kw_zext:
5638 case lltok::kw_sext:
5639 case lltok::kw_fptrunc:
5640 case lltok::kw_fpext:
5641 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005642 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005643 case lltok::kw_uitofp:
5644 case lltok::kw_sitofp:
5645 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005646 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005648 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005649 // Other.
5650 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005651 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005652 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5653 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5654 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5655 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005656 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005657 // Call.
5658 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5659 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5660 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005661 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005662 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005663 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005664 case lltok::kw_load: return ParseLoad(Inst, PFS);
5665 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005666 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5667 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005668 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005669 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5670 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5671 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5672 }
5673}
5674
5675/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5676bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005677 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005679 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005680 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5681 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5682 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5683 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5684 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5685 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5686 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5687 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5688 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5689 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5690 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5691 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5692 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5693 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5694 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5695 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5696 }
5697 } else {
5698 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005699 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5701 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5702 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5703 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5704 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5705 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5706 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5707 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5708 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5709 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5710 }
5711 }
5712 Lex.Lex();
5713 return false;
5714}
5715
5716//===----------------------------------------------------------------------===//
5717// Terminator Instructions.
5718//===----------------------------------------------------------------------===//
5719
5720/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005721/// ::= 'ret' void (',' !dbg, !1)*
5722/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005723bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005724 PerFunctionState &PFS) {
5725 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005726 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005727 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005728
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005729 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005730
Chris Lattnerfdd87902009-10-05 05:54:46 +00005731 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005732 if (!ResType->isVoidTy())
5733 return Error(TypeLoc, "value doesn't match function result type '" +
5734 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005735
Owen Anderson55f1c092009-08-13 21:58:54 +00005736 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005737 return false;
5738 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005739
Chris Lattnerac161bf2009-01-02 07:01:27 +00005740 Value *RV;
5741 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005742
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005743 if (ResType != RV->getType())
5744 return Error(TypeLoc, "value doesn't match function result type '" +
5745 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005746
Owen Anderson55f1c092009-08-13 21:58:54 +00005747 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005748 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749}
5750
Chris Lattnerac161bf2009-01-02 07:01:27 +00005751/// ParseBr
5752/// ::= 'br' TypeAndValue
5753/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5754bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5755 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005756 Value *Op0;
5757 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005758 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005759
Chris Lattnerac161bf2009-01-02 07:01:27 +00005760 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5761 Inst = BranchInst::Create(BB);
5762 return false;
5763 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005764
Owen Anderson55f1c092009-08-13 21:58:54 +00005765 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005766 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005767
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005769 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005770 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005771 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005772 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005773
Chris Lattner3ed871f2009-10-27 19:13:16 +00005774 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005775 return false;
5776}
5777
5778/// ParseSwitch
5779/// Instruction
5780/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5781/// JumpTable
5782/// ::= (TypeAndValue ',' TypeAndValue)*
5783bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5784 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005785 Value *Cond;
5786 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005787 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5788 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005789 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005790 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5791 return true;
5792
Duncan Sands19d0b472010-02-16 11:11:14 +00005793 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005794 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005795
Chris Lattnerac161bf2009-01-02 07:01:27 +00005796 // Parse the jump table pairs.
5797 SmallPtrSet<Value*, 32> SeenCases;
5798 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5799 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005800 Value *Constant;
5801 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005802
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5804 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005805 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005807
David Blaikie70573dc2014-11-19 07:49:26 +00005808 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005809 return Error(CondLoc, "duplicate case value in switch");
5810 if (!isa<ConstantInt>(Constant))
5811 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005812
Chris Lattner3ed871f2009-10-27 19:13:16 +00005813 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005814 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005815
Chris Lattnerac161bf2009-01-02 07:01:27 +00005816 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005817
Chris Lattner3ed871f2009-10-27 19:13:16 +00005818 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005819 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5820 SI->addCase(Table[i].first, Table[i].second);
5821 Inst = SI;
5822 return false;
5823}
5824
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005825/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005826/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005827/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5828bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005829 LocTy AddrLoc;
5830 Value *Address;
5831 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005832 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5833 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005834 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005835
Duncan Sands19d0b472010-02-16 11:11:14 +00005836 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005837 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005838
Chris Lattner3ed871f2009-10-27 19:13:16 +00005839 // Parse the destination list.
5840 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005841
Chris Lattner3ed871f2009-10-27 19:13:16 +00005842 if (Lex.getKind() != lltok::rsquare) {
5843 BasicBlock *DestBB;
5844 if (ParseTypeAndBasicBlock(DestBB, PFS))
5845 return true;
5846 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005847
Chris Lattner3ed871f2009-10-27 19:13:16 +00005848 while (EatIfPresent(lltok::comma)) {
5849 if (ParseTypeAndBasicBlock(DestBB, PFS))
5850 return true;
5851 DestList.push_back(DestBB);
5852 }
5853 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005854
Chris Lattner3ed871f2009-10-27 19:13:16 +00005855 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5856 return true;
5857
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005858 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005859 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5860 IBI->addDestination(DestList[i]);
5861 Inst = IBI;
5862 return false;
5863}
5864
Chris Lattnerac161bf2009-01-02 07:01:27 +00005865/// ParseInvoke
5866/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5867/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5868bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5869 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005870 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005871 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005872 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005873 unsigned CC;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005874 unsigned InvokeAddrSpace;
Craig Topper2617dcc2014-04-15 06:32:26 +00005875 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005876 LocTy RetTypeLoc;
5877 ValID CalleeID;
5878 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005879 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880
Chris Lattner3ed871f2009-10-27 19:13:16 +00005881 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005882 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005883 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005884 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005885 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005886 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5887 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005888 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005889 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005890 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005891 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005892 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005893 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005894
Chris Lattnerac161bf2009-01-02 07:01:27 +00005895 // If RetType is a non-function pointer type, then this is the short syntax
5896 // for the call, which means that RetType is just the return type. Infer the
5897 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005898 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5899 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005900 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005901 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005902 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5903 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005904
Chris Lattnerac161bf2009-01-02 07:01:27 +00005905 if (!FunctionType::isValidReturnType(RetType))
5906 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005907
Owen Anderson4056ca92009-07-29 22:17:13 +00005908 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005909 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005910
David Blaikie41ba2b42015-07-27 23:32:19 +00005911 CalleeID.FTy = Ty;
5912
Chris Lattnerac161bf2009-01-02 07:01:27 +00005913 // Look up the callee.
5914 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005915 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5916 Callee, &PFS, /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005917 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005918
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005919 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005920 SmallVector<Value *, 8> Args;
5921 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005922
Chris Lattnerac161bf2009-01-02 07:01:27 +00005923 // Loop through FunctionType's arguments and ensure they are specified
5924 // correctly. Also, gather any parameter attributes.
5925 FunctionType::param_iterator I = Ty->param_begin();
5926 FunctionType::param_iterator E = Ty->param_end();
5927 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005928 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005929 if (I != E) {
5930 ExpectedTy = *I++;
5931 } else if (!Ty->isVarArg()) {
5932 return Error(ArgList[i].Loc, "too many arguments specified");
5933 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005934
Chris Lattnerac161bf2009-01-02 07:01:27 +00005935 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5936 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005937 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005938 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005939 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005940 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005941
Chris Lattnerac161bf2009-01-02 07:01:27 +00005942 if (I != E)
5943 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005944
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005945 if (FnAttrs.hasAlignmentAttr())
5946 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005947
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005948 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005949 AttributeList PAL =
5950 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5951 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005952
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005953 InvokeInst *II =
5954 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005955 II->setCallingConv(CC);
5956 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005957 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005958 Inst = II;
5959 return false;
5960}
5961
Bill Wendlingf891bf82011-07-31 06:30:59 +00005962/// ParseResume
5963/// ::= 'resume' TypeAndValue
5964bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5965 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005966 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5967 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005968
Bill Wendlingf891bf82011-07-31 06:30:59 +00005969 ResumeInst *RI = ResumeInst::Create(Exn);
5970 Inst = RI;
5971 return false;
5972}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005973
David Majnemer654e1302015-07-31 17:58:14 +00005974bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5975 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005976 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005977 return true;
5978
5979 while (Lex.getKind() != lltok::rsquare) {
5980 // If this isn't the first argument, we need a comma.
5981 if (!Args.empty() &&
5982 ParseToken(lltok::comma, "expected ',' in argument list"))
5983 return true;
5984
5985 // Parse the argument.
5986 LocTy ArgLoc;
5987 Type *ArgTy = nullptr;
5988 if (ParseType(ArgTy, ArgLoc))
5989 return true;
5990
5991 Value *V;
5992 if (ArgTy->isMetadataTy()) {
5993 if (ParseMetadataAsValue(V, PFS))
5994 return true;
5995 } else {
5996 if (ParseValue(ArgTy, V, PFS))
5997 return true;
5998 }
5999 Args.push_back(V);
6000 }
6001
6002 Lex.Lex(); // Lex the ']'.
6003 return false;
6004}
6005
6006/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00006007/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00006008bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006009 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00006010
David Majnemer8a1c45d2015-12-12 05:38:55 +00006011 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6012 return true;
6013
6014 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006015 return true;
David Majnemer654e1302015-07-31 17:58:14 +00006016
6017 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6018 return true;
6019
6020 BasicBlock *UnwindBB = nullptr;
6021 if (Lex.getKind() == lltok::kw_to) {
6022 Lex.Lex();
6023 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6024 return true;
6025 } else {
6026 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6027 return true;
6028 }
6029 }
6030
David Majnemer8a1c45d2015-12-12 05:38:55 +00006031 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00006032 return false;
6033}
6034
6035/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00006036/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006037bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006038 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00006039
David Majnemer8a1c45d2015-12-12 05:38:55 +00006040 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6041 return true;
6042
6043 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00006044 return true;
6045
David Majnemer0bc0eef2015-08-15 02:46:08 +00006046 BasicBlock *BB;
6047 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6048 ParseTypeAndBasicBlock(BB, PFS))
6049 return true;
6050
David Majnemer8a1c45d2015-12-12 05:38:55 +00006051 Inst = CatchReturnInst::Create(CatchPad, BB);
6052 return false;
6053}
6054
6055/// ParseCatchSwitch
6056/// ::= 'catchswitch' within Parent
6057bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6058 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00006059
6060 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6061 return true;
6062
6063 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6064 Lex.getKind() != lltok::LocalVarID)
6065 return TokError("expected scope value for catchswitch");
6066
6067 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6068 return true;
6069
6070 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6071 return true;
6072
6073 SmallVector<BasicBlock *, 32> Table;
6074 do {
6075 BasicBlock *DestBB;
6076 if (ParseTypeAndBasicBlock(DestBB, PFS))
6077 return true;
6078 Table.push_back(DestBB);
6079 } while (EatIfPresent(lltok::comma));
6080
6081 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6082 return true;
6083
6084 if (ParseToken(lltok::kw_unwind,
6085 "expected 'unwind' after catchswitch scope"))
6086 return true;
6087
6088 BasicBlock *UnwindBB = nullptr;
6089 if (EatIfPresent(lltok::kw_to)) {
6090 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6091 return true;
6092 } else {
6093 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6094 return true;
6095 }
6096
6097 auto *CatchSwitch =
6098 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6099 for (BasicBlock *DestBB : Table)
6100 CatchSwitch->addHandler(DestBB);
6101 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00006102 return false;
6103}
6104
6105/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006106/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006107bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006108 Value *CatchSwitch = nullptr;
6109
6110 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6111 return true;
6112
6113 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6114 return TokError("expected scope value for catchpad");
6115
6116 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6117 return true;
6118
David Majnemer654e1302015-07-31 17:58:14 +00006119 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006120 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006121 return true;
6122
David Majnemer8a1c45d2015-12-12 05:38:55 +00006123 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00006124 return false;
6125}
6126
David Majnemer654e1302015-07-31 17:58:14 +00006127/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00006128/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00006129bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006130 Value *ParentPad = nullptr;
6131
6132 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6133 return true;
6134
6135 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6136 Lex.getKind() != lltok::LocalVarID)
6137 return TokError("expected scope value for cleanuppad");
6138
6139 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6140 return true;
6141
David Majnemer654e1302015-07-31 17:58:14 +00006142 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006143 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006144 return true;
6145
David Majnemer8a1c45d2015-12-12 05:38:55 +00006146 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00006147 return false;
6148}
6149
Chris Lattnerac161bf2009-01-02 07:01:27 +00006150//===----------------------------------------------------------------------===//
Cameron McInallycbde0d92018-11-13 18:15:47 +00006151// Unary Operators.
6152//===----------------------------------------------------------------------===//
6153
6154/// ParseUnaryOp
6155/// ::= UnaryOp TypeAndValue ',' Value
6156///
6157/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6158/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6159bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6160 unsigned Opc, unsigned OperandType) {
6161 LocTy Loc; Value *LHS;
6162 if (ParseTypeAndValue(LHS, Loc, PFS))
6163 return true;
6164
6165 bool Valid;
6166 switch (OperandType) {
6167 default: llvm_unreachable("Unknown operand type!");
6168 case 0: // int or FP.
6169 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6170 LHS->getType()->isFPOrFPVectorTy();
6171 break;
6172 case 1:
6173 Valid = LHS->getType()->isIntOrIntVectorTy();
6174 break;
6175 case 2:
6176 Valid = LHS->getType()->isFPOrFPVectorTy();
6177 break;
6178 }
6179
6180 if (!Valid)
6181 return Error(Loc, "invalid operand type for instruction");
6182
6183 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6184 return false;
6185}
6186
6187//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00006188// Binary Operators.
6189//===----------------------------------------------------------------------===//
6190
6191/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006192/// ::= ArithmeticOps TypeAndValue ',' Value
6193///
6194/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6195/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00006196bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006197 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006198 LocTy Loc; Value *LHS, *RHS;
6199 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6200 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6201 ParseValue(LHS->getType(), RHS, PFS))
6202 return true;
6203
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006204 bool Valid;
6205 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00006206 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006207 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00006208 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6209 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006210 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00006211 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6212 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006213 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006214
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006215 if (!Valid)
6216 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006217
Chris Lattnerac161bf2009-01-02 07:01:27 +00006218 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6219 return false;
6220}
6221
6222/// ParseLogical
6223/// ::= ArithmeticOps TypeAndValue ',' Value {
6224bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6225 unsigned Opc) {
6226 LocTy Loc; Value *LHS, *RHS;
6227 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6228 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6229 ParseValue(LHS->getType(), RHS, PFS))
6230 return true;
6231
Duncan Sands9dff9be2010-02-15 16:12:20 +00006232 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006233 return Error(Loc,"instruction requires integer or integer vector operands");
6234
6235 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6236 return false;
6237}
6238
Chris Lattnerac161bf2009-01-02 07:01:27 +00006239/// ParseCompare
6240/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6241/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006242bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6243 unsigned Opc) {
6244 // Parse the integer/fp comparison predicate.
6245 LocTy Loc;
6246 unsigned Pred;
6247 Value *LHS, *RHS;
6248 if (ParseCmpPredicate(Pred, Opc) ||
6249 ParseTypeAndValue(LHS, Loc, PFS) ||
6250 ParseToken(lltok::comma, "expected ',' after compare value") ||
6251 ParseValue(LHS->getType(), RHS, PFS))
6252 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006253
Chris Lattnerac161bf2009-01-02 07:01:27 +00006254 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006255 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006256 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006257 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006258 } else {
6259 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006260 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006261 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006262 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006263 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006264 }
6265 return false;
6266}
6267
6268//===----------------------------------------------------------------------===//
6269// Other Instructions.
6270//===----------------------------------------------------------------------===//
6271
6272
6273/// ParseCast
6274/// ::= CastOpc TypeAndValue 'to' Type
6275bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6276 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006277 LocTy Loc;
6278 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006279 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006280 if (ParseTypeAndValue(Op, Loc, PFS) ||
6281 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6282 ParseType(DestTy))
6283 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006284
Chris Lattner89d856e2009-03-01 00:53:13 +00006285 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6286 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006287 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006288 getTypeString(Op->getType()) + "' to '" +
6289 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006290 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006291 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6292 return false;
6293}
6294
6295/// ParseSelect
6296/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6297bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6298 LocTy Loc;
6299 Value *Op0, *Op1, *Op2;
6300 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6301 ParseToken(lltok::comma, "expected ',' after select condition") ||
6302 ParseTypeAndValue(Op1, PFS) ||
6303 ParseToken(lltok::comma, "expected ',' after select value") ||
6304 ParseTypeAndValue(Op2, PFS))
6305 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006306
Chris Lattnerac161bf2009-01-02 07:01:27 +00006307 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6308 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006309
Chris Lattnerac161bf2009-01-02 07:01:27 +00006310 Inst = SelectInst::Create(Op0, Op1, Op2);
6311 return false;
6312}
6313
Chris Lattnerb55ab542009-01-05 08:18:44 +00006314/// ParseVA_Arg
6315/// ::= 'va_arg' TypeAndValue ',' Type
6316bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006317 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006318 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006319 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006320 if (ParseTypeAndValue(Op, PFS) ||
6321 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006322 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006323 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006324
Chris Lattnerb55ab542009-01-05 08:18:44 +00006325 if (!EltTy->isFirstClassType())
6326 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006327
6328 Inst = new VAArgInst(Op, EltTy);
6329 return false;
6330}
6331
6332/// ParseExtractElement
6333/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6334bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6335 LocTy Loc;
6336 Value *Op0, *Op1;
6337 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6338 ParseToken(lltok::comma, "expected ',' after extract value") ||
6339 ParseTypeAndValue(Op1, PFS))
6340 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006341
Chris Lattnerac161bf2009-01-02 07:01:27 +00006342 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6343 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006344
Eric Christopherc9742252009-07-25 02:28:41 +00006345 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006346 return false;
6347}
6348
6349/// ParseInsertElement
6350/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6351bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6352 LocTy Loc;
6353 Value *Op0, *Op1, *Op2;
6354 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6355 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6356 ParseTypeAndValue(Op1, PFS) ||
6357 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6358 ParseTypeAndValue(Op2, PFS))
6359 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006360
Chris Lattnerac161bf2009-01-02 07:01:27 +00006361 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006362 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006363
Chris Lattnerac161bf2009-01-02 07:01:27 +00006364 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6365 return false;
6366}
6367
6368/// ParseShuffleVector
6369/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6370bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6371 LocTy Loc;
6372 Value *Op0, *Op1, *Op2;
6373 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6374 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6375 ParseTypeAndValue(Op1, PFS) ||
6376 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6377 ParseTypeAndValue(Op2, PFS))
6378 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006379
Chris Lattnerac161bf2009-01-02 07:01:27 +00006380 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006381 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006382
Chris Lattnerac161bf2009-01-02 07:01:27 +00006383 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6384 return false;
6385}
6386
6387/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006388/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006389int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006390 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006393 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006394 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6395 ParseValue(Ty, Op0, PFS) ||
6396 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006397 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006398 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6399 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006400
Chris Lattnerf4f03422009-12-30 05:27:33 +00006401 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006403
6404 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006405 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006406
Chris Lattner3822f632009-01-02 08:05:26 +00006407 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006408 break;
6409
Chris Lattnerf4f03422009-12-30 05:27:33 +00006410 if (Lex.getKind() == lltok::MetadataVar) {
6411 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006412 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006413 }
Devang Patel8f842d32009-10-16 18:45:49 +00006414
Chris Lattner3822f632009-01-02 08:05:26 +00006415 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006416 ParseValue(Ty, Op0, PFS) ||
6417 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006418 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006419 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6420 return true;
6421 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006422
Chris Lattnerac161bf2009-01-02 07:01:27 +00006423 if (!Ty->isFirstClassType())
6424 return Error(TypeLoc, "phi node must have first class type");
6425
Jay Foad52131342011-03-30 11:28:46 +00006426 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006427 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6428 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6429 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006430 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006431}
6432
Bill Wendlingfae14752011-08-12 20:24:12 +00006433/// ParseLandingPad
6434/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6435/// Clause
6436/// ::= 'catch' TypeAndValue
6437/// ::= 'filter'
6438/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6439bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006440 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006441
David Majnemer7fddecc2015-06-17 20:52:32 +00006442 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006443 return true;
6444
David Majnemer7fddecc2015-06-17 20:52:32 +00006445 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006446 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6447
6448 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6449 LandingPadInst::ClauseType CT;
6450 if (EatIfPresent(lltok::kw_catch))
6451 CT = LandingPadInst::Catch;
6452 else if (EatIfPresent(lltok::kw_filter))
6453 CT = LandingPadInst::Filter;
6454 else
6455 return TokError("expected 'catch' or 'filter' clause type");
6456
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006457 Value *V;
6458 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006459 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006460 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006461
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006462 // A 'catch' type expects a non-array constant. A filter clause expects an
6463 // array constant.
6464 if (CT == LandingPadInst::Catch) {
6465 if (isa<ArrayType>(V->getType()))
6466 Error(VLoc, "'catch' clause has an invalid type");
6467 } else {
6468 if (!isa<ArrayType>(V->getType()))
6469 Error(VLoc, "'filter' clause has an invalid type");
6470 }
6471
Owen Andersonf8f259d2015-03-09 07:13:42 +00006472 Constant *CV = dyn_cast<Constant>(V);
6473 if (!CV)
6474 return Error(VLoc, "clause argument must be a constant");
6475 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006476 }
6477
Owen Andersonf8f259d2015-03-09 07:13:42 +00006478 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006479 return false;
6480}
6481
Chris Lattnerac161bf2009-01-02 07:01:27 +00006482/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006483/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6484/// OptionalAttrs Type Value ParameterList OptionalAttrs
6485/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6486/// OptionalAttrs Type Value ParameterList OptionalAttrs
6487/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6488/// OptionalAttrs Type Value ParameterList OptionalAttrs
6489/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6490/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006491bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006492 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006493 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006494 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006495 LocTy BuiltinLoc;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006496 unsigned CallAddrSpace;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006497 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006498 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006499 LocTy RetTypeLoc;
6500 ValID CalleeID;
6501 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006502 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006503 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006504
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006505 if (TCK != CallInst::TCK_None &&
6506 ParseToken(lltok::kw_call,
6507 "expected 'tail call', 'musttail call', or 'notail call'"))
6508 return true;
6509
6510 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6511
6512 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006513 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006514 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006515 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006516 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6517 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006518 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6519 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006520 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006521
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006522 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6523 return Error(CallLoc, "fast-math-flags specified for call without "
6524 "floating-point scalar or vector return type");
6525
Chris Lattnerac161bf2009-01-02 07:01:27 +00006526 // If RetType is a non-function pointer type, then this is the short syntax
6527 // for the call, which means that RetType is just the return type. Infer the
6528 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006529 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6530 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006531 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006532 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006533 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6534 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006535
Chris Lattnerac161bf2009-01-02 07:01:27 +00006536 if (!FunctionType::isValidReturnType(RetType))
6537 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006538
Owen Anderson4056ca92009-07-29 22:17:13 +00006539 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006540 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006541
David Blaikie41ba2b42015-07-27 23:32:19 +00006542 CalleeID.FTy = Ty;
6543
Chris Lattnerac161bf2009-01-02 07:01:27 +00006544 // Look up the callee.
6545 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006546 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6547 &PFS, /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006548 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006549
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006550 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006551 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006552
Chris Lattnerac161bf2009-01-02 07:01:27 +00006553 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006554
Chris Lattnerac161bf2009-01-02 07:01:27 +00006555 // Loop through FunctionType's arguments and ensure they are specified
6556 // correctly. Also, gather any parameter attributes.
6557 FunctionType::param_iterator I = Ty->param_begin();
6558 FunctionType::param_iterator E = Ty->param_end();
6559 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006560 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006561 if (I != E) {
6562 ExpectedTy = *I++;
6563 } else if (!Ty->isVarArg()) {
6564 return Error(ArgList[i].Loc, "too many arguments specified");
6565 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006566
Chris Lattnerac161bf2009-01-02 07:01:27 +00006567 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6568 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006569 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006570 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006571 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006572 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006573
Chris Lattnerac161bf2009-01-02 07:01:27 +00006574 if (I != E)
6575 return Error(CallLoc, "not enough parameters specified for call");
6576
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006577 if (FnAttrs.hasAlignmentAttr())
6578 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006579
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006580 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006581 AttributeList PAL =
6582 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6583 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006584
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006585 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006586 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006587 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006588 if (FMF.any())
6589 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006590 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006591 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006592 Inst = CI;
6593 return false;
6594}
6595
6596//===----------------------------------------------------------------------===//
6597// Memory Instructions.
6598//===----------------------------------------------------------------------===//
6599
6600/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006601/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006602/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006603int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006604 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006605 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006606 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006607 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006608 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006609
6610 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006611 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006612
David Majnemera3b0eb22015-02-16 08:38:03 +00006613 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006614
David Majnemera3b0eb22015-02-16 08:38:03 +00006615 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6616 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006617
Chris Lattnerb2f39502009-12-30 05:44:30 +00006618 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006619 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006620 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006621 if (ParseOptionalAlignment(Alignment))
6622 return true;
6623 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6624 return true;
6625 } else if (Lex.getKind() == lltok::kw_addrspace) {
6626 ASLoc = Lex.getLoc();
6627 if (ParseOptionalAddrSpace(AddrSpace))
6628 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006629 } else if (Lex.getKind() == lltok::MetadataVar) {
6630 AteExtraComma = true;
6631 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006632 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006633 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006634 if (EatIfPresent(lltok::comma)) {
6635 if (Lex.getKind() == lltok::kw_align) {
6636 if (ParseOptionalAlignment(Alignment))
6637 return true;
6638 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6639 return true;
6640 } else if (Lex.getKind() == lltok::kw_addrspace) {
6641 ASLoc = Lex.getLoc();
6642 if (ParseOptionalAddrSpace(AddrSpace))
6643 return true;
6644 } else if (Lex.getKind() == lltok::MetadataVar) {
6645 AteExtraComma = true;
6646 }
6647 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006648 }
6649 }
6650
Dan Gohman2140a742010-05-28 01:14:11 +00006651 if (Size && !Size->getType()->isIntegerTy())
6652 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006653
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006654 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006655 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006656 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006657 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006658 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006659}
6660
6661/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006662/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006663/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006664/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006665int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006666 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006667 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006668 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006669 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006670 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006671 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006672
6673 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006674 isAtomic = true;
6675 Lex.Lex();
6676 }
6677
Chris Lattnerbc639292011-11-27 06:56:53 +00006678 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006679 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006680 isVolatile = true;
6681 Lex.Lex();
6682 }
6683
David Blaikie15d9a4c2015-04-06 20:59:48 +00006684 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006685 LocTy ExplicitTypeLoc = Lex.getLoc();
6686 if (ParseType(Ty) ||
6687 ParseToken(lltok::comma, "expected comma after load's type") ||
6688 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006689 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006690 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6691 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006692
David Blaikie15d9a4c2015-04-06 20:59:48 +00006693 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006694 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006695 if (isAtomic && !Alignment)
6696 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006697 if (Ordering == AtomicOrdering::Release ||
6698 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006699 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006700
David Blaikiea79ac142015-02-27 21:17:42 +00006701 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6702 return Error(ExplicitTypeLoc,
6703 "explicit pointee type doesn't match operand's pointee type");
6704
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006705 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006706 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006707}
6708
6709/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006710
6711/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6712/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006713/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006714int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006715 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006716 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006717 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006718 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006719 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006720 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006721
6722 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006723 isAtomic = true;
6724 Lex.Lex();
6725 }
6726
Chris Lattnerbc639292011-11-27 06:56:53 +00006727 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006728 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006729 isVolatile = true;
6730 Lex.Lex();
6731 }
6732
Chris Lattnerac161bf2009-01-02 07:01:27 +00006733 if (ParseTypeAndValue(Val, Loc, PFS) ||
6734 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006735 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006736 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006737 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006738 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006739
Duncan Sands19d0b472010-02-16 11:11:14 +00006740 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006741 return Error(PtrLoc, "store operand must be a pointer");
6742 if (!Val->getType()->isFirstClassType())
6743 return Error(Loc, "store operand must be a first class value");
6744 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6745 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006746 if (isAtomic && !Alignment)
6747 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006748 if (Ordering == AtomicOrdering::Acquire ||
6749 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006750 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006751
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006752 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006753 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006754}
6755
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006756/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006757/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6758/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006759int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006760 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6761 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006762 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6763 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006764 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006765 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006766 bool isWeak = false;
6767
6768 if (EatIfPresent(lltok::kw_weak))
6769 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006770
6771 if (EatIfPresent(lltok::kw_volatile))
6772 isVolatile = true;
6773
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006774 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6775 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6776 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6777 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6778 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006779 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006780 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006781 return true;
6782
JF Bastien800f87a2016-04-06 21:19:33 +00006783 if (SuccessOrdering == AtomicOrdering::Unordered ||
6784 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006785 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006786 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6787 return TokError("cmpxchg failure argument shall be no stronger than the "
6788 "success argument");
6789 if (FailureOrdering == AtomicOrdering::Release ||
6790 FailureOrdering == AtomicOrdering::AcquireRelease)
6791 return TokError(
6792 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006793 if (!Ptr->getType()->isPointerTy())
6794 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6795 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6796 return Error(CmpLoc, "compare value and pointer type do not match");
6797 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6798 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006799 if (!New->getType()->isFirstClassType())
6800 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006801 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006802 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006803 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006804 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006805 Inst = CXI;
6806 return AteExtraComma ? InstExtraComma : InstNormal;
6807}
6808
6809/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006810/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6811/// 'singlethread'? AtomicOrdering
6812int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006813 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6814 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006815 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006816 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006817 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006818 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006819
6820 if (EatIfPresent(lltok::kw_volatile))
6821 isVolatile = true;
6822
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006823 switch (Lex.getKind()) {
6824 default: return TokError("expected binary operation in atomicrmw");
6825 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6826 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6827 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6828 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6829 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6830 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6831 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6832 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6833 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6834 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6835 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6836 }
6837 Lex.Lex(); // Eat the operation.
6838
6839 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6840 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6841 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006842 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006843 return true;
6844
JF Bastien800f87a2016-04-06 21:19:33 +00006845 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006846 return TokError("atomicrmw cannot be unordered");
6847 if (!Ptr->getType()->isPointerTy())
6848 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6849 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6850 return Error(ValLoc, "atomicrmw value and pointer type do not match");
Matt Arsenault0f83d662018-10-03 02:37:15 +00006851
Matt Arsenault0cb08e42019-01-17 10:49:01 +00006852 if (Operation != AtomicRMWInst::Xchg && !Val->getType()->isIntegerTy()) {
Matt Arsenault0f83d662018-10-03 02:37:15 +00006853 return Error(ValLoc, "atomicrmw " +
6854 AtomicRMWInst::getOperationName(Operation) +
6855 " operand must be an integer");
6856 }
6857
Matt Arsenault0cb08e42019-01-17 10:49:01 +00006858 if (Operation == AtomicRMWInst::Xchg &&
6859 !Val->getType()->isIntegerTy() &&
6860 !Val->getType()->isFloatingPointTy()) {
6861 return Error(ValLoc, "atomicrmw " +
6862 AtomicRMWInst::getOperationName(Operation) +
6863 " operand must be an integer or floating point type");
6864 }
6865
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006866 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6867 if (Size < 8 || (Size & (Size - 1)))
6868 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6869 " integer");
6870
6871 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006872 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006873 RMWI->setVolatile(isVolatile);
6874 Inst = RMWI;
6875 return AteExtraComma ? InstExtraComma : InstNormal;
6876}
6877
Eli Friedmanfee02c62011-07-25 23:16:38 +00006878/// ParseFence
6879/// ::= 'fence' 'singlethread'? AtomicOrdering
6880int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006881 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006882 SyncScope::ID SSID = SyncScope::System;
6883 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006884 return true;
6885
JF Bastien800f87a2016-04-06 21:19:33 +00006886 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006887 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006888 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006889 return TokError("fence cannot be monotonic");
6890
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006891 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006892 return InstNormal;
6893}
6894
Chris Lattnerac161bf2009-01-02 07:01:27 +00006895/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006896/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006897int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006898 Value *Ptr = nullptr;
6899 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006900 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006901
Dan Gohman16cbbe42009-07-29 15:58:36 +00006902 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006903
David Blaikie79e6c742015-02-27 19:29:02 +00006904 Type *Ty = nullptr;
6905 LocTy ExplicitTypeLoc = Lex.getLoc();
6906 if (ParseType(Ty) ||
6907 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6908 ParseTypeAndValue(Ptr, Loc, PFS))
6909 return true;
6910
Eli Benderskyd9806682013-04-22 17:03:42 +00006911 Type *BaseType = Ptr->getType();
6912 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6913 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006914 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006915
David Blaikie8d757942015-03-09 23:08:44 +00006916 if (Ty != BasePointerType->getElementType())
6917 return Error(ExplicitTypeLoc,
6918 "explicit pointee type doesn't match operand's pointee type");
6919
Chris Lattnerac161bf2009-01-02 07:01:27 +00006920 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006921 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006922 // GEP returns a vector of pointers if at least one of parameters is a vector.
6923 // All vector parameters should have the same vector width.
6924 unsigned GEPWidth = BaseType->isVectorTy() ?
6925 BaseType->getVectorNumElements() : 0;
6926
Chris Lattner3822f632009-01-02 08:05:26 +00006927 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006928 if (Lex.getKind() == lltok::MetadataVar) {
6929 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006930 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006931 }
Chris Lattner3822f632009-01-02 08:05:26 +00006932 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006933 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006934 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006935
Nadav Rotem3924cb02011-12-05 06:29:09 +00006936 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006937 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6938 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006939 return Error(EltLoc,
6940 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006941 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006942 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006943 Indices.push_back(Val);
6944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006945
Craig Toppere3dcce92015-08-01 22:20:21 +00006946 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006947 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006948 return Error(Loc, "base element of getelementptr must be sized");
6949
David Blaikied33bad32015-04-17 22:32:13 +00006950 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006951 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006952 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006953 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006954 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006955 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006956}
6957
6958/// ParseExtractValue
6959/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006960int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006961 Value *Val; LocTy Loc;
6962 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006963 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006964 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006965 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006966 return true;
6967
Chris Lattner392be582010-02-12 20:49:41 +00006968 if (!Val->getType()->isAggregateType())
6969 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006970
Jay Foad57aa6362011-07-13 10:26:04 +00006971 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006972 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006973 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006974 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006975}
6976
6977/// ParseInsertValue
6978/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006979int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006980 Value *Val0, *Val1; LocTy Loc0, Loc1;
6981 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006982 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006983 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6984 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6985 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006986 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006987 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006988
Chris Lattner392be582010-02-12 20:49:41 +00006989 if (!Val0->getType()->isAggregateType())
6990 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006991
David Majnemer30074532015-02-11 07:43:58 +00006992 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6993 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006994 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006995 if (IndexedType != Val1->getType())
6996 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6997 getTypeString(Val1->getType()) + "' instead of '" +
6998 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006999 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00007000 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007001}
Nick Lewycky49f89192009-04-04 07:22:01 +00007002
7003//===----------------------------------------------------------------------===//
7004// Embedded metadata.
7005//===----------------------------------------------------------------------===//
7006
7007/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007008/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00007009/// Element
7010/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007011bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00007012 if (ParseToken(lltok::lbrace, "expected '{' here"))
7013 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007014
Dan Gohman1e0213a2010-07-13 19:33:27 +00007015 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007016 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00007017 return false;
7018
Nick Lewycky49f89192009-04-04 07:22:01 +00007019 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00007020 // Null is a special case since it is typeless.
7021 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00007022 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00007023 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00007024 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00007025
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007026 Metadata *MD;
7027 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007028 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007029 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00007030 } while (EatIfPresent(lltok::comma));
7031
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007032 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00007033}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007034
7035//===----------------------------------------------------------------------===//
7036// Use-list order directives.
7037//===----------------------------------------------------------------------===//
7038bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7039 SMLoc Loc) {
7040 if (V->use_empty())
7041 return Error(Loc, "value has no uses");
7042
7043 unsigned NumUses = 0;
7044 SmallDenseMap<const Use *, unsigned, 16> Order;
7045 for (const Use &U : V->uses()) {
7046 if (++NumUses > Indexes.size())
7047 break;
7048 Order[&U] = Indexes[NumUses - 1];
7049 }
7050 if (NumUses < 2)
7051 return Error(Loc, "value only has one use");
7052 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00007053 return Error(Loc,
7054 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007055
7056 V->sortUseList([&](const Use &L, const Use &R) {
7057 return Order.lookup(&L) < Order.lookup(&R);
7058 });
7059 return false;
7060}
7061
7062/// ParseUseListOrderIndexes
7063/// ::= '{' uint32 (',' uint32)+ '}'
7064bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7065 SMLoc Loc = Lex.getLoc();
7066 if (ParseToken(lltok::lbrace, "expected '{' here"))
7067 return true;
7068 if (Lex.getKind() == lltok::rbrace)
7069 return Lex.Error("expected non-empty list of uselistorder indexes");
7070
7071 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7072 // indexes should be distinct numbers in the range [0, size-1], and should
7073 // not be in order.
7074 unsigned Offset = 0;
7075 unsigned Max = 0;
7076 bool IsOrdered = true;
7077 assert(Indexes.empty() && "Expected empty order vector");
7078 do {
7079 unsigned Index;
7080 if (ParseUInt32(Index))
7081 return true;
7082
7083 // Update consistency checks.
7084 Offset += Index - Indexes.size();
7085 Max = std::max(Max, Index);
7086 IsOrdered &= Index == Indexes.size();
7087
7088 Indexes.push_back(Index);
7089 } while (EatIfPresent(lltok::comma));
7090
7091 if (ParseToken(lltok::rbrace, "expected '}' here"))
7092 return true;
7093
7094 if (Indexes.size() < 2)
7095 return Error(Loc, "expected >= 2 uselistorder indexes");
7096 if (Offset != 0 || Max >= Indexes.size())
7097 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7098 if (IsOrdered)
7099 return Error(Loc, "expected uselistorder indexes to change the order");
7100
7101 return false;
7102}
7103
7104/// ParseUseListOrder
7105/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7106bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7107 SMLoc Loc = Lex.getLoc();
7108 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7109 return true;
7110
7111 Value *V;
7112 SmallVector<unsigned, 16> Indexes;
7113 if (ParseTypeAndValue(V, PFS) ||
7114 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7115 ParseUseListOrderIndexes(Indexes))
7116 return true;
7117
7118 return sortUseListOrder(V, Indexes, Loc);
7119}
7120
7121/// ParseUseListOrderBB
7122/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7123bool LLParser::ParseUseListOrderBB() {
7124 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7125 SMLoc Loc = Lex.getLoc();
7126 Lex.Lex();
7127
7128 ValID Fn, Label;
7129 SmallVector<unsigned, 16> Indexes;
7130 if (ParseValID(Fn) ||
7131 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7132 ParseValID(Label) ||
7133 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7134 ParseUseListOrderIndexes(Indexes))
7135 return true;
7136
7137 // Check the function.
7138 GlobalValue *GV;
7139 if (Fn.Kind == ValID::t_GlobalName)
7140 GV = M->getNamedValue(Fn.StrVal);
7141 else if (Fn.Kind == ValID::t_GlobalID)
7142 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7143 else
7144 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7145 if (!GV)
7146 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7147 auto *F = dyn_cast<Function>(GV);
7148 if (!F)
7149 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7150 if (F->isDeclaration())
7151 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7152
7153 // Check the basic block.
7154 if (Label.Kind == ValID::t_LocalID)
7155 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7156 if (Label.Kind != ValID::t_LocalName)
7157 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00007158 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007159 if (!V)
7160 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7161 if (!isa<BasicBlock>(V))
7162 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7163
7164 return sortUseListOrder(V, Indexes, Loc);
7165}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007166
7167/// ModuleEntry
7168/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7169/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7170bool LLParser::ParseModuleEntry(unsigned ID) {
7171 assert(Lex.getKind() == lltok::kw_module);
7172 Lex.Lex();
7173
7174 std::string Path;
7175 if (ParseToken(lltok::colon, "expected ':' here") ||
7176 ParseToken(lltok::lparen, "expected '(' here") ||
7177 ParseToken(lltok::kw_path, "expected 'path' here") ||
7178 ParseToken(lltok::colon, "expected ':' here") ||
7179 ParseStringConstant(Path) ||
7180 ParseToken(lltok::comma, "expected ',' here") ||
7181 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7182 ParseToken(lltok::colon, "expected ':' here") ||
7183 ParseToken(lltok::lparen, "expected '(' here"))
7184 return true;
7185
7186 ModuleHash Hash;
7187 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7188 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7189 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7190 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7191 ParseUInt32(Hash[4]))
7192 return true;
7193
7194 if (ParseToken(lltok::rparen, "expected ')' here") ||
7195 ParseToken(lltok::rparen, "expected ')' here"))
7196 return true;
7197
7198 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7199 ModuleIdMap[ID] = ModuleEntry->first();
7200
7201 return false;
7202}
7203
7204/// TypeIdEntry
7205/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7206bool LLParser::ParseTypeIdEntry(unsigned ID) {
7207 assert(Lex.getKind() == lltok::kw_typeid);
7208 Lex.Lex();
7209
7210 std::string Name;
7211 if (ParseToken(lltok::colon, "expected ':' here") ||
7212 ParseToken(lltok::lparen, "expected '(' here") ||
7213 ParseToken(lltok::kw_name, "expected 'name' here") ||
7214 ParseToken(lltok::colon, "expected ':' here") ||
7215 ParseStringConstant(Name))
7216 return true;
7217
7218 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7219 if (ParseToken(lltok::comma, "expected ',' here") ||
7220 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7221 return true;
7222
7223 // Check if this ID was forward referenced, and if so, update the
7224 // corresponding GUIDs.
7225 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7226 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7227 for (auto TIDRef : FwdRefTIDs->second) {
7228 assert(!*TIDRef.first &&
7229 "Forward referenced type id GUID expected to be 0");
7230 *TIDRef.first = GlobalValue::getGUID(Name);
7231 }
7232 ForwardRefTypeIds.erase(FwdRefTIDs);
7233 }
7234
7235 return false;
7236}
7237
7238/// TypeIdSummary
7239/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7240bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7241 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7242 ParseToken(lltok::colon, "expected ':' here") ||
7243 ParseToken(lltok::lparen, "expected '(' here") ||
7244 ParseTypeTestResolution(TIS.TTRes))
7245 return true;
7246
7247 if (EatIfPresent(lltok::comma)) {
7248 // Expect optional wpdResolutions field
7249 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7250 return true;
7251 }
7252
7253 if (ParseToken(lltok::rparen, "expected ')' here"))
7254 return true;
7255
7256 return false;
7257}
7258
7259/// TypeTestResolution
7260/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7261/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7262/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7263/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7264/// [',' 'inlinesBits' ':' UInt64]? ')'
7265bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7266 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7267 ParseToken(lltok::colon, "expected ':' here") ||
7268 ParseToken(lltok::lparen, "expected '(' here") ||
7269 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7270 ParseToken(lltok::colon, "expected ':' here"))
7271 return true;
7272
7273 switch (Lex.getKind()) {
7274 case lltok::kw_unsat:
7275 TTRes.TheKind = TypeTestResolution::Unsat;
7276 break;
7277 case lltok::kw_byteArray:
7278 TTRes.TheKind = TypeTestResolution::ByteArray;
7279 break;
7280 case lltok::kw_inline:
7281 TTRes.TheKind = TypeTestResolution::Inline;
7282 break;
7283 case lltok::kw_single:
7284 TTRes.TheKind = TypeTestResolution::Single;
7285 break;
7286 case lltok::kw_allOnes:
7287 TTRes.TheKind = TypeTestResolution::AllOnes;
7288 break;
7289 default:
7290 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7291 }
7292 Lex.Lex();
7293
7294 if (ParseToken(lltok::comma, "expected ',' here") ||
7295 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7296 ParseToken(lltok::colon, "expected ':' here") ||
7297 ParseUInt32(TTRes.SizeM1BitWidth))
7298 return true;
7299
7300 // Parse optional fields
7301 while (EatIfPresent(lltok::comma)) {
7302 switch (Lex.getKind()) {
7303 case lltok::kw_alignLog2:
7304 Lex.Lex();
7305 if (ParseToken(lltok::colon, "expected ':'") ||
7306 ParseUInt64(TTRes.AlignLog2))
7307 return true;
7308 break;
7309 case lltok::kw_sizeM1:
7310 Lex.Lex();
7311 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7312 return true;
7313 break;
7314 case lltok::kw_bitMask: {
7315 unsigned Val;
7316 Lex.Lex();
7317 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7318 return true;
7319 assert(Val <= 0xff);
7320 TTRes.BitMask = (uint8_t)Val;
7321 break;
7322 }
7323 case lltok::kw_inlineBits:
7324 Lex.Lex();
7325 if (ParseToken(lltok::colon, "expected ':'") ||
7326 ParseUInt64(TTRes.InlineBits))
7327 return true;
7328 break;
7329 default:
7330 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7331 }
7332 }
7333
7334 if (ParseToken(lltok::rparen, "expected ')' here"))
7335 return true;
7336
7337 return false;
7338}
7339
7340/// OptionalWpdResolutions
7341/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7342/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7343bool LLParser::ParseOptionalWpdResolutions(
7344 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7345 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7346 ParseToken(lltok::colon, "expected ':' here") ||
7347 ParseToken(lltok::lparen, "expected '(' here"))
7348 return true;
7349
7350 do {
7351 uint64_t Offset;
7352 WholeProgramDevirtResolution WPDRes;
7353 if (ParseToken(lltok::lparen, "expected '(' here") ||
7354 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7355 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7356 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7357 ParseToken(lltok::rparen, "expected ')' here"))
7358 return true;
7359 WPDResMap[Offset] = WPDRes;
7360 } while (EatIfPresent(lltok::comma));
7361
7362 if (ParseToken(lltok::rparen, "expected ')' here"))
7363 return true;
7364
7365 return false;
7366}
7367
7368/// WpdRes
7369/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7370/// [',' OptionalResByArg]? ')'
7371/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7372/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7373/// [',' OptionalResByArg]? ')'
7374/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7375/// [',' OptionalResByArg]? ')'
7376bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7377 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7378 ParseToken(lltok::colon, "expected ':' here") ||
7379 ParseToken(lltok::lparen, "expected '(' here") ||
7380 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7381 ParseToken(lltok::colon, "expected ':' here"))
7382 return true;
7383
7384 switch (Lex.getKind()) {
7385 case lltok::kw_indir:
7386 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7387 break;
7388 case lltok::kw_singleImpl:
7389 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7390 break;
7391 case lltok::kw_branchFunnel:
7392 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7393 break;
7394 default:
7395 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7396 }
7397 Lex.Lex();
7398
7399 // Parse optional fields
7400 while (EatIfPresent(lltok::comma)) {
7401 switch (Lex.getKind()) {
7402 case lltok::kw_singleImplName:
7403 Lex.Lex();
7404 if (ParseToken(lltok::colon, "expected ':' here") ||
7405 ParseStringConstant(WPDRes.SingleImplName))
7406 return true;
7407 break;
7408 case lltok::kw_resByArg:
7409 if (ParseOptionalResByArg(WPDRes.ResByArg))
7410 return true;
7411 break;
7412 default:
7413 return Error(Lex.getLoc(),
7414 "expected optional WholeProgramDevirtResolution field");
7415 }
7416 }
7417
7418 if (ParseToken(lltok::rparen, "expected ')' here"))
7419 return true;
7420
7421 return false;
7422}
7423
7424/// OptionalResByArg
7425/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7426/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7427/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7428/// 'virtualConstProp' )
7429/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7430/// [',' 'bit' ':' UInt32]? ')'
7431bool LLParser::ParseOptionalResByArg(
7432 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7433 &ResByArg) {
7434 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7435 ParseToken(lltok::colon, "expected ':' here") ||
7436 ParseToken(lltok::lparen, "expected '(' here"))
7437 return true;
7438
7439 do {
7440 std::vector<uint64_t> Args;
7441 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7442 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7443 ParseToken(lltok::colon, "expected ':' here") ||
7444 ParseToken(lltok::lparen, "expected '(' here") ||
7445 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7446 ParseToken(lltok::colon, "expected ':' here"))
7447 return true;
7448
7449 WholeProgramDevirtResolution::ByArg ByArg;
7450 switch (Lex.getKind()) {
7451 case lltok::kw_indir:
7452 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7453 break;
7454 case lltok::kw_uniformRetVal:
7455 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7456 break;
7457 case lltok::kw_uniqueRetVal:
7458 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7459 break;
7460 case lltok::kw_virtualConstProp:
7461 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7462 break;
7463 default:
7464 return Error(Lex.getLoc(),
7465 "unexpected WholeProgramDevirtResolution::ByArg kind");
7466 }
7467 Lex.Lex();
7468
7469 // Parse optional fields
7470 while (EatIfPresent(lltok::comma)) {
7471 switch (Lex.getKind()) {
7472 case lltok::kw_info:
7473 Lex.Lex();
7474 if (ParseToken(lltok::colon, "expected ':' here") ||
7475 ParseUInt64(ByArg.Info))
7476 return true;
7477 break;
7478 case lltok::kw_byte:
7479 Lex.Lex();
7480 if (ParseToken(lltok::colon, "expected ':' here") ||
7481 ParseUInt32(ByArg.Byte))
7482 return true;
7483 break;
7484 case lltok::kw_bit:
7485 Lex.Lex();
7486 if (ParseToken(lltok::colon, "expected ':' here") ||
7487 ParseUInt32(ByArg.Bit))
7488 return true;
7489 break;
7490 default:
7491 return Error(Lex.getLoc(),
7492 "expected optional whole program devirt field");
7493 }
7494 }
7495
7496 if (ParseToken(lltok::rparen, "expected ')' here"))
7497 return true;
7498
7499 ResByArg[Args] = ByArg;
7500 } while (EatIfPresent(lltok::comma));
7501
7502 if (ParseToken(lltok::rparen, "expected ')' here"))
7503 return true;
7504
7505 return false;
7506}
7507
7508/// OptionalResByArg
7509/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7510bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7511 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7512 ParseToken(lltok::colon, "expected ':' here") ||
7513 ParseToken(lltok::lparen, "expected '(' here"))
7514 return true;
7515
7516 do {
7517 uint64_t Val;
7518 if (ParseUInt64(Val))
7519 return true;
7520 Args.push_back(Val);
7521 } while (EatIfPresent(lltok::comma));
7522
7523 if (ParseToken(lltok::rparen, "expected ')' here"))
7524 return true;
7525
7526 return false;
7527}
7528
Benjamin Kramerb17d2132019-01-12 18:36:22 +00007529static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
Eugene Leviant009d8332018-11-23 10:54:51 +00007530
7531static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7532 bool ReadOnly = Fwd->isReadOnly();
7533 *Fwd = Resolved;
7534 if (ReadOnly)
7535 Fwd->setReadOnly();
7536}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007537
7538/// Stores the given Name/GUID and associated summary into the Index.
7539/// Also updates any forward references to the associated entry ID.
7540void LLParser::AddGlobalValueToIndex(
7541 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7542 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7543 // First create the ValueInfo utilizing the Name or GUID.
7544 ValueInfo VI;
7545 if (GUID != 0) {
7546 assert(Name.empty());
7547 VI = Index->getOrInsertValueInfo(GUID);
7548 } else {
7549 assert(!Name.empty());
7550 if (M) {
7551 auto *GV = M->getNamedValue(Name);
7552 assert(GV);
7553 VI = Index->getOrInsertValueInfo(GV);
7554 } else {
7555 assert(
7556 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7557 "Need a source_filename to compute GUID for local");
7558 GUID = GlobalValue::getGUID(
7559 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7560 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7561 }
7562 }
7563
7564 // Add the summary if one was provided.
7565 if (Summary)
7566 Index->addGlobalValueSummary(VI, std::move(Summary));
7567
7568 // Resolve forward references from calls/refs
7569 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7570 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7571 for (auto VIRef : FwdRefVIs->second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00007572 assert(VIRef.first->getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007573 "Forward referenced ValueInfo expected to be empty");
Eugene Leviant009d8332018-11-23 10:54:51 +00007574 resolveFwdRef(VIRef.first, VI);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007575 }
7576 ForwardRefValueInfos.erase(FwdRefVIs);
7577 }
7578
7579 // Resolve forward references from aliases
7580 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7581 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7582 for (auto AliaseeRef : FwdRefAliasees->second) {
7583 assert(!AliaseeRef.first->hasAliasee() &&
7584 "Forward referencing alias already has aliasee");
7585 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7586 }
7587 ForwardRefAliasees.erase(FwdRefAliasees);
7588 }
7589
7590 // Save the associated ValueInfo for use in later references by ID.
7591 if (ID == NumberedValueInfos.size())
7592 NumberedValueInfos.push_back(VI);
7593 else {
7594 // Handle non-continuous numbers (to make test simplification easier).
7595 if (ID > NumberedValueInfos.size())
7596 NumberedValueInfos.resize(ID + 1);
7597 NumberedValueInfos[ID] = VI;
7598 }
7599}
7600
7601/// ParseGVEntry
7602/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7603/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7604/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7605bool LLParser::ParseGVEntry(unsigned ID) {
7606 assert(Lex.getKind() == lltok::kw_gv);
7607 Lex.Lex();
7608
7609 if (ParseToken(lltok::colon, "expected ':' here") ||
7610 ParseToken(lltok::lparen, "expected '(' here"))
7611 return true;
7612
7613 std::string Name;
7614 GlobalValue::GUID GUID = 0;
7615 switch (Lex.getKind()) {
7616 case lltok::kw_name:
7617 Lex.Lex();
7618 if (ParseToken(lltok::colon, "expected ':' here") ||
7619 ParseStringConstant(Name))
7620 return true;
7621 // Can't create GUID/ValueInfo until we have the linkage.
7622 break;
7623 case lltok::kw_guid:
7624 Lex.Lex();
7625 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7626 return true;
7627 break;
7628 default:
7629 return Error(Lex.getLoc(), "expected name or guid tag");
7630 }
7631
7632 if (!EatIfPresent(lltok::comma)) {
7633 // No summaries. Wrap up.
7634 if (ParseToken(lltok::rparen, "expected ')' here"))
7635 return true;
7636 // This was created for a call to an external or indirect target.
7637 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7638 // created for indirect calls with VP. A Name with no GUID came from
7639 // an external definition. We pass ExternalLinkage since that is only
7640 // used when the GUID must be computed from Name, and in that case
7641 // the symbol must have external linkage.
7642 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7643 nullptr);
7644 return false;
7645 }
7646
7647 // Have a list of summaries
7648 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7649 ParseToken(lltok::colon, "expected ':' here"))
7650 return true;
7651
7652 do {
7653 if (ParseToken(lltok::lparen, "expected '(' here"))
7654 return true;
7655 switch (Lex.getKind()) {
7656 case lltok::kw_function:
7657 if (ParseFunctionSummary(Name, GUID, ID))
7658 return true;
7659 break;
7660 case lltok::kw_variable:
7661 if (ParseVariableSummary(Name, GUID, ID))
7662 return true;
7663 break;
7664 case lltok::kw_alias:
7665 if (ParseAliasSummary(Name, GUID, ID))
7666 return true;
7667 break;
7668 default:
7669 return Error(Lex.getLoc(), "expected summary type");
7670 }
7671 if (ParseToken(lltok::rparen, "expected ')' here"))
7672 return true;
7673 } while (EatIfPresent(lltok::comma));
7674
7675 if (ParseToken(lltok::rparen, "expected ')' here"))
7676 return true;
7677
7678 return false;
7679}
7680
7681/// FunctionSummary
7682/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7683/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7684/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7685bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7686 unsigned ID) {
7687 assert(Lex.getKind() == lltok::kw_function);
7688 Lex.Lex();
7689
7690 StringRef ModulePath;
7691 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7692 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7693 /*Live=*/false, /*IsLocal=*/false);
7694 unsigned InstCount;
7695 std::vector<FunctionSummary::EdgeTy> Calls;
7696 FunctionSummary::TypeIdInfo TypeIdInfo;
7697 std::vector<ValueInfo> Refs;
7698 // Default is all-zeros (conservative values).
7699 FunctionSummary::FFlags FFlags = {};
7700 if (ParseToken(lltok::colon, "expected ':' here") ||
7701 ParseToken(lltok::lparen, "expected '(' here") ||
7702 ParseModuleReference(ModulePath) ||
7703 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7704 ParseToken(lltok::comma, "expected ',' here") ||
7705 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7706 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7707 return true;
7708
7709 // Parse optional fields
7710 while (EatIfPresent(lltok::comma)) {
7711 switch (Lex.getKind()) {
7712 case lltok::kw_funcFlags:
7713 if (ParseOptionalFFlags(FFlags))
7714 return true;
7715 break;
7716 case lltok::kw_calls:
7717 if (ParseOptionalCalls(Calls))
7718 return true;
7719 break;
7720 case lltok::kw_typeIdInfo:
7721 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7722 return true;
7723 break;
7724 case lltok::kw_refs:
7725 if (ParseOptionalRefs(Refs))
7726 return true;
7727 break;
7728 default:
7729 return Error(Lex.getLoc(), "expected optional function summary field");
7730 }
7731 }
7732
7733 if (ParseToken(lltok::rparen, "expected ')' here"))
7734 return true;
7735
7736 auto FS = llvm::make_unique<FunctionSummary>(
Easwaran Raman5a7056f2018-12-13 19:54:27 +00007737 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
7738 std::move(Calls), std::move(TypeIdInfo.TypeTests),
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007739 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7740 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7741 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7742 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7743
7744 FS->setModulePath(ModulePath);
7745
7746 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7747 ID, std::move(FS));
7748
7749 return false;
7750}
7751
7752/// VariableSummary
7753/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7754/// [',' OptionalRefs]? ')'
7755bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7756 unsigned ID) {
7757 assert(Lex.getKind() == lltok::kw_variable);
7758 Lex.Lex();
7759
7760 StringRef ModulePath;
7761 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7762 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7763 /*Live=*/false, /*IsLocal=*/false);
Eugene Leviant009d8332018-11-23 10:54:51 +00007764 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007765 std::vector<ValueInfo> Refs;
7766 if (ParseToken(lltok::colon, "expected ':' here") ||
7767 ParseToken(lltok::lparen, "expected '(' here") ||
7768 ParseModuleReference(ModulePath) ||
Eugene Leviant009d8332018-11-23 10:54:51 +00007769 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7770 ParseToken(lltok::comma, "expected ',' here") ||
7771 ParseGVarFlags(GVarFlags))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007772 return true;
7773
Teresa Johnson8d86f1b2019-01-17 16:05:04 +00007774 // Parse optional refs field
7775 if (EatIfPresent(lltok::comma)) {
7776 if (ParseOptionalRefs(Refs))
7777 return true;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007778 }
7779
7780 if (ParseToken(lltok::rparen, "expected ')' here"))
7781 return true;
7782
Eugene Leviant009d8332018-11-23 10:54:51 +00007783 auto GS =
7784 llvm::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007785
7786 GS->setModulePath(ModulePath);
7787
7788 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7789 ID, std::move(GS));
7790
7791 return false;
7792}
7793
7794/// AliasSummary
7795/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7796/// 'aliasee' ':' GVReference ')'
7797bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7798 unsigned ID) {
7799 assert(Lex.getKind() == lltok::kw_alias);
7800 LocTy Loc = Lex.getLoc();
7801 Lex.Lex();
7802
7803 StringRef ModulePath;
7804 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7805 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7806 /*Live=*/false, /*IsLocal=*/false);
7807 if (ParseToken(lltok::colon, "expected ':' here") ||
7808 ParseToken(lltok::lparen, "expected '(' here") ||
7809 ParseModuleReference(ModulePath) ||
7810 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7811 ParseToken(lltok::comma, "expected ',' here") ||
7812 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7813 ParseToken(lltok::colon, "expected ':' here"))
7814 return true;
7815
7816 ValueInfo AliaseeVI;
7817 unsigned GVId;
7818 if (ParseGVReference(AliaseeVI, GVId))
7819 return true;
7820
7821 if (ParseToken(lltok::rparen, "expected ')' here"))
7822 return true;
7823
7824 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7825
7826 AS->setModulePath(ModulePath);
7827
7828 // Record forward reference if the aliasee is not parsed yet.
Eugene Leviant009d8332018-11-23 10:54:51 +00007829 if (AliaseeVI.getRef() == FwdVIRef) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007830 auto FwdRef = ForwardRefAliasees.insert(
7831 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7832 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7833 } else
7834 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7835
7836 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7837 ID, std::move(AS));
7838
7839 return false;
7840}
7841
7842/// Flag
7843/// ::= [0|1]
7844bool LLParser::ParseFlag(unsigned &Val) {
7845 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7846 return TokError("expected integer");
7847 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7848 Lex.Lex();
7849 return false;
7850}
7851
7852/// OptionalFFlags
7853/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7854/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7855/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
Teresa Johnsoncb397462018-11-06 19:41:35 +00007856/// [',' 'noInline' ':' Flag]? ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007857bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7858 assert(Lex.getKind() == lltok::kw_funcFlags);
7859 Lex.Lex();
7860
7861 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7862 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7863 return true;
7864
7865 do {
7866 unsigned Val;
7867 switch (Lex.getKind()) {
7868 case lltok::kw_readNone:
7869 Lex.Lex();
7870 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7871 return true;
7872 FFlags.ReadNone = Val;
7873 break;
7874 case lltok::kw_readOnly:
7875 Lex.Lex();
7876 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7877 return true;
7878 FFlags.ReadOnly = Val;
7879 break;
7880 case lltok::kw_noRecurse:
7881 Lex.Lex();
7882 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7883 return true;
7884 FFlags.NoRecurse = Val;
7885 break;
7886 case lltok::kw_returnDoesNotAlias:
7887 Lex.Lex();
7888 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7889 return true;
7890 FFlags.ReturnDoesNotAlias = Val;
7891 break;
Teresa Johnsoncb397462018-11-06 19:41:35 +00007892 case lltok::kw_noInline:
7893 Lex.Lex();
7894 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7895 return true;
7896 FFlags.NoInline = Val;
7897 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007898 default:
7899 return Error(Lex.getLoc(), "expected function flag type");
7900 }
7901 } while (EatIfPresent(lltok::comma));
7902
7903 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
7904 return true;
7905
7906 return false;
7907}
7908
7909/// OptionalCalls
7910/// := 'calls' ':' '(' Call [',' Call]* ')'
7911/// Call ::= '(' 'callee' ':' GVReference
7912/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7913bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7914 assert(Lex.getKind() == lltok::kw_calls);
7915 Lex.Lex();
7916
7917 if (ParseToken(lltok::colon, "expected ':' in calls") |
7918 ParseToken(lltok::lparen, "expected '(' in calls"))
7919 return true;
7920
7921 IdToIndexMapType IdToIndexMap;
7922 // Parse each call edge
7923 do {
7924 ValueInfo VI;
7925 if (ParseToken(lltok::lparen, "expected '(' in call") ||
7926 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
7927 ParseToken(lltok::colon, "expected ':'"))
7928 return true;
7929
7930 LocTy Loc = Lex.getLoc();
7931 unsigned GVId;
7932 if (ParseGVReference(VI, GVId))
7933 return true;
7934
7935 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7936 unsigned RelBF = 0;
7937 if (EatIfPresent(lltok::comma)) {
7938 // Expect either hotness or relbf
7939 if (EatIfPresent(lltok::kw_hotness)) {
7940 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
7941 return true;
7942 } else {
7943 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
7944 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
7945 return true;
7946 }
7947 }
7948 // Keep track of the Call array index needing a forward reference.
7949 // We will save the location of the ValueInfo needing an update, but
7950 // can only do so once the std::vector is finalized.
Eugene Leviant009d8332018-11-23 10:54:51 +00007951 if (VI.getRef() == FwdVIRef)
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007952 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7953 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
7954
7955 if (ParseToken(lltok::rparen, "expected ')' in call"))
7956 return true;
7957 } while (EatIfPresent(lltok::comma));
7958
7959 // Now that the Calls vector is finalized, it is safe to save the locations
7960 // of any forward GV references that need updating later.
7961 for (auto I : IdToIndexMap) {
7962 for (auto P : I.second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00007963 assert(Calls[P.first].first.getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007964 "Forward referenced ValueInfo expected to be empty");
7965 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7966 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7967 FwdRef.first->second.push_back(
7968 std::make_pair(&Calls[P.first].first, P.second));
7969 }
7970 }
7971
7972 if (ParseToken(lltok::rparen, "expected ')' in calls"))
7973 return true;
7974
7975 return false;
7976}
7977
7978/// Hotness
7979/// := ('unknown'|'cold'|'none'|'hot'|'critical')
7980bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
7981 switch (Lex.getKind()) {
7982 case lltok::kw_unknown:
7983 Hotness = CalleeInfo::HotnessType::Unknown;
7984 break;
7985 case lltok::kw_cold:
7986 Hotness = CalleeInfo::HotnessType::Cold;
7987 break;
7988 case lltok::kw_none:
7989 Hotness = CalleeInfo::HotnessType::None;
7990 break;
7991 case lltok::kw_hot:
7992 Hotness = CalleeInfo::HotnessType::Hot;
7993 break;
7994 case lltok::kw_critical:
7995 Hotness = CalleeInfo::HotnessType::Critical;
7996 break;
7997 default:
7998 return Error(Lex.getLoc(), "invalid call edge hotness");
7999 }
8000 Lex.Lex();
8001 return false;
8002}
8003
8004/// OptionalRefs
8005/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8006bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8007 assert(Lex.getKind() == lltok::kw_refs);
8008 Lex.Lex();
8009
8010 if (ParseToken(lltok::colon, "expected ':' in refs") |
8011 ParseToken(lltok::lparen, "expected '(' in refs"))
8012 return true;
8013
Eugene Leviant009d8332018-11-23 10:54:51 +00008014 struct ValueContext {
8015 ValueInfo VI;
8016 unsigned GVId;
8017 LocTy Loc;
8018 };
8019 std::vector<ValueContext> VContexts;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008020 // Parse each ref edge
8021 do {
Eugene Leviant009d8332018-11-23 10:54:51 +00008022 ValueContext VC;
8023 VC.Loc = Lex.getLoc();
8024 if (ParseGVReference(VC.VI, VC.GVId))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008025 return true;
Eugene Leviant009d8332018-11-23 10:54:51 +00008026 VContexts.push_back(VC);
8027 } while (EatIfPresent(lltok::comma));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008028
Eugene Leviant009d8332018-11-23 10:54:51 +00008029 // Sort value contexts so that ones with readonly ValueInfo are at the end
8030 // of VContexts vector. This is needed to match immutableRefCount() behavior.
Eugene Leviant972e3482018-11-23 11:28:58 +00008031 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008032 return VC1.VI.isReadOnly() < VC2.VI.isReadOnly();
8033 });
8034
8035 IdToIndexMapType IdToIndexMap;
8036 for (auto &VC : VContexts) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008037 // Keep track of the Refs array index needing a forward reference.
8038 // We will save the location of the ValueInfo needing an update, but
8039 // can only do so once the std::vector is finalized.
Eugene Leviant009d8332018-11-23 10:54:51 +00008040 if (VC.VI.getRef() == FwdVIRef)
8041 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8042 Refs.push_back(VC.VI);
8043 }
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008044
8045 // Now that the Refs vector is finalized, it is safe to save the locations
8046 // of any forward GV references that need updating later.
8047 for (auto I : IdToIndexMap) {
8048 for (auto P : I.second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008049 assert(Refs[P.first].getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008050 "Forward referenced ValueInfo expected to be empty");
8051 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8052 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8053 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8054 }
8055 }
8056
8057 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8058 return true;
8059
8060 return false;
8061}
8062
8063/// OptionalTypeIdInfo
8064/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8065/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8066/// [',' TypeCheckedLoadConstVCalls]? ')'
8067bool LLParser::ParseOptionalTypeIdInfo(
8068 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8069 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8070 Lex.Lex();
8071
8072 if (ParseToken(lltok::colon, "expected ':' here") ||
8073 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8074 return true;
8075
8076 do {
8077 switch (Lex.getKind()) {
8078 case lltok::kw_typeTests:
8079 if (ParseTypeTests(TypeIdInfo.TypeTests))
8080 return true;
8081 break;
8082 case lltok::kw_typeTestAssumeVCalls:
8083 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8084 TypeIdInfo.TypeTestAssumeVCalls))
8085 return true;
8086 break;
8087 case lltok::kw_typeCheckedLoadVCalls:
8088 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8089 TypeIdInfo.TypeCheckedLoadVCalls))
8090 return true;
8091 break;
8092 case lltok::kw_typeTestAssumeConstVCalls:
8093 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8094 TypeIdInfo.TypeTestAssumeConstVCalls))
8095 return true;
8096 break;
8097 case lltok::kw_typeCheckedLoadConstVCalls:
8098 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8099 TypeIdInfo.TypeCheckedLoadConstVCalls))
8100 return true;
8101 break;
8102 default:
8103 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8104 }
8105 } while (EatIfPresent(lltok::comma));
8106
8107 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8108 return true;
8109
8110 return false;
8111}
8112
8113/// TypeTests
8114/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8115/// [',' (SummaryID | UInt64)]* ')'
8116bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8117 assert(Lex.getKind() == lltok::kw_typeTests);
8118 Lex.Lex();
8119
8120 if (ParseToken(lltok::colon, "expected ':' here") ||
8121 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8122 return true;
8123
8124 IdToIndexMapType IdToIndexMap;
8125 do {
8126 GlobalValue::GUID GUID = 0;
8127 if (Lex.getKind() == lltok::SummaryID) {
8128 unsigned ID = Lex.getUIntVal();
8129 LocTy Loc = Lex.getLoc();
8130 // Keep track of the TypeTests array index needing a forward reference.
8131 // We will save the location of the GUID needing an update, but
8132 // can only do so once the std::vector is finalized.
8133 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8134 Lex.Lex();
8135 } else if (ParseUInt64(GUID))
8136 return true;
8137 TypeTests.push_back(GUID);
8138 } while (EatIfPresent(lltok::comma));
8139
8140 // Now that the TypeTests vector is finalized, it is safe to save the
8141 // locations of any forward GV references that need updating later.
8142 for (auto I : IdToIndexMap) {
8143 for (auto P : I.second) {
8144 assert(TypeTests[P.first] == 0 &&
8145 "Forward referenced type id GUID expected to be 0");
8146 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8147 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8148 FwdRef.first->second.push_back(
8149 std::make_pair(&TypeTests[P.first], P.second));
8150 }
8151 }
8152
8153 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8154 return true;
8155
8156 return false;
8157}
8158
8159/// VFuncIdList
8160/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8161bool LLParser::ParseVFuncIdList(
8162 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8163 assert(Lex.getKind() == Kind);
8164 Lex.Lex();
8165
8166 if (ParseToken(lltok::colon, "expected ':' here") ||
8167 ParseToken(lltok::lparen, "expected '(' here"))
8168 return true;
8169
8170 IdToIndexMapType IdToIndexMap;
8171 do {
8172 FunctionSummary::VFuncId VFuncId;
8173 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8174 return true;
8175 VFuncIdList.push_back(VFuncId);
8176 } while (EatIfPresent(lltok::comma));
8177
8178 if (ParseToken(lltok::rparen, "expected ')' here"))
8179 return true;
8180
8181 // Now that the VFuncIdList vector is finalized, it is safe to save the
8182 // locations of any forward GV references that need updating later.
8183 for (auto I : IdToIndexMap) {
8184 for (auto P : I.second) {
8185 assert(VFuncIdList[P.first].GUID == 0 &&
8186 "Forward referenced type id GUID expected to be 0");
8187 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8188 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8189 FwdRef.first->second.push_back(
8190 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8191 }
8192 }
8193
8194 return false;
8195}
8196
8197/// ConstVCallList
8198/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8199bool LLParser::ParseConstVCallList(
8200 lltok::Kind Kind,
8201 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8202 assert(Lex.getKind() == Kind);
8203 Lex.Lex();
8204
8205 if (ParseToken(lltok::colon, "expected ':' here") ||
8206 ParseToken(lltok::lparen, "expected '(' here"))
8207 return true;
8208
8209 IdToIndexMapType IdToIndexMap;
8210 do {
8211 FunctionSummary::ConstVCall ConstVCall;
8212 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8213 return true;
8214 ConstVCallList.push_back(ConstVCall);
8215 } while (EatIfPresent(lltok::comma));
8216
8217 if (ParseToken(lltok::rparen, "expected ')' here"))
8218 return true;
8219
8220 // Now that the ConstVCallList vector is finalized, it is safe to save the
8221 // locations of any forward GV references that need updating later.
8222 for (auto I : IdToIndexMap) {
8223 for (auto P : I.second) {
8224 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8225 "Forward referenced type id GUID expected to be 0");
8226 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8227 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8228 FwdRef.first->second.push_back(
8229 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8230 }
8231 }
8232
8233 return false;
8234}
8235
8236/// ConstVCall
Teresa Johnsonc7816802018-08-14 01:49:33 +00008237/// ::= '(' VFuncId ',' Args ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008238bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8239 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsonc7816802018-08-14 01:49:33 +00008240 if (ParseToken(lltok::lparen, "expected '(' here") ||
8241 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8242 return true;
8243
8244 if (EatIfPresent(lltok::comma))
8245 if (ParseArgs(ConstVCall.Args))
8246 return true;
8247
8248 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008249 return true;
8250
8251 return false;
8252}
8253
8254/// VFuncId
8255/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8256/// 'offset' ':' UInt64 ')'
8257bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8258 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8259 assert(Lex.getKind() == lltok::kw_vFuncId);
8260 Lex.Lex();
8261
8262 if (ParseToken(lltok::colon, "expected ':' here") ||
8263 ParseToken(lltok::lparen, "expected '(' here"))
8264 return true;
8265
8266 if (Lex.getKind() == lltok::SummaryID) {
8267 VFuncId.GUID = 0;
8268 unsigned ID = Lex.getUIntVal();
8269 LocTy Loc = Lex.getLoc();
8270 // Keep track of the array index needing a forward reference.
8271 // We will save the location of the GUID needing an update, but
8272 // can only do so once the caller's std::vector is finalized.
8273 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8274 Lex.Lex();
8275 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8276 ParseToken(lltok::colon, "expected ':' here") ||
8277 ParseUInt64(VFuncId.GUID))
8278 return true;
8279
8280 if (ParseToken(lltok::comma, "expected ',' here") ||
8281 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8282 ParseToken(lltok::colon, "expected ':' here") ||
8283 ParseUInt64(VFuncId.Offset) ||
8284 ParseToken(lltok::rparen, "expected ')' here"))
8285 return true;
8286
8287 return false;
8288}
8289
8290/// GVFlags
8291/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8292/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8293/// 'dsoLocal' ':' Flag ')'
8294bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8295 assert(Lex.getKind() == lltok::kw_flags);
8296 Lex.Lex();
8297
8298 bool HasLinkage;
8299 if (ParseToken(lltok::colon, "expected ':' here") ||
8300 ParseToken(lltok::lparen, "expected '(' here") ||
8301 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8302 ParseToken(lltok::colon, "expected ':' here"))
8303 return true;
8304
8305 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8306 assert(HasLinkage && "Linkage not optional in summary entry");
8307 Lex.Lex();
8308
8309 unsigned Flag;
8310 if (ParseToken(lltok::comma, "expected ',' here") ||
8311 ParseToken(lltok::kw_notEligibleToImport,
8312 "expected 'notEligibleToImport' here") ||
8313 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8314 return true;
8315 GVFlags.NotEligibleToImport = Flag;
8316
8317 if (ParseToken(lltok::comma, "expected ',' here") ||
8318 ParseToken(lltok::kw_live, "expected 'live' here") ||
8319 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8320 return true;
8321 GVFlags.Live = Flag;
8322
8323 if (ParseToken(lltok::comma, "expected ',' here") ||
8324 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8325 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8326 return true;
8327 GVFlags.DSOLocal = Flag;
8328
8329 if (ParseToken(lltok::rparen, "expected ')' here"))
8330 return true;
8331
8332 return false;
8333}
8334
Eugene Leviant009d8332018-11-23 10:54:51 +00008335/// GVarFlags
8336/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8337bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8338 assert(Lex.getKind() == lltok::kw_varFlags);
8339 Lex.Lex();
8340
8341 unsigned Flag;
8342 if (ParseToken(lltok::colon, "expected ':' here") ||
8343 ParseToken(lltok::lparen, "expected '(' here") ||
8344 ParseToken(lltok::kw_readonly, "expected 'readonly' here") ||
8345 ParseToken(lltok::colon, "expected ':' here"))
8346 return true;
8347
8348 ParseFlag(Flag);
8349 GVarFlags.ReadOnly = Flag;
8350
8351 if (ParseToken(lltok::rparen, "expected ')' here"))
8352 return true;
8353 return false;
8354}
8355
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008356/// ModuleReference
8357/// ::= 'module' ':' UInt
8358bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8359 // Parse module id.
8360 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8361 ParseToken(lltok::colon, "expected ':' here") ||
8362 ParseToken(lltok::SummaryID, "expected module ID"))
8363 return true;
8364
8365 unsigned ModuleID = Lex.getUIntVal();
8366 auto I = ModuleIdMap.find(ModuleID);
8367 // We should have already parsed all module IDs
8368 assert(I != ModuleIdMap.end());
8369 ModulePath = I->second;
8370 return false;
8371}
8372
8373/// GVReference
8374/// ::= SummaryID
8375bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008376 bool ReadOnly = EatIfPresent(lltok::kw_readonly);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008377 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8378 return true;
8379
8380 GVId = Lex.getUIntVal();
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008381 // Check if we already have a VI for this GV
8382 if (GVId < NumberedValueInfos.size()) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008383 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008384 VI = NumberedValueInfos[GVId];
8385 } else
8386 // We will create a forward reference to the stored location.
Eugene Leviant009d8332018-11-23 10:54:51 +00008387 VI = ValueInfo(false, FwdVIRef);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008388
Eugene Leviant009d8332018-11-23 10:54:51 +00008389 if (ReadOnly)
8390 VI.setReadOnly();
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008391 return false;
8392}