blob: c156a60ffa790f76ba5367569804c4eb3ba1adb0 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Teresa Johnson63ee0e72018-06-26 13:56:49 +000074 return ParseTopLevelEntities() || ValidateEndOfModule() ||
75 ValidateEndOfIndex();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000123 if (!M)
124 return false;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000125 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000126 for (const auto &RAG : ForwardRefAttrGroups) {
127 Value *V = RAG.first;
128 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000129 AttrBuilder B;
130
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000131 for (const auto &Attr : Attrs)
132 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000133
134 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000135 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000136 AttrBuilder FnAttrs(AS.getFnAttributes());
137 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000138
139 FnAttrs.merge(B);
140
141 // If the alignment was parsed as an attribute, move to the alignment
142 // field.
143 if (FnAttrs.hasAlignmentAttr()) {
144 Fn->setAlignment(FnAttrs.getAlignment());
145 FnAttrs.removeAttribute(Attribute::Alignment);
146 }
147
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000148 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
149 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000152 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000153 AttrBuilder FnAttrs(AS.getFnAttributes());
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000155 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000156 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
157 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000158 CI->setAttributes(AS);
159 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000160 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000161 AttrBuilder FnAttrs(AS.getFnAttributes());
162 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000163 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000164 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
165 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000166 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000167 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
168 AttrBuilder Attrs(GV->getAttributes());
169 Attrs.merge(B);
170 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000171 } else {
172 llvm_unreachable("invalid object with forward attribute group reference");
173 }
174 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000175
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000176 // If there are entries in ForwardRefBlockAddresses at this point, the
177 // function was never defined.
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000181
David Majnemer19b51052015-02-11 07:43:56 +0000182 for (const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186
187 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
188 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
189 if (I->second.second.isValid())
190 return Error(I->second.second,
191 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000192
David Majnemerdad0a642014-06-27 18:19:56 +0000193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first + "'");
197
Chris Lattnerac161bf2009-01-02 07:01:27 +0000198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000202
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000206 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000207
Devang Pateld2541152009-07-08 19:23:54 +0000208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000211 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
217 }
Devang Pateld2541152009-07-08 19:23:54 +0000218
Mehdi Aminie4709272016-09-14 22:29:59 +0000219 for (auto *Inst : InstsWithTBAATag) {
220 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
221 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
222 auto *UpgradedMD = UpgradeTBAANode(*MD);
223 if (MD != UpgradedMD)
224 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000226
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 // Look for intrinsic functions and CallInst that need to be upgraded
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000230
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000231 // Some types could be renamed during loading if several modules are
232 // loaded in the same LLVMContext (LTO scenario). In this case we should
233 // remangle intrinsics names as well.
234 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
235 Function *F = &*FI++;
236 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
237 F->replaceAllUsesWith(Remangled.getValue());
238 F->eraseFromParent();
239 }
240 }
241
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000242 if (UpgradeDebugInfo)
243 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000244
Manman Renb5d7ff42016-05-25 23:14:48 +0000245 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000246 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000247
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000248 if (!Slots)
249 return false;
250 // Initialize the slot mapping.
251 // Because by this point we've parsed and validated everything, we can "steal"
252 // the mapping from LLParser as it doesn't need it anymore.
253 Slots->GlobalValues = std::move(NumberedVals);
254 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000255 for (const auto &I : NamedTypes)
256 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
257 for (const auto &I : NumberedTypes)
258 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000259
Chris Lattnerac161bf2009-01-02 07:01:27 +0000260 return false;
261}
262
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000263/// Do final validity and sanity checks at the end of the index.
264bool LLParser::ValidateEndOfIndex() {
265 if (!Index)
266 return false;
267
268 if (!ForwardRefValueInfos.empty())
269 return Error(ForwardRefValueInfos.begin()->second.front().second,
270 "use of undefined summary '^" +
271 Twine(ForwardRefValueInfos.begin()->first) + "'");
272
273 if (!ForwardRefAliasees.empty())
274 return Error(ForwardRefAliasees.begin()->second.front().second,
275 "use of undefined summary '^" +
276 Twine(ForwardRefAliasees.begin()->first) + "'");
277
278 if (!ForwardRefTypeIds.empty())
279 return Error(ForwardRefTypeIds.begin()->second.front().second,
280 "use of undefined type id summary '^" +
281 Twine(ForwardRefTypeIds.begin()->first) + "'");
282
283 return false;
284}
285
Chris Lattnerac161bf2009-01-02 07:01:27 +0000286//===----------------------------------------------------------------------===//
287// Top-Level Entities
288//===----------------------------------------------------------------------===//
289
290bool LLParser::ParseTopLevelEntities() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000291 // If there is no Module, then parse just the summary index entries.
292 if (!M) {
293 while (true) {
294 switch (Lex.getKind()) {
295 case lltok::Eof:
296 return false;
297 case lltok::SummaryID:
298 if (ParseSummaryEntry())
299 return true;
300 break;
301 case lltok::kw_source_filename:
302 if (ParseSourceFileName())
303 return true;
304 break;
305 default:
306 // Skip everything else
307 Lex.Lex();
308 }
309 }
310 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000311 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 switch (Lex.getKind()) {
313 default: return TokError("expected top-level entity");
314 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000315 case lltok::kw_declare: if (ParseDeclare()) return true; break;
316 case lltok::kw_define: if (ParseDefine()) return true; break;
317 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
318 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000319 case lltok::kw_source_filename:
320 if (ParseSourceFileName())
321 return true;
322 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000323 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000324 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000326 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000328 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000329 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000330 case lltok::SummaryID:
331 if (ParseSummaryEntry())
332 return true;
333 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000334 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000335 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000336 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
337 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000338 if (ParseUseListOrderBB())
339 return true;
340 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341 }
342 }
343}
344
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345/// toplevelentity
346/// ::= 'module' 'asm' STRINGCONSTANT
347bool LLParser::ParseModuleAsm() {
348 assert(Lex.getKind() == lltok::kw_module);
349 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000350
351 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000352 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
353 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000354
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000355 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000356 return false;
357}
358
359/// toplevelentity
360/// ::= 'target' 'triple' '=' STRINGCONSTANT
361/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
362bool LLParser::ParseTargetDefinition() {
363 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000364 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000365 switch (Lex.Lex()) {
366 default: return TokError("unknown target property");
367 case lltok::kw_triple:
368 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000369 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
370 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000372 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000373 return false;
374 case lltok::kw_datalayout:
375 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000376 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
377 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000379 if (DataLayoutStr.empty())
380 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381 return false;
382 }
383}
384
Bill Wendling706d3d62012-11-28 08:41:48 +0000385/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000386/// ::= 'source_filename' '=' STRINGCONSTANT
387bool LLParser::ParseSourceFileName() {
388 assert(Lex.getKind() == lltok::kw_source_filename);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000389 Lex.Lex();
390 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000391 ParseStringConstant(SourceFileName))
Teresa Johnson83c517c2016-03-30 18:15:08 +0000392 return true;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000393 if (M)
394 M->setSourceFileName(SourceFileName);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000395 return false;
396}
397
398/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000399/// ::= 'deplibs' '=' '[' ']'
400/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
401/// FIXME: Remove in 4.0. Currently parse, but ignore.
402bool LLParser::ParseDepLibs() {
403 assert(Lex.getKind() == lltok::kw_deplibs);
404 Lex.Lex();
405 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
406 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
407 return true;
408
409 if (EatIfPresent(lltok::rsquare))
410 return false;
411
412 do {
413 std::string Str;
414 if (ParseStringConstant(Str)) return true;
415 } while (EatIfPresent(lltok::comma));
416
417 return ParseToken(lltok::rsquare, "expected ']' at end of list");
418}
419
Dan Gohman466876b2009-08-12 23:32:33 +0000420/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000421/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000423 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000425 Lex.Lex(); // eat LocalVarID;
426
427 if (ParseToken(lltok::equal, "expected '=' after name") ||
428 ParseToken(lltok::kw_type, "expected 'type' after '='"))
429 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000430
Craig Topper2617dcc2014-04-15 06:32:26 +0000431 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000432 if (ParseStructDefinition(TypeLoc, "",
433 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000434
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000435 if (!isa<StructType>(Result)) {
436 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
437 if (Entry.first)
438 return Error(TypeLoc, "non-struct types may not be recursive");
439 Entry.first = Result;
440 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000442
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 return false;
444}
445
446/// toplevelentity
447/// ::= LocalVar '=' 'type' type
448bool LLParser::ParseNamedType() {
449 std::string Name = Lex.getStrVal();
450 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000451 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000452
Chris Lattner3822f632009-01-02 08:05:26 +0000453 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000454 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000455 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000456
Craig Topper2617dcc2014-04-15 06:32:26 +0000457 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000458 if (ParseStructDefinition(NameLoc, Name,
459 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 if (!isa<StructType>(Result)) {
462 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
463 if (Entry.first)
464 return Error(NameLoc, "non-struct types may not be recursive");
465 Entry.first = Result;
466 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000469 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470}
471
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472/// toplevelentity
473/// ::= 'declare' FunctionHeader
474bool LLParser::ParseDeclare() {
475 assert(Lex.getKind() == lltok::kw_declare);
476 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000477
Peter Collingbourne21521892016-06-21 23:42:48 +0000478 std::vector<std::pair<unsigned, MDNode *>> MDs;
479 while (Lex.getKind() == lltok::MetadataVar) {
480 unsigned MDK;
481 MDNode *N;
482 if (ParseMetadataAttachment(MDK, N))
483 return true;
484 MDs.push_back({MDK, N});
485 }
486
Chris Lattnerac161bf2009-01-02 07:01:27 +0000487 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000488 if (ParseFunctionHeader(F, false))
489 return true;
490 for (auto &MD : MDs)
491 F->addMetadata(MD.first, *MD.second);
492 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493}
494
495/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000496/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000497bool LLParser::ParseDefine() {
498 assert(Lex.getKind() == lltok::kw_define);
499 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattnerac161bf2009-01-02 07:01:27 +0000501 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000502 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000503 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000504 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000505}
506
Chris Lattner3822f632009-01-02 08:05:26 +0000507/// ParseGlobalType
508/// ::= 'constant'
509/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000510bool LLParser::ParseGlobalType(bool &IsConstant) {
511 if (Lex.getKind() == lltok::kw_constant)
512 IsConstant = true;
513 else if (Lex.getKind() == lltok::kw_global)
514 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000515 else {
516 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000517 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000518 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000519 Lex.Lex();
520 return false;
521}
522
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000523bool LLParser::ParseOptionalUnnamedAddr(
524 GlobalVariable::UnnamedAddr &UnnamedAddr) {
525 if (EatIfPresent(lltok::kw_unnamed_addr))
526 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
527 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
528 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
529 else
530 UnnamedAddr = GlobalValue::UnnamedAddr::None;
531 return false;
532}
533
Dan Gohman466876b2009-08-12 23:32:33 +0000534/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000535/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000536/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
537/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000538/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000539/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000540/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
541/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000542/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000543bool LLParser::ParseUnnamedGlobal() {
544 unsigned VarID = NumberedVals.size();
545 std::string Name;
546 LocTy NameLoc = Lex.getLoc();
547
548 // Handle the GlobalID form.
549 if (Lex.getKind() == lltok::GlobalID) {
550 if (Lex.getUIntVal() != VarID)
551 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000552 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000553 Lex.Lex(); // eat GlobalID;
554
555 if (ParseToken(lltok::equal, "expected '=' after name"))
556 return true;
557 }
558
559 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000560 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000561 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000562 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000563 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000564 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
565 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000566 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000567 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000568
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000569 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000570 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000571 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000572
573 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000574 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000575}
576
Chris Lattnerac161bf2009-01-02 07:01:27 +0000577/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000578/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000579/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
580/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000581/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000582bool LLParser::ParseNamedGlobal() {
583 assert(Lex.getKind() == lltok::GlobalVar);
584 LocTy NameLoc = Lex.getLoc();
585 std::string Name = Lex.getStrVal();
586 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000587
Chris Lattnerac161bf2009-01-02 07:01:27 +0000588 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000589 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000590 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000591 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000592 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000593 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000594 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
595 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000596 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000597 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000598
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000599 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000600 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000601 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000602
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000603 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000604 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000605}
606
David Majnemerdad0a642014-06-27 18:19:56 +0000607bool LLParser::parseComdat() {
608 assert(Lex.getKind() == lltok::ComdatVar);
609 std::string Name = Lex.getStrVal();
610 LocTy NameLoc = Lex.getLoc();
611 Lex.Lex();
612
613 if (ParseToken(lltok::equal, "expected '=' here"))
614 return true;
615
616 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
617 return TokError("expected comdat type");
618
619 Comdat::SelectionKind SK;
620 switch (Lex.getKind()) {
621 default:
622 return TokError("unknown selection kind");
623 case lltok::kw_any:
624 SK = Comdat::Any;
625 break;
626 case lltok::kw_exactmatch:
627 SK = Comdat::ExactMatch;
628 break;
629 case lltok::kw_largest:
630 SK = Comdat::Largest;
631 break;
632 case lltok::kw_noduplicates:
633 SK = Comdat::NoDuplicates;
634 break;
635 case lltok::kw_samesize:
636 SK = Comdat::SameSize;
637 break;
638 }
639 Lex.Lex();
640
641 // See if the comdat was forward referenced, if so, use the comdat.
642 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
643 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
644 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
645 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
646
647 Comdat *C;
648 if (I != ComdatSymTab.end())
649 C = &I->second;
650 else
651 C = M->getOrInsertComdat(Name);
652 C->setSelectionKind(SK);
653
654 return false;
655}
656
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000657// MDString:
658// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000659bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000660 std::string Str;
661 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000662 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000663 return false;
664}
665
666// MDNode:
667// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000668bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000669 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000670 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000671 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000672 if (ParseUInt32(MID))
673 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000674
Chris Lattner8eff0152010-04-01 05:14:45 +0000675 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000676 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000677 Result = NumberedMetadata[MID];
678 return false;
679 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000680
Chris Lattner8eff0152010-04-01 05:14:45 +0000681 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000682 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000683 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000684
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000685 Result = FwdRef.first.get();
686 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000687 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000688}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000689
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000690/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000691/// !foo = !{ !1, !2 }
692bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000693 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000694 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000695 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000696
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000697 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000698 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000699 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000700 return true;
701
Dan Gohman2637cc12010-07-21 23:38:33 +0000702 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000703 if (Lex.getKind() != lltok::rbrace)
704 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000705 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000706 // Parse DIExpressions inline as a special case. They are still MDNodes,
707 // so they can still appear in named metadata. Remove this logic if they
708 // become plain Metadata.
709 if (Lex.getKind() == lltok::MetadataVar &&
710 Lex.getStrVal() == "DIExpression") {
711 if (ParseDIExpression(N, /*IsDistinct=*/false))
712 return true;
713 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
714 ParseMDNodeID(N)) {
715 return true;
716 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000717 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000718 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000719
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000720 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000721}
722
Devang Patel39e64d42009-07-01 19:21:12 +0000723/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000724/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000725bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000726 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000727 Lex.Lex();
728 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000729
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000730 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000731 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000732 ParseToken(lltok::equal, "expected '=' here"))
733 return true;
734
735 // Detect common error, from old metadata syntax.
736 if (Lex.getKind() == lltok::Type)
737 return TokError("unexpected type in metadata definition");
738
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000739 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000740 if (Lex.getKind() == lltok::MetadataVar) {
741 if (ParseSpecializedMDNode(Init, IsDistinct))
742 return true;
743 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
744 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000745 return true;
746
Chris Lattnerfc58af22009-12-30 04:51:58 +0000747 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000748 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000749 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000750 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000751 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000752
Chris Lattnerfc58af22009-12-30 04:51:58 +0000753 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
754 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000755 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000756 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000757 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000758 }
759
Devang Patel39e64d42009-07-01 19:21:12 +0000760 return false;
761}
762
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000763// Skips a single module summary entry.
764bool LLParser::SkipModuleSummaryEntry() {
765 // Each module summary entry consists of a tag for the entry
766 // type, followed by a colon, then the fields surrounded by nested sets of
767 // parentheses. The "tag:" looks like a Label. Once parsing support is
768 // in place we will look for the tokens corresponding to the expected tags.
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000769 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
770 Lex.getKind() != lltok::kw_typeid)
771 return TokError(
772 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
773 Lex.Lex();
774 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000775 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
776 return true;
777 // Now walk through the parenthesized entry, until the number of open
778 // parentheses goes back down to 0 (the first '(' was parsed above).
779 unsigned NumOpenParen = 1;
780 do {
781 switch (Lex.getKind()) {
782 case lltok::lparen:
783 NumOpenParen++;
784 break;
785 case lltok::rparen:
786 NumOpenParen--;
787 break;
788 case lltok::Eof:
789 return TokError("found end of file while parsing summary entry");
790 default:
791 // Skip everything in between parentheses.
792 break;
793 }
794 Lex.Lex();
795 } while (NumOpenParen > 0);
796 return false;
797}
798
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000799/// SummaryEntry
800/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000801bool LLParser::ParseSummaryEntry() {
802 assert(Lex.getKind() == lltok::SummaryID);
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000803 unsigned SummaryID = Lex.getUIntVal();
804
805 // For summary entries, colons should be treated as distinct tokens,
806 // not an indication of the end of a label token.
807 Lex.setIgnoreColonInIdentifiers(true);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000808
809 Lex.Lex();
810 if (ParseToken(lltok::equal, "expected '=' here"))
811 return true;
812
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000813 // If we don't have an index object, skip the summary entry.
814 if (!Index)
815 return SkipModuleSummaryEntry();
816
817 switch (Lex.getKind()) {
818 case lltok::kw_gv:
819 return ParseGVEntry(SummaryID);
820 case lltok::kw_module:
821 return ParseModuleEntry(SummaryID);
822 case lltok::kw_typeid:
823 return ParseTypeIdEntry(SummaryID);
824 break;
825 default:
826 return Error(Lex.getLoc(), "unexpected summary kind");
827 }
828 Lex.setIgnoreColonInIdentifiers(false);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000829 return false;
830}
831
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000832static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
833 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
834 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
835}
836
Rafael Espindolae4b02312018-01-11 22:15:05 +0000837// If there was an explicit dso_local, update GV. In the absence of an explicit
838// dso_local we keep the default value.
839static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
840 if (DSOLocal)
841 GV.setDSOLocal(true);
842}
843
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000844/// parseIndirectSymbol:
Fangrui Songf78650a2018-07-30 19:41:25 +0000845/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertilec70d28b2017-10-26 15:00:26 +0000846/// OptionalVisibility OptionalDLLStorageClass
847/// OptionalThreadLocal OptionalUnnamedAddr
848// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000849///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000850/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000851/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000852///
Eric Christopher536f0a92015-05-28 23:07:39 +0000853/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000855bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
856 unsigned L, unsigned Visibility,
857 unsigned DLLStorageClass, bool DSOLocal,
858 GlobalVariable::ThreadLocalMode TLM,
859 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000860 bool IsAlias;
861 if (Lex.getKind() == lltok::kw_alias)
862 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000863 else if (Lex.getKind() == lltok::kw_ifunc)
864 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000865 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000866 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868
Rafael Espindola78527052013-10-06 15:10:43 +0000869 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
870
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000871 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000872 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000873
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000874 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000875 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000876 "symbol with local linkage must have default visibility");
877
David Blaikie2f408302015-09-11 03:22:04 +0000878 Type *Ty;
879 LocTy ExplicitTypeLoc = Lex.getLoc();
880 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000881 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000882 return true;
883
Rafael Espindola64c1e182014-06-03 02:41:57 +0000884 Constant *Aliasee;
885 LocTy AliaseeLoc = Lex.getLoc();
886 if (Lex.getKind() != lltok::kw_bitcast &&
887 Lex.getKind() != lltok::kw_getelementptr &&
888 Lex.getKind() != lltok::kw_addrspacecast &&
889 Lex.getKind() != lltok::kw_inttoptr) {
890 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000891 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000893 // The bitcast dest type is not present, it is implied by the dest type.
894 ValID ID;
895 if (ParseValID(ID))
896 return true;
897 if (ID.Kind != ValID::t_Constant)
898 return Error(AliaseeLoc, "invalid aliasee");
899 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000901
Rafael Espindola64c1e182014-06-03 02:41:57 +0000902 Type *AliaseeType = Aliasee->getType();
903 auto *PTy = dyn_cast<PointerType>(AliaseeType);
904 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000905 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000906 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000908 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000909 return Error(
910 ExplicitTypeLoc,
911 "explicit pointee type doesn't match operand's pointee type");
912
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000913 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
914 return Error(
915 ExplicitTypeLoc,
916 "explicit pointee type should be a function type");
917
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000918 GlobalValue *GVal = nullptr;
919
920 // See if the alias was forward referenced, if so, prepare to replace the
921 // forward reference.
922 if (!Name.empty()) {
923 GVal = M->getNamedValue(Name);
924 if (GVal) {
925 if (!ForwardRefVals.erase(Name))
926 return Error(NameLoc, "redefinition of global '@" + Name + "'");
927 }
928 } else {
929 auto I = ForwardRefValIDs.find(NumberedVals.size());
930 if (I != ForwardRefValIDs.end()) {
931 GVal = I->second.first;
932 ForwardRefValIDs.erase(I);
933 }
934 }
935
Chris Lattnerac161bf2009-01-02 07:01:27 +0000936 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000937 std::unique_ptr<GlobalIndirectSymbol> GA;
938 if (IsAlias)
939 GA.reset(GlobalAlias::create(Ty, AddrSpace,
940 (GlobalValue::LinkageTypes)Linkage, Name,
941 Aliasee, /*Parent*/ nullptr));
942 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000943 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
944 (GlobalValue::LinkageTypes)Linkage, Name,
945 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000946 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000947 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000948 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000949 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000950 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Rafael Espindola54fc2982015-06-17 17:53:31 +0000952 if (Name.empty())
953 NumberedVals.push_back(GA.get());
954
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000955 if (GVal) {
956 // Verify that types agree.
957 if (GVal->getType() != GA->getType())
958 return Error(
959 ExplicitTypeLoc,
960 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattnerac161bf2009-01-02 07:01:27 +0000962 // If they agree, just RAUW the old value with the alias and remove the
963 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000964 GVal->replaceAllUsesWith(GA.get());
965 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000967
Chris Lattnerac161bf2009-01-02 07:01:27 +0000968 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000969 if (IsAlias)
970 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
971 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000972 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000973 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000974
Rafael Espindolaaa273822014-05-09 21:49:17 +0000975 // The module owns this now
976 GA.release();
977
Chris Lattnerac161bf2009-01-02 07:01:27 +0000978 return false;
979}
980
981/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000982/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
983/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000984/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000985/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000986/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
987/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
988/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
989/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000990///
Eric Christopher536f0a92015-05-28 23:07:39 +0000991/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000992/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000993///
994bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
995 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000996 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000997 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000998 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000999 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1000 return Error(NameLoc,
1001 "symbol with local linkage must have default visibility");
1002
Chris Lattnerac161bf2009-01-02 07:01:27 +00001003 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001004 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001005 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001007
Craig Topper2617dcc2014-04-15 06:32:26 +00001008 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001009 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001010 ParseOptionalToken(lltok::kw_externally_initialized,
1011 IsExternallyInitialized,
1012 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001013 ParseGlobalType(IsConstant) ||
1014 ParseType(Ty, TyLoc))
1015 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001016
Chris Lattnerac161bf2009-01-02 07:01:27 +00001017 // If the linkage is specified and is external, then no initializer is
1018 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +00001019 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +00001020 if (!HasLinkage ||
1021 !GlobalValue::isValidDeclarationLinkage(
1022 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001023 if (ParseGlobalValue(Ty, Init))
1024 return true;
1025 }
1026
David Majnemer49b3d9b2015-02-16 08:41:08 +00001027 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +00001028 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
David Majnemer598bd052014-12-09 05:56:09 +00001030 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031
1032 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +00001033 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +00001034 GVal = M->getNamedValue(Name);
1035 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +00001036 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +00001037 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00001038 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +00001040 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +00001042 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001043 ForwardRefValIDs.erase(I);
1044 }
1045 }
1046
David Majnemer598bd052014-12-09 05:56:09 +00001047 GlobalVariable *GV;
1048 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1050 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001051 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001052 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +00001053 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 return Error(TyLoc,
1055 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001056
David Majnemer598bd052014-12-09 05:56:09 +00001057 GV = cast<GlobalVariable>(GVal);
1058
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 // Move the forward-reference to the correct spot in the module.
1060 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1061 }
1062
1063 if (Name.empty())
1064 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001065
Chris Lattnerac161bf2009-01-02 07:01:27 +00001066 // Set the parsed properties on the global.
1067 if (Init)
1068 GV->setInitializer(Init);
1069 GV->setConstant(IsConstant);
1070 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00001071 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001073 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001074 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001075 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001076 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 // Parse attributes on the global.
1079 while (Lex.getKind() == lltok::comma) {
1080 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001081
Chris Lattnerac161bf2009-01-02 07:01:27 +00001082 if (Lex.getKind() == lltok::kw_section) {
1083 Lex.Lex();
1084 GV->setSection(Lex.getStrVal());
1085 if (ParseToken(lltok::StringConstant, "expected global section string"))
1086 return true;
1087 } else if (Lex.getKind() == lltok::kw_align) {
1088 unsigned Alignment;
1089 if (ParseOptionalAlignment(Alignment)) return true;
1090 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001091 } else if (Lex.getKind() == lltok::MetadataVar) {
1092 if (ParseGlobalObjectMetadataAttachment(*GV))
1093 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001094 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001095 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001096 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +00001097 return true;
1098 if (C)
1099 GV->setComdat(C);
1100 else
1101 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102 }
1103 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001104
Javed Absarf3d79042017-05-11 12:28:08 +00001105 AttrBuilder Attrs;
1106 LocTy BuiltinLoc;
1107 std::vector<unsigned> FwdRefAttrGrps;
1108 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1109 return true;
1110 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1111 GV->setAttributes(AttributeSet::get(Context, Attrs));
1112 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1113 }
1114
Chris Lattnerac161bf2009-01-02 07:01:27 +00001115 return false;
1116}
1117
Bill Wendling63b88192013-02-06 06:52:58 +00001118/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001119/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001120bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001121 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001122 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001123 Lex.Lex();
1124
David Majnemerb39e22b2014-12-09 18:33:57 +00001125 if (Lex.getKind() != lltok::AttrGrpID)
1126 return TokError("expected attribute group id");
1127
Bill Wendling63b88192013-02-06 06:52:58 +00001128 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001129 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001130 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001131 Lex.Lex();
1132
1133 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001134 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001135 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001136 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001137 ParseToken(lltok::rbrace, "expected end of attribute group"))
1138 return true;
1139
Bill Wendlingb32b0412013-02-08 06:32:06 +00001140 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001141 return Error(AttrGrpLoc, "attribute group has no attributes");
1142
1143 return false;
1144}
1145
Bill Wendling8b0321d2013-02-08 00:52:31 +00001146/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001147/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001148bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1149 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001150 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001151 bool HaveError = false;
1152
1153 B.clear();
1154
Bill Wendling63b88192013-02-06 06:52:58 +00001155 while (true) {
1156 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001157 if (Token == lltok::kw_builtin)
1158 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001159 switch (Token) {
1160 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001161 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001162 return Error(Lex.getLoc(), "unterminated attribute group");
1163 case lltok::rbrace:
1164 // Finished.
1165 return false;
1166
Bill Wendlingb32b0412013-02-08 06:32:06 +00001167 case lltok::AttrGrpID: {
1168 // Allow a function to reference an attribute group:
1169 //
1170 // define void @foo() #1 { ... }
1171 if (inAttrGrp)
1172 HaveError |=
1173 Error(Lex.getLoc(),
1174 "cannot have an attribute group reference in an attribute group");
1175
1176 unsigned AttrGrpNum = Lex.getUIntVal();
1177 if (inAttrGrp) break;
1178
1179 // Save the reference to the attribute group. We'll fill it in later.
1180 FwdRefAttrGrps.push_back(AttrGrpNum);
1181 break;
1182 }
Bill Wendling63b88192013-02-06 06:52:58 +00001183 // Target-dependent attributes:
1184 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001185 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001186 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001187 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001188 }
1189
1190 // Target-independent attributes:
1191 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001192 // As a hack, we allow function alignment to be initially parsed as an
1193 // attribute on a function declaration/definition or added to an attribute
1194 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001195 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001196 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001197 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001198 if (ParseToken(lltok::equal, "expected '=' here") ||
1199 ParseUInt32(Alignment))
1200 return true;
1201 } else {
1202 if (ParseOptionalAlignment(Alignment))
1203 return true;
1204 }
Bill Wendling63b88192013-02-06 06:52:58 +00001205 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001206 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001207 }
1208 case lltok::kw_alignstack: {
1209 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001210 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001211 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001212 if (ParseToken(lltok::equal, "expected '=' here") ||
1213 ParseUInt32(Alignment))
1214 return true;
1215 } else {
1216 if (ParseOptionalStackAlignment(Alignment))
1217 return true;
1218 }
Bill Wendling63b88192013-02-06 06:52:58 +00001219 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001220 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001221 }
George Burgess IV278199f2016-04-12 01:05:35 +00001222 case lltok::kw_allocsize: {
1223 unsigned ElemSizeArg;
1224 Optional<unsigned> NumElemsArg;
1225 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1226 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1227 return true;
1228 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1229 continue;
1230 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001231 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1232 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1233 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1234 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1235 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001236 case lltok::kw_inaccessiblememonly:
1237 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1238 case lltok::kw_inaccessiblemem_or_argmemonly:
1239 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001240 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1241 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1242 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1243 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1244 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1245 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1246 case lltok::kw_noimplicitfloat:
1247 B.addAttribute(Attribute::NoImplicitFloat); break;
1248 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1249 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1250 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1251 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001252 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001253 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001254 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001255 case lltok::kw_optforfuzzing:
1256 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001257 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1258 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1259 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1260 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1261 case lltok::kw_returns_twice:
1262 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001263 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001264 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1265 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1266 case lltok::kw_sspstrong:
1267 B.addAttribute(Attribute::StackProtectStrong); break;
1268 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001269 case lltok::kw_shadowcallstack:
1270 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001271 case lltok::kw_sanitize_address:
1272 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001273 case lltok::kw_sanitize_hwaddress:
1274 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001275 case lltok::kw_sanitize_thread:
1276 B.addAttribute(Attribute::SanitizeThread); break;
1277 case lltok::kw_sanitize_memory:
1278 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001279 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001280 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001281 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001282
1283 // Error handling.
1284 case lltok::kw_inreg:
1285 case lltok::kw_signext:
1286 case lltok::kw_zeroext:
1287 HaveError |=
1288 Error(Lex.getLoc(),
1289 "invalid use of attribute on a function");
1290 break;
1291 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001292 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001293 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001294 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001295 case lltok::kw_nest:
1296 case lltok::kw_noalias:
1297 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001298 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001299 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001300 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001301 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001302 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001303 HaveError |=
1304 Error(Lex.getLoc(),
1305 "invalid use of parameter-only attribute on a function");
1306 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001307 }
1308
1309 Lex.Lex();
1310 }
1311}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001312
1313//===----------------------------------------------------------------------===//
1314// GlobalValue Reference/Resolution Routines.
1315//===----------------------------------------------------------------------===//
1316
Karl Schimpf77729782015-09-03 18:06:44 +00001317static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1318 const std::string &Name) {
1319 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1320 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1321 else
1322 return new GlobalVariable(*M, PTy->getElementType(), false,
1323 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1324 nullptr, GlobalVariable::NotThreadLocal,
1325 PTy->getAddressSpace());
1326}
1327
Chris Lattnerac161bf2009-01-02 07:01:27 +00001328/// GetGlobalVal - Get a value with the specified name or ID, creating a
1329/// forward reference record if needed. This can return null if the value
1330/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001331GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001332 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001333 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001334 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001335 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001336 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001337 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001338
Chris Lattnerac161bf2009-01-02 07:01:27 +00001339 // Look this name up in the normal function symbol table.
1340 GlobalValue *Val =
1341 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001342
Chris Lattnerac161bf2009-01-02 07:01:27 +00001343 // If this is a forward reference for the value, see if we already created a
1344 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001345 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001346 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001347 if (I != ForwardRefVals.end())
1348 Val = I->second.first;
1349 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001350
Chris Lattnerac161bf2009-01-02 07:01:27 +00001351 // If we have the value in the symbol table or fwd-ref table, return it.
1352 if (Val) {
1353 if (Val->getType() == Ty) return Val;
1354 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001355 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001356 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001358
Chris Lattnerac161bf2009-01-02 07:01:27 +00001359 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001360 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1362 return FwdVal;
1363}
1364
Chris Lattner229907c2011-07-18 04:54:35 +00001365GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1366 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001367 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001368 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001369 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001370 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001371
Craig Topper2617dcc2014-04-15 06:32:26 +00001372 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001373
Chris Lattnerac161bf2009-01-02 07:01:27 +00001374 // If this is a forward reference for the value, see if we already created a
1375 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001376 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001377 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001378 if (I != ForwardRefValIDs.end())
1379 Val = I->second.first;
1380 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001381
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382 // If we have the value in the symbol table or fwd-ref table, return it.
1383 if (Val) {
1384 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001385 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001386 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001387 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001388 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001389
Chris Lattnerac161bf2009-01-02 07:01:27 +00001390 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001391 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001392 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1393 return FwdVal;
1394}
1395
Chris Lattnerac161bf2009-01-02 07:01:27 +00001396//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001397// Comdat Reference/Resolution Routines.
1398//===----------------------------------------------------------------------===//
1399
1400Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1401 // Look this name up in the comdat symbol table.
1402 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1403 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1404 if (I != ComdatSymTab.end())
1405 return &I->second;
1406
1407 // Otherwise, create a new forward reference for this value and remember it.
1408 Comdat *C = M->getOrInsertComdat(Name);
1409 ForwardRefComdats[Name] = Loc;
1410 return C;
1411}
1412
David Majnemerdad0a642014-06-27 18:19:56 +00001413//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001414// Helper Routines.
1415//===----------------------------------------------------------------------===//
1416
1417/// ParseToken - If the current token has the specified kind, eat it and return
1418/// success. Otherwise, emit the specified error and return failure.
1419bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1420 if (Lex.getKind() != T)
1421 return TokError(ErrMsg);
1422 Lex.Lex();
1423 return false;
1424}
1425
Chris Lattner3822f632009-01-02 08:05:26 +00001426/// ParseStringConstant
1427/// ::= StringConstant
1428bool LLParser::ParseStringConstant(std::string &Result) {
1429 if (Lex.getKind() != lltok::StringConstant)
1430 return TokError("expected string constant");
1431 Result = Lex.getStrVal();
1432 Lex.Lex();
1433 return false;
1434}
1435
1436/// ParseUInt32
1437/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001438bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001439 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1440 return TokError("expected integer");
1441 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1442 if (Val64 != unsigned(Val64))
1443 return TokError("expected 32-bit integer (too large)");
1444 Val = Val64;
1445 Lex.Lex();
1446 return false;
1447}
1448
Hal Finkelb0407ba2014-07-18 15:51:28 +00001449/// ParseUInt64
1450/// ::= uint64
1451bool LLParser::ParseUInt64(uint64_t &Val) {
1452 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1453 return TokError("expected integer");
1454 Val = Lex.getAPSIntVal().getLimitedValue();
1455 Lex.Lex();
1456 return false;
1457}
1458
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001459/// ParseTLSModel
1460/// := 'localdynamic'
1461/// := 'initialexec'
1462/// := 'localexec'
1463bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1464 switch (Lex.getKind()) {
1465 default:
1466 return TokError("expected localdynamic, initialexec or localexec");
1467 case lltok::kw_localdynamic:
1468 TLM = GlobalVariable::LocalDynamicTLSModel;
1469 break;
1470 case lltok::kw_initialexec:
1471 TLM = GlobalVariable::InitialExecTLSModel;
1472 break;
1473 case lltok::kw_localexec:
1474 TLM = GlobalVariable::LocalExecTLSModel;
1475 break;
1476 }
1477
1478 Lex.Lex();
1479 return false;
1480}
1481
1482/// ParseOptionalThreadLocal
1483/// := /*empty*/
1484/// := 'thread_local'
1485/// := 'thread_local' '(' tlsmodel ')'
1486bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1487 TLM = GlobalVariable::NotThreadLocal;
1488 if (!EatIfPresent(lltok::kw_thread_local))
1489 return false;
1490
1491 TLM = GlobalVariable::GeneralDynamicTLSModel;
1492 if (Lex.getKind() == lltok::lparen) {
1493 Lex.Lex();
1494 return ParseTLSModel(TLM) ||
1495 ParseToken(lltok::rparen, "expected ')' after thread local model");
1496 }
1497 return false;
1498}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001499
1500/// ParseOptionalAddrSpace
1501/// := /*empty*/
1502/// := 'addrspace' '(' uint32 ')'
1503bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1504 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001505 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001506 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001507 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001508 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001509 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001510}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001511
Artur Pilipenko17376c42015-08-03 14:31:49 +00001512/// ParseStringAttribute
1513/// := StringConstant
1514/// := StringConstant '=' StringConstant
1515bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1516 std::string Attr = Lex.getStrVal();
1517 Lex.Lex();
1518 std::string Val;
1519 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1520 return true;
1521 B.addAttribute(Attr, Val);
1522 return false;
1523}
1524
Bill Wendling34c2eb22012-12-04 23:40:58 +00001525/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1526bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1527 bool HaveError = false;
1528
1529 B.clear();
1530
Eugene Zelenko1804a772016-08-25 00:45:04 +00001531 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001532 lltok::Kind Token = Lex.getKind();
1533 switch (Token) {
1534 default: // End of attributes.
1535 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001536 case lltok::StringConstant: {
1537 if (ParseStringAttribute(B))
1538 return true;
1539 continue;
1540 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001541 case lltok::kw_align: {
1542 unsigned Alignment;
1543 if (ParseOptionalAlignment(Alignment))
1544 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001545 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001546 continue;
1547 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001548 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001549 case lltok::kw_dereferenceable: {
1550 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001551 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001552 return true;
1553 B.addDereferenceableAttr(Bytes);
1554 continue;
1555 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001556 case lltok::kw_dereferenceable_or_null: {
1557 uint64_t Bytes;
1558 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1559 return true;
1560 B.addDereferenceableOrNullAttr(Bytes);
1561 continue;
1562 }
Reid Klecknera534a382013-12-19 02:14:12 +00001563 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001564 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1565 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1566 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1567 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001568 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001569 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1570 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001571 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001572 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1573 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001574 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001575 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001576 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001577 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001578
Stephen Lin7577ed52013-04-20 13:16:13 +00001579 case lltok::kw_alignstack:
1580 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001581 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001582 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001583 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001584 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001585 case lltok::kw_minsize:
1586 case lltok::kw_naked:
1587 case lltok::kw_nobuiltin:
1588 case lltok::kw_noduplicate:
1589 case lltok::kw_noimplicitfloat:
1590 case lltok::kw_noinline:
1591 case lltok::kw_nonlazybind:
1592 case lltok::kw_noredzone:
1593 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001594 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001595 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001596 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001597 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001598 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001599 case lltok::kw_returns_twice:
1600 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001601 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001602 case lltok::kw_sanitize_memory:
1603 case lltok::kw_sanitize_thread:
1604 case lltok::kw_ssp:
1605 case lltok::kw_sspreq:
1606 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001607 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001608 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001609 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001610 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001611 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1612 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001613 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001614
Bill Wendling34c2eb22012-12-04 23:40:58 +00001615 Lex.Lex();
1616 }
1617}
1618
1619/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1620bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1621 bool HaveError = false;
1622
1623 B.clear();
1624
Eugene Zelenko1804a772016-08-25 00:45:04 +00001625 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001626 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001627 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001628 default: // End of attributes.
1629 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001630 case lltok::StringConstant: {
1631 if (ParseStringAttribute(B))
1632 return true;
1633 continue;
1634 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001635 case lltok::kw_dereferenceable: {
1636 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001637 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001638 return true;
1639 B.addDereferenceableAttr(Bytes);
1640 continue;
1641 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001642 case lltok::kw_dereferenceable_or_null: {
1643 uint64_t Bytes;
1644 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1645 return true;
1646 B.addDereferenceableOrNullAttr(Bytes);
1647 continue;
1648 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001649 case lltok::kw_align: {
1650 unsigned Alignment;
1651 if (ParseOptionalAlignment(Alignment))
1652 return true;
1653 B.addAlignmentAttr(Alignment);
1654 continue;
1655 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001656 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1657 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001658 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001659 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1660 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001661
Bill Wendling34c2eb22012-12-04 23:40:58 +00001662 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001663 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001664 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001665 case lltok::kw_nest:
1666 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001667 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001668 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001669 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001670 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001671 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001672 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001673
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001674 case lltok::kw_alignstack:
1675 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001676 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001677 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001678 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001679 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001680 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001681 case lltok::kw_minsize:
1682 case lltok::kw_naked:
1683 case lltok::kw_nobuiltin:
1684 case lltok::kw_noduplicate:
1685 case lltok::kw_noimplicitfloat:
1686 case lltok::kw_noinline:
1687 case lltok::kw_nonlazybind:
1688 case lltok::kw_noredzone:
1689 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001690 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001691 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001692 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001693 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001694 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001695 case lltok::kw_returns_twice:
1696 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001697 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001698 case lltok::kw_sanitize_memory:
1699 case lltok::kw_sanitize_thread:
1700 case lltok::kw_ssp:
1701 case lltok::kw_sspreq:
1702 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001703 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001704 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001705 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001706 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001707 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001708 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001709
1710 case lltok::kw_readnone:
1711 case lltok::kw_readonly:
1712 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001713 }
1714
Chris Lattnerac161bf2009-01-02 07:01:27 +00001715 Lex.Lex();
1716 }
1717}
1718
Rafael Espindolac6269912016-05-10 17:16:45 +00001719static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1720 HasLinkage = true;
1721 switch (Kind) {
1722 default:
1723 HasLinkage = false;
1724 return GlobalValue::ExternalLinkage;
1725 case lltok::kw_private:
1726 return GlobalValue::PrivateLinkage;
1727 case lltok::kw_internal:
1728 return GlobalValue::InternalLinkage;
1729 case lltok::kw_weak:
1730 return GlobalValue::WeakAnyLinkage;
1731 case lltok::kw_weak_odr:
1732 return GlobalValue::WeakODRLinkage;
1733 case lltok::kw_linkonce:
1734 return GlobalValue::LinkOnceAnyLinkage;
1735 case lltok::kw_linkonce_odr:
1736 return GlobalValue::LinkOnceODRLinkage;
1737 case lltok::kw_available_externally:
1738 return GlobalValue::AvailableExternallyLinkage;
1739 case lltok::kw_appending:
1740 return GlobalValue::AppendingLinkage;
1741 case lltok::kw_common:
1742 return GlobalValue::CommonLinkage;
1743 case lltok::kw_extern_weak:
1744 return GlobalValue::ExternalWeakLinkage;
1745 case lltok::kw_external:
1746 return GlobalValue::ExternalLinkage;
1747 }
1748}
1749
Chris Lattnerac161bf2009-01-02 07:01:27 +00001750/// ParseOptionalLinkage
1751/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001752/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001753/// ::= 'internal'
1754/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001755/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001756/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001757/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001758/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001759/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001760/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001761/// ::= 'extern_weak'
1762/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001763bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1764 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001765 unsigned &DLLStorageClass,
1766 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001767 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1768 if (HasLinkage)
1769 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001770 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001771 ParseOptionalVisibility(Visibility);
1772 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001773
1774 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1775 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1776 }
1777
Chris Lattnerac161bf2009-01-02 07:01:27 +00001778 return false;
1779}
1780
Sean Fertilec70d28b2017-10-26 15:00:26 +00001781void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1782 switch (Lex.getKind()) {
1783 default:
1784 DSOLocal = false;
1785 break;
1786 case lltok::kw_dso_local:
1787 DSOLocal = true;
1788 Lex.Lex();
1789 break;
1790 case lltok::kw_dso_preemptable:
1791 DSOLocal = false;
1792 Lex.Lex();
1793 break;
1794 }
1795}
1796
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797/// ParseOptionalVisibility
1798/// ::= /*empty*/
1799/// ::= 'default'
1800/// ::= 'hidden'
1801/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001802///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001803void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001805 default:
1806 Res = GlobalValue::DefaultVisibility;
1807 return;
1808 case lltok::kw_default:
1809 Res = GlobalValue::DefaultVisibility;
1810 break;
1811 case lltok::kw_hidden:
1812 Res = GlobalValue::HiddenVisibility;
1813 break;
1814 case lltok::kw_protected:
1815 Res = GlobalValue::ProtectedVisibility;
1816 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001817 }
1818 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001819}
1820
Nico Rieck7157bb72014-01-14 15:22:47 +00001821/// ParseOptionalDLLStorageClass
1822/// ::= /*empty*/
1823/// ::= 'dllimport'
1824/// ::= 'dllexport'
1825///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001826void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001827 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001828 default:
1829 Res = GlobalValue::DefaultStorageClass;
1830 return;
1831 case lltok::kw_dllimport:
1832 Res = GlobalValue::DLLImportStorageClass;
1833 break;
1834 case lltok::kw_dllexport:
1835 Res = GlobalValue::DLLExportStorageClass;
1836 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001837 }
1838 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001839}
1840
Chris Lattnerac161bf2009-01-02 07:01:27 +00001841/// ParseOptionalCallingConv
1842/// ::= /*empty*/
1843/// ::= 'ccc'
1844/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001845/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001846/// ::= 'coldcc'
1847/// ::= 'x86_stdcallcc'
1848/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001849/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001850/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001851/// ::= 'arm_apcscc'
1852/// ::= 'arm_aapcscc'
1853/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001854/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001855/// ::= 'avr_intrcc'
1856/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001857/// ::= 'ptx_kernel'
1858/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001859/// ::= 'spir_func'
1860/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001861/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001862/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001863/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001864/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001865/// ::= 'preserve_mostcc'
1866/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001867/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001868/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001869/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001870/// ::= 'hhvmcc'
1871/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001872/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001873/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001874/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001875/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001876/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001877/// ::= 'amdgpu_gs'
1878/// ::= 'amdgpu_ps'
1879/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001880/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001882///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001883bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001884 switch (Lex.getKind()) {
1885 default: CC = CallingConv::C; return false;
1886 case lltok::kw_ccc: CC = CallingConv::C; break;
1887 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1888 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1889 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1890 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001891 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001892 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001893 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001894 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1895 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1896 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001897 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001898 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1899 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001900 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1901 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001902 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1903 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001904 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001905 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001906 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001907 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001908 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001909 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1910 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001911 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001912 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001913 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001914 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1915 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001916 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001917 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001918 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001919 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001920 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001921 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1922 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1923 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001924 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001925 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001926 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001927 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001928 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001929 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001930
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 Lex.Lex();
1932 return false;
1933}
1934
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001935/// ParseMetadataAttachment
1936/// ::= !dbg !42
1937bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1938 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1939
1940 std::string Name = Lex.getStrVal();
1941 Kind = M->getMDKindID(Name);
1942 Lex.Lex();
1943
1944 return ParseMDNode(MD);
1945}
1946
Chris Lattner5c427632009-12-30 05:31:19 +00001947/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001948/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001949bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001950 do {
1951 if (Lex.getKind() != lltok::MetadataVar)
1952 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001953
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001954 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001955 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001956 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001957 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001959 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001960 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001961 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001962
Chris Lattner596760d2009-12-29 21:25:40 +00001963 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001964 } while (EatIfPresent(lltok::comma));
1965 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001966}
1967
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001968/// ParseGlobalObjectMetadataAttachment
1969/// ::= !dbg !57
1970bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1971 unsigned MDK;
1972 MDNode *N;
1973 if (ParseMetadataAttachment(MDK, N))
1974 return true;
1975
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001976 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001977 return false;
1978}
1979
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001980/// ParseOptionalFunctionMetadata
1981/// ::= (!dbg !57)*
1982bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001983 while (Lex.getKind() == lltok::MetadataVar)
1984 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001985 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001986 return false;
1987}
1988
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989/// ParseOptionalAlignment
1990/// ::= /* empty */
1991/// ::= 'align' 4
1992bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1993 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001994 if (!EatIfPresent(lltok::kw_align))
1995 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001996 LocTy AlignLoc = Lex.getLoc();
1997 if (ParseUInt32(Alignment)) return true;
1998 if (!isPowerOf2_32(Alignment))
1999 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00002000 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00002001 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00002002 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002003}
2004
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002005/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00002006/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002007/// ::= AttrKind '(' 4 ')'
2008///
2009/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2010bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2011 uint64_t &Bytes) {
2012 assert((AttrKind == lltok::kw_dereferenceable ||
2013 AttrKind == lltok::kw_dereferenceable_or_null) &&
2014 "contract!");
2015
Hal Finkelb0407ba2014-07-18 15:51:28 +00002016 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002017 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00002018 return false;
2019 LocTy ParenLoc = Lex.getLoc();
2020 if (!EatIfPresent(lltok::lparen))
2021 return Error(ParenLoc, "expected '('");
2022 LocTy DerefLoc = Lex.getLoc();
2023 if (ParseUInt64(Bytes)) return true;
2024 ParenLoc = Lex.getLoc();
2025 if (!EatIfPresent(lltok::rparen))
2026 return Error(ParenLoc, "expected ')'");
2027 if (!Bytes)
2028 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2029 return false;
2030}
2031
Chris Lattnerb2f39502009-12-30 05:44:30 +00002032/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002033/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00002034/// ::= ',' align 4
2035///
2036/// This returns with AteExtraComma set to true if it ate an excess comma at the
2037/// end.
2038bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2039 bool &AteExtraComma) {
2040 AteExtraComma = false;
2041 while (EatIfPresent(lltok::comma)) {
2042 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00002043 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00002044 AteExtraComma = true;
2045 return false;
2046 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002047
Chris Lattner95b0ff42010-04-23 00:50:50 +00002048 if (Lex.getKind() != lltok::kw_align)
2049 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00002050
Chris Lattner95b0ff42010-04-23 00:50:50 +00002051 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00002052 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002053
Devang Patelea8a4b92009-09-17 23:04:48 +00002054 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055}
2056
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002057/// ParseOptionalCommaAddrSpace
2058/// ::=
2059/// ::= ',' addrspace(1)
2060///
2061/// This returns with AteExtraComma set to true if it ate an excess comma at the
2062/// end.
2063bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2064 LocTy &Loc,
2065 bool &AteExtraComma) {
2066 AteExtraComma = false;
2067 while (EatIfPresent(lltok::comma)) {
2068 // Metadata at the end is an early exit.
2069 if (Lex.getKind() == lltok::MetadataVar) {
2070 AteExtraComma = true;
2071 return false;
2072 }
2073
2074 Loc = Lex.getLoc();
2075 if (Lex.getKind() != lltok::kw_addrspace)
2076 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2077
2078 if (ParseOptionalAddrSpace(AddrSpace))
2079 return true;
2080 }
2081
2082 return false;
2083}
2084
George Burgess IV278199f2016-04-12 01:05:35 +00002085bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2086 Optional<unsigned> &HowManyArg) {
2087 Lex.Lex();
2088
2089 auto StartParen = Lex.getLoc();
2090 if (!EatIfPresent(lltok::lparen))
2091 return Error(StartParen, "expected '('");
2092
2093 if (ParseUInt32(BaseSizeArg))
2094 return true;
2095
2096 if (EatIfPresent(lltok::comma)) {
2097 auto HowManyAt = Lex.getLoc();
2098 unsigned HowMany;
2099 if (ParseUInt32(HowMany))
2100 return true;
2101 if (HowMany == BaseSizeArg)
2102 return Error(HowManyAt,
2103 "'allocsize' indices can't refer to the same parameter");
2104 HowManyArg = HowMany;
2105 } else
2106 HowManyArg = None;
2107
2108 auto EndParen = Lex.getLoc();
2109 if (!EatIfPresent(lltok::rparen))
2110 return Error(EndParen, "expected ')'");
2111 return false;
2112}
2113
Eli Friedmanfee02c62011-07-25 23:16:38 +00002114/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002115/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002116/// else: ::=
2117///
2118/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002119bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002120 AtomicOrdering &Ordering) {
2121 if (!isAtomic)
2122 return false;
2123
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002124 return ParseScope(SSID) || ParseOrdering(Ordering);
2125}
Tim Northovere94a5182014-03-11 10:48:52 +00002126
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002127/// ParseScope
2128/// ::= syncscope("singlethread" | "<target scope>")?
2129///
2130/// This sets synchronization scope ID to the ID of the parsed value.
2131bool LLParser::ParseScope(SyncScope::ID &SSID) {
2132 SSID = SyncScope::System;
2133 if (EatIfPresent(lltok::kw_syncscope)) {
2134 auto StartParenAt = Lex.getLoc();
2135 if (!EatIfPresent(lltok::lparen))
2136 return Error(StartParenAt, "Expected '(' in syncscope");
2137
2138 std::string SSN;
2139 auto SSNAt = Lex.getLoc();
2140 if (ParseStringConstant(SSN))
2141 return Error(SSNAt, "Expected synchronization scope name");
2142
2143 auto EndParenAt = Lex.getLoc();
2144 if (!EatIfPresent(lltok::rparen))
2145 return Error(EndParenAt, "Expected ')' in syncscope");
2146
2147 SSID = Context.getOrInsertSyncScopeID(SSN);
2148 }
2149
2150 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002151}
2152
2153/// ParseOrdering
2154/// ::= AtomicOrdering
2155///
2156/// This sets Ordering to the parsed value.
2157bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002158 switch (Lex.getKind()) {
2159 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002160 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2161 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2162 // Not specified yet:
2163 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2164 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2165 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2166 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2167 case lltok::kw_seq_cst:
2168 Ordering = AtomicOrdering::SequentiallyConsistent;
2169 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002170 }
2171 Lex.Lex();
2172 return false;
2173}
2174
Charles Davisbe5557e2010-02-12 00:31:15 +00002175/// ParseOptionalStackAlignment
2176/// ::= /* empty */
2177/// ::= 'alignstack' '(' 4 ')'
2178bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2179 Alignment = 0;
2180 if (!EatIfPresent(lltok::kw_alignstack))
2181 return false;
2182 LocTy ParenLoc = Lex.getLoc();
2183 if (!EatIfPresent(lltok::lparen))
2184 return Error(ParenLoc, "expected '('");
2185 LocTy AlignLoc = Lex.getLoc();
2186 if (ParseUInt32(Alignment)) return true;
2187 ParenLoc = Lex.getLoc();
2188 if (!EatIfPresent(lltok::rparen))
2189 return Error(ParenLoc, "expected ')'");
2190 if (!isPowerOf2_32(Alignment))
2191 return Error(AlignLoc, "stack alignment is not a power of two");
2192 return false;
2193}
Devang Patelea8a4b92009-09-17 23:04:48 +00002194
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002195/// ParseIndexList - This parses the index list for an insert/extractvalue
2196/// instruction. This sets AteExtraComma in the case where we eat an extra
2197/// comma at the end of the line and find that it is followed by metadata.
2198/// Clients that don't allow metadata can call the version of this function that
2199/// only takes one argument.
2200///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201/// ParseIndexList
2202/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002203///
2204bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2205 bool &AteExtraComma) {
2206 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002207
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 if (Lex.getKind() != lltok::comma)
2209 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattner3822f632009-01-02 08:05:26 +00002211 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002212 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002213 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002214 AteExtraComma = true;
2215 return false;
2216 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002217 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002218 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002219 Indices.push_back(Idx);
2220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002221
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 return false;
2223}
2224
2225//===----------------------------------------------------------------------===//
2226// Type Parsing.
2227//===----------------------------------------------------------------------===//
2228
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002229/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002230bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002231 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 switch (Lex.getKind()) {
2233 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002234 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002236 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002240 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002241 // Type ::= StructType
2242 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 return true;
2244 break;
2245 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002246 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 Lex.Lex(); // eat the lsquare.
2248 if (ParseArrayVectorType(Result, false))
2249 return true;
2250 break;
2251 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002253 Lex.Lex();
2254 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002255 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002256 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 } else if (ParseArrayVectorType(Result, true))
2259 return true;
2260 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002261 case lltok::LocalVar: {
2262 // Type ::= %foo
2263 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002264
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002265 // If the type hasn't been defined yet, create a forward definition and
2266 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002267 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002268 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002269 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002271 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 Lex.Lex();
2273 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002274 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002275
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002276 case lltok::LocalVarID: {
2277 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002278 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002279
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280 // If the type hasn't been defined yet, create a forward definition and
2281 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002282 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002283 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002284 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002286 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287 Lex.Lex();
2288 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002289 }
2290 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002291
2292 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002293 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 switch (Lex.getKind()) {
2295 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002296 default:
2297 if (!AllowVoid && Result->isVoidTy())
2298 return Error(TypeLoc, "void type only allowed for function results");
2299 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002301 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002302 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002303 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002305 if (Result->isVoidTy())
2306 return TokError("pointers to void are invalid - use i8* instead");
2307 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002308 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002309 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 Lex.Lex();
2311 break;
2312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002313 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002315 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002317 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002318 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002319 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002320 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002321 unsigned AddrSpace;
2322 if (ParseOptionalAddrSpace(AddrSpace) ||
2323 ParseToken(lltok::star, "expected '*' in address space"))
2324 return true;
2325
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 break;
2328 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002329
Chris Lattnerac161bf2009-01-02 07:01:27 +00002330 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2331 case lltok::lparen:
2332 if (ParseFunctionType(Result))
2333 return true;
2334 break;
2335 }
2336 }
2337}
2338
2339/// ParseParameterList
2340/// ::= '(' ')'
2341/// ::= '(' Arg (',' Arg)* ')'
2342/// Arg
2343/// ::= Type OptionalAttributes Value OptionalAttributes
2344bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002345 PerFunctionState &PFS, bool IsMustTailCall,
2346 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002347 if (ParseToken(lltok::lparen, "expected '(' in call"))
2348 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 while (Lex.getKind() != lltok::rparen) {
2351 // If this isn't the first argument, we need a comma.
2352 if (!ArgList.empty() &&
2353 ParseToken(lltok::comma, "expected ',' in argument list"))
2354 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
Reid Kleckner83498642014-08-26 00:33:28 +00002356 // Parse an ellipsis if this is a musttail call in a variadic function.
2357 if (Lex.getKind() == lltok::dotdotdot) {
2358 const char *Msg = "unexpected ellipsis in argument list for ";
2359 if (!IsMustTailCall)
2360 return TokError(Twine(Msg) + "non-musttail call");
2361 if (!InVarArgsFunc)
2362 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2363 Lex.Lex(); // Lex the '...', it is purely for readability.
2364 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2365 }
2366
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367 // Parse the argument.
2368 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002369 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002370 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002372 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002374
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002375 if (ArgTy->isMetadataTy()) {
2376 if (ParseMetadataAsValue(V, PFS))
2377 return true;
2378 } else {
2379 // Otherwise, handle normal operands.
2380 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2381 return true;
2382 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002383 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002384 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 }
2386
Reid Kleckner83498642014-08-26 00:33:28 +00002387 if (IsMustTailCall && InVarArgsFunc)
2388 return TokError("expected '...' at end of argument list for musttail call "
2389 "in varargs function");
2390
Chris Lattnerac161bf2009-01-02 07:01:27 +00002391 Lex.Lex(); // Lex the ')'.
2392 return false;
2393}
2394
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002395/// ParseOptionalOperandBundles
2396/// ::= /*empty*/
2397/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2398///
2399/// OperandBundle
2400/// ::= bundle-tag '(' ')'
2401/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2402///
2403/// bundle-tag ::= String Constant
2404bool LLParser::ParseOptionalOperandBundles(
2405 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2406 LocTy BeginLoc = Lex.getLoc();
2407 if (!EatIfPresent(lltok::lsquare))
2408 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002410 while (Lex.getKind() != lltok::rsquare) {
2411 // If this isn't the first operand bundle, we need a comma.
2412 if (!BundleList.empty() &&
2413 ParseToken(lltok::comma, "expected ',' in input list"))
2414 return true;
2415
2416 std::string Tag;
2417 if (ParseStringConstant(Tag))
2418 return true;
2419
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002420 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2421 return true;
2422
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002423 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002424 while (Lex.getKind() != lltok::rparen) {
2425 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002426 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002427 ParseToken(lltok::comma, "expected ',' in input list"))
2428 return true;
2429
2430 Type *Ty = nullptr;
2431 Value *Input = nullptr;
2432 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2433 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002434 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002435 }
2436
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002437 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2438
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002439 Lex.Lex(); // Lex the ')'.
2440 }
2441
2442 if (BundleList.empty())
2443 return Error(BeginLoc, "operand bundle set must not be empty");
2444
2445 Lex.Lex(); // Lex the ']'.
2446 return false;
2447}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448
Chris Lattner2ed06b42009-01-05 18:34:07 +00002449/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002450/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451/// ::= '(' ArgTypeListI ')'
2452/// ArgTypeListI
2453/// ::= /*empty*/
2454/// ::= '...'
2455/// ::= ArgTypeList ',' '...'
2456/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002457///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002458bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2459 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 isVarArg = false;
2461 assert(Lex.getKind() == lltok::lparen);
2462 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 if (Lex.getKind() == lltok::rparen) {
2465 // empty
2466 } else if (Lex.getKind() == lltok::dotdotdot) {
2467 isVarArg = true;
2468 Lex.Lex();
2469 } else {
2470 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002471 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002472 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002475 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002476 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002477
Chris Lattnerfdd87902009-10-05 05:54:46 +00002478 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002479 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Chris Lattnerdef19492011-06-17 06:36:20 +00002481 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002482 Name = Lex.getStrVal();
2483 Lex.Lex();
2484 }
Chris Lattner3822f632009-01-02 08:05:26 +00002485
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002486 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002487 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002489 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002490 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002491 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002492
Chris Lattner3822f632009-01-02 08:05:26 +00002493 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002495 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 break;
2498 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 // Otherwise must be an argument type.
2501 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002502 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002503
Chris Lattnerfdd87902009-10-05 05:54:46 +00002504 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002505 return Error(TypeLoc, "argument can not have void type");
2506
Chris Lattnerdef19492011-06-17 06:36:20 +00002507 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 Name = Lex.getStrVal();
2509 Lex.Lex();
2510 } else {
2511 Name = "";
2512 }
Chris Lattner3822f632009-01-02 08:05:26 +00002513
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002514 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002515 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002516
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002517 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002518 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002519 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 }
2521 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattner3822f632009-01-02 08:05:26 +00002523 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002525
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526/// ParseFunctionType
2527/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002528bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 assert(Lex.getKind() == lltok::lparen);
2530
Chris Lattnerce473c72009-01-05 08:04:33 +00002531 if (!FunctionType::isValidReturnType(Result))
2532 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002533
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002534 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002535 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002536 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 // Reject names on the arguments lists.
2540 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2541 if (!ArgList[i].Name.empty())
2542 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002543 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002544 return Error(ArgList[i].Loc,
2545 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002546 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002547
Jay Foadb804a2b2011-07-12 14:06:48 +00002548 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002550 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002551
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002552 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 return false;
2554}
2555
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002556/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2557/// other structs.
2558bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2559 SmallVector<Type*, 8> Elts;
2560 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002561
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002562 Result = StructType::get(Context, Elts, Packed);
2563 return false;
2564}
2565
2566/// ParseStructDefinition - Parse a struct in a 'type' definition.
2567bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2568 std::pair<Type*, LocTy> &Entry,
2569 Type *&ResultTy) {
2570 // If the type was already defined, diagnose the redefinition.
2571 if (Entry.first && !Entry.second.isValid())
2572 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002573
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002574 // If we have opaque, just return without filling in the definition for the
2575 // struct. This counts as a definition as far as the .ll file goes.
2576 if (EatIfPresent(lltok::kw_opaque)) {
2577 // This type is being defined, so clear the location to indicate this.
2578 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002579
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002580 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002581 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002582 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002583 ResultTy = Entry.first;
2584 return false;
2585 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002586
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002587 // If the type starts with '<', then it is either a packed struct or a vector.
2588 bool isPacked = EatIfPresent(lltok::less);
2589
2590 // If we don't have a struct, then we have a random type alias, which we
2591 // accept for compatibility with old files. These types are not allowed to be
2592 // forward referenced and not allowed to be recursive.
2593 if (Lex.getKind() != lltok::lbrace) {
2594 if (Entry.first)
2595 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002596
Craig Topper2617dcc2014-04-15 06:32:26 +00002597 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002598 if (isPacked)
2599 return ParseArrayVectorType(ResultTy, true);
2600 return ParseType(ResultTy);
2601 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002602
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002603 // This type is being defined, so clear the location to indicate this.
2604 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002605
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002606 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002607 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002608 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002609
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002610 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002611
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002612 SmallVector<Type*, 8> Body;
2613 if (ParseStructBody(Body) ||
2614 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2615 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002616
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002617 STy->setBody(Body, isPacked);
2618 ResultTy = STy;
2619 return false;
2620}
2621
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002623/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002625/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002627/// ::= '<' '{' Type (',' Type)* '}' '>'
2628bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002629 assert(Lex.getKind() == lltok::lbrace);
2630 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002631
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002632 // Handle the empty struct.
2633 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002634 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635
Chris Lattnerf880ca22009-03-09 04:49:14 +00002636 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002637 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002638 if (ParseType(Ty)) return true;
2639 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002640
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002641 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002642 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643
Chris Lattner3822f632009-01-02 08:05:26 +00002644 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002645 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002646 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002647
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002648 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002649 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002650
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002651 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002653
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002654 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655}
2656
2657/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2658/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002659/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660/// ::= '[' APSINTVAL 'x' Types ']'
2661/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002662bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2664 Lex.getAPSIntVal().getBitWidth() > 64)
2665 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 LocTy SizeLoc = Lex.getLoc();
2668 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002669 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Chris Lattner3822f632009-01-02 08:05:26 +00002671 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2672 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002673
2674 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002675 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002676 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002677
Chris Lattner3822f632009-01-02 08:05:26 +00002678 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2679 "expected end of sequential type"))
2680 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002681
Chris Lattnerac161bf2009-01-02 07:01:27 +00002682 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002683 if (Size == 0)
2684 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 if ((unsigned)Size != Size)
2686 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002687 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002688 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002689 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002691 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002693 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 }
2695 return false;
2696}
2697
2698//===----------------------------------------------------------------------===//
2699// Function Semantic Analysis.
2700//===----------------------------------------------------------------------===//
2701
Chris Lattner3432c622009-10-28 03:39:23 +00002702LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2703 int functionNumber)
2704 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002705
2706 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002707 for (Argument &A : F.args())
2708 if (!A.hasName())
2709 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710}
2711
2712LLParser::PerFunctionState::~PerFunctionState() {
2713 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714
David Blaikie9ebdc692015-09-21 21:07:50 +00002715 for (const auto &P : ForwardRefVals) {
2716 if (isa<BasicBlock>(P.second.first))
2717 continue;
2718 P.second.first->replaceAllUsesWith(
2719 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002720 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002721 }
2722
2723 for (const auto &P : ForwardRefValIDs) {
2724 if (isa<BasicBlock>(P.second.first))
2725 continue;
2726 P.second.first->replaceAllUsesWith(
2727 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002728 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002729 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730}
2731
Chris Lattner3432c622009-10-28 03:39:23 +00002732bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733 if (!ForwardRefVals.empty())
2734 return P.Error(ForwardRefVals.begin()->second.second,
2735 "use of undefined value '%" + ForwardRefVals.begin()->first +
2736 "'");
2737 if (!ForwardRefValIDs.empty())
2738 return P.Error(ForwardRefValIDs.begin()->second.second,
2739 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002740 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 return false;
2742}
2743
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002744static bool isValidVariableType(Module *M, Type *Ty, Value *Val, bool IsCall) {
2745 if (Val->getType() == Ty)
2746 return true;
2747 // For calls we also accept variables in the program address space
2748 if (IsCall && isa<PointerType>(Ty)) {
2749 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
2750 M->getDataLayout().getProgramAddressSpace());
2751 if (Val->getType() == TyInProgAS)
2752 return true;
2753 }
2754 return false;
2755}
2756
Chris Lattnerac161bf2009-01-02 07:01:27 +00002757/// GetVal - Get a value with the specified name or ID, creating a
2758/// forward reference record if needed. This can return null if the value
2759/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002760Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002761 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002762 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002763 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002764
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 // If this is a forward reference for the value, see if we already created a
2766 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002767 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002768 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002769 if (I != ForwardRefVals.end())
2770 Val = I->second.first;
2771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002772
Chris Lattnerac161bf2009-01-02 07:01:27 +00002773 // If we have the value in the symbol table or fwd-ref table, return it.
2774 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002775 if (isValidVariableType(P.M, Ty, Val, IsCall))
2776 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002777 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002778 P.Error(Loc, "'%" + Name + "' is not a basic block");
2779 else
2780 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002781 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002782 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002784
Chris Lattnerac161bf2009-01-02 07:01:27 +00002785 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002786 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002788 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 // Otherwise, create a new forward reference for this value and remember it.
2792 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002793 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002794 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002795 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002796 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002797 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002798
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2800 return FwdVal;
2801}
2802
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002803Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2804 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002806 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 // If this is a forward reference for the value, see if we already created a
2809 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002810 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002811 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002812 if (I != ForwardRefValIDs.end())
2813 Val = I->second.first;
2814 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002815
Chris Lattnerac161bf2009-01-02 07:01:27 +00002816 // If we have the value in the symbol table or fwd-ref table, return it.
2817 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002818 if (isValidVariableType(P.M, Ty, Val, IsCall))
2819 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002820 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002821 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002823 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002824 getTypeString(Val->getType()) + "'");
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
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002828 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002830 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 // Otherwise, create a new forward reference for this value and remember it.
2834 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002835 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002836 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002837 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002838 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002839 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2842 return FwdVal;
2843}
2844
2845/// SetInstName - After an instruction is parsed and inserted into its
2846/// basic block, this installs its name.
2847bool LLParser::PerFunctionState::SetInstName(int NameID,
2848 const std::string &NameStr,
2849 LocTy NameLoc, Instruction *Inst) {
2850 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002851 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 if (NameID != -1 || !NameStr.empty())
2853 return P.Error(NameLoc, "instructions returning void cannot have a name");
2854 return false;
2855 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002856
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 // If this was a numbered instruction, verify that the instruction is the
2858 // expected value and resolve any forward references.
2859 if (NameStr.empty()) {
2860 // If neither a name nor an ID was specified, just use the next ID.
2861 if (NameID == -1)
2862 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863
Chris Lattnerac161bf2009-01-02 07:01:27 +00002864 if (unsigned(NameID) != NumberedVals.size())
2865 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002866 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002867
David Blaikie9ebdc692015-09-21 21:07:50 +00002868 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002870 Value *Sentinel = FI->second.first;
2871 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002872 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002873 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002874
2875 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002876 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002877 ForwardRefValIDs.erase(FI);
2878 }
2879
2880 NumberedVals.push_back(Inst);
2881 return false;
2882 }
2883
2884 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002885 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002886 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002887 Value *Sentinel = FI->second.first;
2888 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002889 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002890 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002891
2892 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002893 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 ForwardRefVals.erase(FI);
2895 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002896
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 // Set the name on the instruction.
2898 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002899
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002900 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002901 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002902 NameStr + "'");
2903 return false;
2904}
2905
2906/// GetBB - Get a basic block with the specified name or ID, creating a
2907/// forward reference record if needed.
2908BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2909 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002910 return dyn_cast_or_null<BasicBlock>(
2911 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002912}
2913
2914BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002915 return dyn_cast_or_null<BasicBlock>(
2916 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002917}
2918
2919/// DefineBB - Define the specified basic block, which is either named or
2920/// unnamed. If there is an error, this returns null otherwise it returns
2921/// the block being defined.
2922BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2923 LocTy Loc) {
2924 BasicBlock *BB;
2925 if (Name.empty())
2926 BB = GetBB(NumberedVals.size(), Loc);
2927 else
2928 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002929 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002930
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 // Move the block to the end of the function. Forward ref'd blocks are
2932 // inserted wherever they happen to be referenced.
2933 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002934
Chris Lattnerac161bf2009-01-02 07:01:27 +00002935 // Remove the block from forward ref sets.
2936 if (Name.empty()) {
2937 ForwardRefValIDs.erase(NumberedVals.size());
2938 NumberedVals.push_back(BB);
2939 } else {
2940 // BB forward references are already in the function symbol table.
2941 ForwardRefVals.erase(Name);
2942 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002943
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 return BB;
2945}
2946
2947//===----------------------------------------------------------------------===//
2948// Constants.
2949//===----------------------------------------------------------------------===//
2950
2951/// ParseValID - Parse an abstract value that doesn't necessarily have a
2952/// type implied. For example, if we parse "4" we don't know what integer type
2953/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002954/// sanity. PFS is used to convert function-local operands of metadata (since
2955/// metadata operands are not just parsed here but also converted to values).
2956/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002957bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002958 ID.Loc = Lex.getLoc();
2959 switch (Lex.getKind()) {
2960 default: return TokError("expected value token");
2961 case lltok::GlobalID: // @42
2962 ID.UIntVal = Lex.getUIntVal();
2963 ID.Kind = ValID::t_GlobalID;
2964 break;
2965 case lltok::GlobalVar: // @foo
2966 ID.StrVal = Lex.getStrVal();
2967 ID.Kind = ValID::t_GlobalName;
2968 break;
2969 case lltok::LocalVarID: // %42
2970 ID.UIntVal = Lex.getUIntVal();
2971 ID.Kind = ValID::t_LocalID;
2972 break;
2973 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974 ID.StrVal = Lex.getStrVal();
2975 ID.Kind = ValID::t_LocalName;
2976 break;
2977 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002978 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002979 ID.Kind = ValID::t_APSInt;
2980 break;
2981 case lltok::APFloat:
2982 ID.APFloatVal = Lex.getAPFloatVal();
2983 ID.Kind = ValID::t_APFloat;
2984 break;
2985 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002986 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002987 ID.Kind = ValID::t_Constant;
2988 break;
2989 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002990 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002991 ID.Kind = ValID::t_Constant;
2992 break;
2993 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2994 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2995 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002996 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002997
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 case lltok::lbrace: {
2999 // ValID ::= '{' ConstVector '}'
3000 Lex.Lex();
3001 SmallVector<Constant*, 16> Elts;
3002 if (ParseGlobalValueVector(Elts) ||
3003 ParseToken(lltok::rbrace, "expected end of struct constant"))
3004 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003005
David Blaikieadbda4b2015-08-03 20:08:41 +00003006 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003007 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00003008 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3009 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003010 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003011 return false;
3012 }
3013 case lltok::less: {
3014 // ValID ::= '<' ConstVector '>' --> Vector.
3015 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3016 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00003017 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003018
Chris Lattnerac161bf2009-01-02 07:01:27 +00003019 SmallVector<Constant*, 16> Elts;
3020 LocTy FirstEltLoc = Lex.getLoc();
3021 if (ParseGlobalValueVector(Elts) ||
3022 (isPackedStruct &&
3023 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3024 ParseToken(lltok::greater, "expected end of constant"))
3025 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003026
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00003028 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3029 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3030 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003031 ID.UIntVal = Elts.size();
3032 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003033 return false;
3034 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003035
Chris Lattnerac161bf2009-01-02 07:01:27 +00003036 if (Elts.empty())
3037 return Error(ID.Loc, "constant vector must not be empty");
3038
Duncan Sands9dff9be2010-02-15 16:12:20 +00003039 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003040 !Elts[0]->getType()->isFloatingPointTy() &&
3041 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003042 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003043 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003044
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 // Verify that all the vector elements have the same type.
3046 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3047 if (Elts[i]->getType() != Elts[0]->getType())
3048 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003049 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003050 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003051
Chris Lattner69229312011-02-15 00:14:00 +00003052 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 ID.Kind = ValID::t_Constant;
3054 return false;
3055 }
3056 case lltok::lsquare: { // Array Constant
3057 Lex.Lex();
3058 SmallVector<Constant*, 16> Elts;
3059 LocTy FirstEltLoc = Lex.getLoc();
3060 if (ParseGlobalValueVector(Elts) ||
3061 ParseToken(lltok::rsquare, "expected end of array constant"))
3062 return true;
3063
3064 // Handle empty element.
3065 if (Elts.empty()) {
3066 // Use undef instead of an array because it's inconvenient to determine
3067 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003068 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003069 return false;
3070 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003071
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003073 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003074 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003075
Owen Anderson4056ca92009-07-29 22:17:13 +00003076 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003077
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003079 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 if (Elts[i]->getType() != Elts[0]->getType())
3081 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003082 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003083 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003084 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003085
Jay Foad83be3612011-06-22 09:24:39 +00003086 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 ID.Kind = ValID::t_Constant;
3088 return false;
3089 }
3090 case lltok::kw_c: // c "foo"
3091 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003092 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3093 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003094 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3095 ID.Kind = ValID::t_Constant;
3096 return false;
3097
3098 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003099 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3100 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003101 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003102 Lex.Lex();
3103 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003104 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003105 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003106 ParseStringConstant(ID.StrVal) ||
3107 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003108 ParseToken(lltok::StringConstant, "expected constraint string"))
3109 return true;
3110 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003111 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003112 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003113 ID.Kind = ValID::t_InlineAsm;
3114 return false;
3115 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003116
Chris Lattner3432c622009-10-28 03:39:23 +00003117 case lltok::kw_blockaddress: {
3118 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3119 Lex.Lex();
3120
3121 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003122
Chris Lattner3432c622009-10-28 03:39:23 +00003123 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3124 ParseValID(Fn) ||
3125 ParseToken(lltok::comma, "expected comma in block address expression")||
3126 ParseValID(Label) ||
3127 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3128 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003129
Chris Lattner3432c622009-10-28 03:39:23 +00003130 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3131 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003132 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003133 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003134
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003135 // Try to find the function (but skip it if it's forward-referenced).
3136 GlobalValue *GV = nullptr;
3137 if (Fn.Kind == ValID::t_GlobalID) {
3138 if (Fn.UIntVal < NumberedVals.size())
3139 GV = NumberedVals[Fn.UIntVal];
3140 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3141 GV = M->getNamedValue(Fn.StrVal);
3142 }
3143 Function *F = nullptr;
3144 if (GV) {
3145 // Confirm that it's actually a function with a definition.
3146 if (!isa<Function>(GV))
3147 return Error(Fn.Loc, "expected function name in blockaddress");
3148 F = cast<Function>(GV);
3149 if (F->isDeclaration())
3150 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3151 }
3152
3153 if (!F) {
3154 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003155 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003156 ForwardRefBlockAddresses.insert(std::make_pair(
3157 std::move(Fn),
3158 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003159 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3160 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003161 if (!FwdRef)
3162 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3163 GlobalValue::InternalLinkage, nullptr, "");
3164 ID.ConstantVal = FwdRef;
3165 ID.Kind = ValID::t_Constant;
3166 return false;
3167 }
3168
3169 // We found the function; now find the basic block. Don't use PFS, since we
3170 // might be inside a constant expression.
3171 BasicBlock *BB;
3172 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3173 if (Label.Kind == ValID::t_LocalID)
3174 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3175 else
3176 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3177 if (!BB)
3178 return Error(Label.Loc, "referenced value is not a basic block");
3179 } else {
3180 if (Label.Kind == ValID::t_LocalID)
3181 return Error(Label.Loc, "cannot take address of numeric label after "
3182 "the function is defined");
3183 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003184 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003185 if (!BB)
3186 return Error(Label.Loc, "referenced value is not a basic block");
3187 }
3188
3189 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003190 ID.Kind = ValID::t_Constant;
3191 return false;
3192 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003193
Chris Lattnerac161bf2009-01-02 07:01:27 +00003194 case lltok::kw_trunc:
3195 case lltok::kw_zext:
3196 case lltok::kw_sext:
3197 case lltok::kw_fptrunc:
3198 case lltok::kw_fpext:
3199 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003200 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003201 case lltok::kw_uitofp:
3202 case lltok::kw_sitofp:
3203 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003204 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003206 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003207 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003208 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003209 Constant *SrcVal;
3210 Lex.Lex();
3211 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3212 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003213 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003214 ParseType(DestTy) ||
3215 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3216 return true;
3217 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3218 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003219 getTypeString(SrcVal->getType()) + "' to '" +
3220 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003221 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003222 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 ID.Kind = ValID::t_Constant;
3224 return false;
3225 }
3226 case lltok::kw_extractvalue: {
3227 Lex.Lex();
3228 Constant *Val;
3229 SmallVector<unsigned, 4> Indices;
3230 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3231 ParseGlobalTypeAndValue(Val) ||
3232 ParseIndexList(Indices) ||
3233 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3234 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003235
Chris Lattner392be582010-02-12 20:49:41 +00003236 if (!Val->getType()->isAggregateType())
3237 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003238 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003239 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003240 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241 ID.Kind = ValID::t_Constant;
3242 return false;
3243 }
3244 case lltok::kw_insertvalue: {
3245 Lex.Lex();
3246 Constant *Val0, *Val1;
3247 SmallVector<unsigned, 4> Indices;
3248 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3249 ParseGlobalTypeAndValue(Val0) ||
3250 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3251 ParseGlobalTypeAndValue(Val1) ||
3252 ParseIndexList(Indices) ||
3253 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3254 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003255 if (!Val0->getType()->isAggregateType())
3256 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003257 Type *IndexedType =
3258 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3259 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003260 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003261 if (IndexedType != Val1->getType())
3262 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3263 getTypeString(Val1->getType()) +
3264 "' instead of '" + getTypeString(IndexedType) +
3265 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003266 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 ID.Kind = ValID::t_Constant;
3268 return false;
3269 }
3270 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003271 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003272 unsigned PredVal, Opc = Lex.getUIntVal();
3273 Constant *Val0, *Val1;
3274 Lex.Lex();
3275 if (ParseCmpPredicate(PredVal, Opc) ||
3276 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3277 ParseGlobalTypeAndValue(Val0) ||
3278 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3279 ParseGlobalTypeAndValue(Val1) ||
3280 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3281 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003282
Chris Lattnerac161bf2009-01-02 07:01:27 +00003283 if (Val0->getType() != Val1->getType())
3284 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003285
Chris Lattnerac161bf2009-01-02 07:01:27 +00003286 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003287
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003289 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003291 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003292 } else {
3293 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003294 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003295 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003297 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003298 }
3299 ID.Kind = ValID::t_Constant;
3300 return false;
3301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003302
Chris Lattnerac161bf2009-01-02 07:01:27 +00003303 // Binary Operators.
3304 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003305 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003306 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003307 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003308 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003309 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003310 case lltok::kw_udiv:
3311 case lltok::kw_sdiv:
3312 case lltok::kw_fdiv:
3313 case lltok::kw_urem:
3314 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003315 case lltok::kw_frem:
3316 case lltok::kw_shl:
3317 case lltok::kw_lshr:
3318 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003319 bool NUW = false;
3320 bool NSW = false;
3321 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003322 unsigned Opc = Lex.getUIntVal();
3323 Constant *Val0, *Val1;
3324 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003325 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003326 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3327 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003328 if (EatIfPresent(lltok::kw_nuw))
3329 NUW = true;
3330 if (EatIfPresent(lltok::kw_nsw)) {
3331 NSW = true;
3332 if (EatIfPresent(lltok::kw_nuw))
3333 NUW = true;
3334 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003335 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3336 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003337 if (EatIfPresent(lltok::kw_exact))
3338 Exact = true;
3339 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3341 ParseGlobalTypeAndValue(Val0) ||
3342 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3343 ParseGlobalTypeAndValue(Val1) ||
3344 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3345 return true;
3346 if (Val0->getType() != Val1->getType())
3347 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003348 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003349 if (NUW)
3350 return Error(ModifierLoc, "nuw only applies to integer operations");
3351 if (NSW)
3352 return Error(ModifierLoc, "nsw only applies to integer operations");
3353 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003354 // Check that the type is valid for the operator.
3355 switch (Opc) {
3356 case Instruction::Add:
3357 case Instruction::Sub:
3358 case Instruction::Mul:
3359 case Instruction::UDiv:
3360 case Instruction::SDiv:
3361 case Instruction::URem:
3362 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003363 case Instruction::Shl:
3364 case Instruction::AShr:
3365 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003366 if (!Val0->getType()->isIntOrIntVectorTy())
3367 return Error(ID.Loc, "constexpr requires integer operands");
3368 break;
3369 case Instruction::FAdd:
3370 case Instruction::FSub:
3371 case Instruction::FMul:
3372 case Instruction::FDiv:
3373 case Instruction::FRem:
3374 if (!Val0->getType()->isFPOrFPVectorTy())
3375 return Error(ID.Loc, "constexpr requires fp operands");
3376 break;
3377 default: llvm_unreachable("Unknown binary operator!");
3378 }
Dan Gohman1b849082009-09-07 23:54:19 +00003379 unsigned Flags = 0;
3380 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3381 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003382 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003383 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003384 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003385 ID.Kind = ValID::t_Constant;
3386 return false;
3387 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003388
Chris Lattnerac161bf2009-01-02 07:01:27 +00003389 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003390 case lltok::kw_and:
3391 case lltok::kw_or:
3392 case lltok::kw_xor: {
3393 unsigned Opc = Lex.getUIntVal();
3394 Constant *Val0, *Val1;
3395 Lex.Lex();
3396 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3397 ParseGlobalTypeAndValue(Val0) ||
3398 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3399 ParseGlobalTypeAndValue(Val1) ||
3400 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3401 return true;
3402 if (Val0->getType() != Val1->getType())
3403 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003404 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003405 return Error(ID.Loc,
3406 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003407 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003408 ID.Kind = ValID::t_Constant;
3409 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003410 }
3411
Chris Lattnerac161bf2009-01-02 07:01:27 +00003412 case lltok::kw_getelementptr:
3413 case lltok::kw_shufflevector:
3414 case lltok::kw_insertelement:
3415 case lltok::kw_extractelement:
3416 case lltok::kw_select: {
3417 unsigned Opc = Lex.getUIntVal();
3418 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003419 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003420 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003421 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003422
Dan Gohman1639c392009-07-27 21:53:46 +00003423 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003424 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003425
3426 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3427 return true;
3428
3429 LocTy ExplicitTypeLoc = Lex.getLoc();
3430 if (Opc == Instruction::GetElementPtr) {
3431 if (ParseType(Ty) ||
3432 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3433 return true;
3434 }
3435
Peter Collingbourned93620b2016-11-10 22:34:55 +00003436 Optional<unsigned> InRangeOp;
3437 if (ParseGlobalValueVector(
3438 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003439 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3440 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003441
Chris Lattnerac161bf2009-01-02 07:01:27 +00003442 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003443 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003444 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003445 return Error(ID.Loc, "base of getelementptr must be a pointer");
3446
3447 Type *BaseType = Elts[0]->getType();
3448 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003449 if (Ty != BasePointerType->getElementType())
3450 return Error(
3451 ExplicitTypeLoc,
3452 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003453
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003454 unsigned GEPWidth =
3455 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3456
Jay Foaded8db7d2011-07-21 14:31:17 +00003457 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003458 for (Constant *Val : Indices) {
3459 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003460 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003461 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003462 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003463 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003464 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003465 return Error(
3466 ID.Loc,
3467 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003468 // GEPWidth may have been unknown because the base is a scalar,
3469 // but it is known now.
3470 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003471 }
3472 }
3473
Craig Toppere3dcce92015-08-01 22:20:21 +00003474 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003475 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003476 return Error(ID.Loc, "base element of getelementptr must be sized");
3477
David Blaikie4a2e73b2015-04-02 18:55:32 +00003478 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003479 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003480
3481 if (InRangeOp) {
3482 if (*InRangeOp == 0)
3483 return Error(ID.Loc,
3484 "inrange keyword may not appear on pointer operand");
3485 --*InRangeOp;
3486 }
3487
3488 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3489 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003490 } else if (Opc == Instruction::Select) {
3491 if (Elts.size() != 3)
3492 return Error(ID.Loc, "expected three operands to select");
3493 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3494 Elts[2]))
3495 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003496 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003497 } else if (Opc == Instruction::ShuffleVector) {
3498 if (Elts.size() != 3)
3499 return Error(ID.Loc, "expected three operands to shufflevector");
3500 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3501 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003502 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003503 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003504 } else if (Opc == Instruction::ExtractElement) {
3505 if (Elts.size() != 2)
3506 return Error(ID.Loc, "expected two operands to extractelement");
3507 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3508 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003509 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003510 } else {
3511 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3512 if (Elts.size() != 3)
3513 return Error(ID.Loc, "expected three operands to insertelement");
3514 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3515 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003516 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003517 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003518 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003519
Chris Lattnerac161bf2009-01-02 07:01:27 +00003520 ID.Kind = ValID::t_Constant;
3521 return false;
3522 }
3523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003524
Chris Lattnerac161bf2009-01-02 07:01:27 +00003525 Lex.Lex();
3526 return false;
3527}
3528
3529/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003530bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003531 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003532 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003533 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003534 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003535 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003536 if (V && !(C = dyn_cast<Constant>(V)))
3537 return Error(ID.Loc, "global values must be constants");
3538 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003539}
3540
Victor Hernandez9d75c962010-01-11 22:31:58 +00003541bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003542 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003543 return ParseType(Ty) ||
3544 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003545}
3546
Rafael Espindola83a362c2015-01-06 22:55:16 +00003547bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003548 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003549
3550 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003551 if (!EatIfPresent(lltok::kw_comdat))
3552 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003553
3554 if (EatIfPresent(lltok::lparen)) {
3555 if (Lex.getKind() != lltok::ComdatVar)
3556 return TokError("expected comdat variable");
3557 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3558 Lex.Lex();
3559 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3560 return true;
3561 } else {
3562 if (GlobalName.empty())
3563 return TokError("comdat cannot be unnamed");
3564 C = getComdat(GlobalName, KwLoc);
3565 }
3566
David Majnemerdad0a642014-06-27 18:19:56 +00003567 return false;
3568}
3569
Victor Hernandez9d75c962010-01-11 22:31:58 +00003570/// ParseGlobalValueVector
3571/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003572/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3573bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3574 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003575 // Empty list.
3576 if (Lex.getKind() == lltok::rbrace ||
3577 Lex.getKind() == lltok::rsquare ||
3578 Lex.getKind() == lltok::greater ||
3579 Lex.getKind() == lltok::rparen)
3580 return false;
3581
Peter Collingbourned93620b2016-11-10 22:34:55 +00003582 do {
3583 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3584 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003585
Peter Collingbourned93620b2016-11-10 22:34:55 +00003586 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003587 if (ParseGlobalTypeAndValue(C)) return true;
3588 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003589 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003590
3591 return false;
3592}
3593
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003594bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003595 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003596 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003597 return true;
3598
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003599 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003600 return false;
3601}
3602
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003603/// MDNode:
3604/// ::= !{ ... }
3605/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003606/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003607bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003608 if (Lex.getKind() == lltok::MetadataVar)
3609 return ParseSpecializedMDNode(N);
3610
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003611 return ParseToken(lltok::exclaim, "expected '!' here") ||
3612 ParseMDNodeTail(N);
3613}
3614
3615bool LLParser::ParseMDNodeTail(MDNode *&N) {
3616 // !{ ... }
3617 if (Lex.getKind() == lltok::lbrace)
3618 return ParseMDTuple(N);
3619
3620 // !42
3621 return ParseMDNodeID(N);
3622}
3623
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003624namespace {
3625
3626/// Structure to represent an optional metadata field.
3627template <class FieldTy> struct MDFieldImpl {
3628 typedef MDFieldImpl ImplTy;
3629 FieldTy Val;
3630 bool Seen;
3631
3632 void assign(FieldTy Val) {
3633 Seen = true;
3634 this->Val = std::move(Val);
3635 }
3636
3637 explicit MDFieldImpl(FieldTy Default)
3638 : Val(std::move(Default)), Seen(false) {}
3639};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003640
Sander de Smalenfdf40912018-01-24 09:56:07 +00003641/// Structure to represent an optional metadata field that
3642/// can be of either type (A or B) and encapsulates the
3643/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3644/// to reimplement the specifics for representing each Field.
3645template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3646 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3647 FieldTypeA A;
3648 FieldTypeB B;
3649 bool Seen;
3650
3651 enum {
3652 IsInvalid = 0,
3653 IsTypeA = 1,
3654 IsTypeB = 2
3655 } WhatIs;
3656
3657 void assign(FieldTypeA A) {
3658 Seen = true;
3659 this->A = std::move(A);
3660 WhatIs = IsTypeA;
3661 }
3662
3663 void assign(FieldTypeB B) {
3664 Seen = true;
3665 this->B = std::move(B);
3666 WhatIs = IsTypeB;
3667 }
3668
3669 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3670 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3671 WhatIs(IsInvalid) {}
3672};
3673
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003674struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3675 uint64_t Max;
3676
3677 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3678 : ImplTy(Default), Max(Max) {}
3679};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003680
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003681struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003682 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003683};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003684
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003685struct ColumnField : public MDUnsignedField {
3686 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3687};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003688
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003689struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003690 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003691 DwarfTagField(dwarf::Tag DefaultTag)
3692 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003693};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003694
Amjad Abouda9bcf162015-12-10 12:56:35 +00003695struct DwarfMacinfoTypeField : public MDUnsignedField {
3696 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3697 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3698 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3699};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003700
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003701struct DwarfAttEncodingField : public MDUnsignedField {
3702 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3703};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003704
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003705struct DwarfVirtualityField : public MDUnsignedField {
3706 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3707};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003708
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003709struct DwarfLangField : public MDUnsignedField {
3710 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3711};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003712
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003713struct DwarfCCField : public MDUnsignedField {
3714 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3715};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003716
Adrian Prantlb939a252016-03-31 23:56:58 +00003717struct EmissionKindField : public MDUnsignedField {
3718 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3719};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003720
David Blaikie66cf14d2018-08-16 21:29:55 +00003721struct NameTableKindField : public MDUnsignedField {
3722 NameTableKindField()
3723 : MDUnsignedField(
3724 0, (unsigned)
3725 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3726};
3727
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003728struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3729 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003730};
3731
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003732struct MDSignedField : public MDFieldImpl<int64_t> {
3733 int64_t Min;
3734 int64_t Max;
3735
3736 MDSignedField(int64_t Default = 0)
3737 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3738 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3739 : ImplTy(Default), Min(Min), Max(Max) {}
3740};
3741
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003742struct MDBoolField : public MDFieldImpl<bool> {
3743 MDBoolField(bool Default = false) : ImplTy(Default) {}
3744};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003745
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003746struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003747 bool AllowNull;
3748
3749 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003750};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003751
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003752struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3753 MDConstant() : ImplTy(nullptr) {}
3754};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003755
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003756struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003757 bool AllowEmpty;
3758 MDStringField(bool AllowEmpty = true)
3759 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003760};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003761
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003762struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3763 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3764};
3765
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003766struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003767 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3768};
3769
Sander de Smalenfdf40912018-01-24 09:56:07 +00003770struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3771 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3772 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3773
3774 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3775 bool AllowNull = true)
3776 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3777
3778 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3779 bool isMDField() const { return WhatIs == IsTypeB; }
3780 int64_t getMDSignedValue() const {
3781 assert(isMDSignedField() && "Wrong field type");
3782 return A.Val;
3783 }
3784 Metadata *getMDFieldValue() const {
3785 assert(isMDField() && "Wrong field type");
3786 return B.Val;
3787 }
3788};
3789
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003790struct MDSignedOrUnsignedField
3791 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3792 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3793
3794 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3795 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3796 int64_t getMDSignedValue() const {
3797 assert(isMDSignedField() && "Wrong field type");
3798 return A.Val;
3799 }
3800 uint64_t getMDUnsignedValue() const {
3801 assert(isMDUnsignedField() && "Wrong field type");
3802 return B.Val;
3803 }
3804};
3805
Eugene Zelenko1804a772016-08-25 00:45:04 +00003806} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003807
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003808namespace llvm {
3809
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003810template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003811bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003812 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003813 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3814 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003815
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003816 auto &U = Lex.getAPSIntVal();
3817 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003818 return TokError("value for '" + Name + "' too large, limit is " +
3819 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003820 Result.assign(U.getZExtValue());
3821 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003822 Lex.Lex();
3823 return false;
3824}
3825
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003826template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003827bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3828 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3829}
3830template <>
3831bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3832 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3833}
3834
3835template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003836bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3837 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003838 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003839
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003840 if (Lex.getKind() != lltok::DwarfTag)
3841 return TokError("expected DWARF tag");
3842
3843 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3844 if (Tag == dwarf::DW_TAG_invalid)
3845 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003846 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003847
3848 Result.assign(Tag);
3849 Lex.Lex();
3850 return false;
3851}
3852
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003853template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003854bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003855 DwarfMacinfoTypeField &Result) {
3856 if (Lex.getKind() == lltok::APSInt)
3857 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3858
3859 if (Lex.getKind() != lltok::DwarfMacinfo)
3860 return TokError("expected DWARF macinfo type");
3861
3862 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3863 if (Macinfo == dwarf::DW_MACINFO_invalid)
3864 return TokError(
3865 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3866 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3867
3868 Result.assign(Macinfo);
3869 Lex.Lex();
3870 return false;
3871}
3872
3873template <>
3874bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003875 DwarfVirtualityField &Result) {
3876 if (Lex.getKind() == lltok::APSInt)
3877 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3878
3879 if (Lex.getKind() != lltok::DwarfVirtuality)
3880 return TokError("expected DWARF virtuality code");
3881
3882 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003883 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003884 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3885 Lex.getStrVal() + "'");
3886 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3887 Result.assign(Virtuality);
3888 Lex.Lex();
3889 return false;
3890}
3891
3892template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003893bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3894 if (Lex.getKind() == lltok::APSInt)
3895 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3896
3897 if (Lex.getKind() != lltok::DwarfLang)
3898 return TokError("expected DWARF language");
3899
3900 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3901 if (!Lang)
3902 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3903 "'");
3904 assert(Lang <= Result.Max && "Expected valid DWARF language");
3905 Result.assign(Lang);
3906 Lex.Lex();
3907 return false;
3908}
3909
3910template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003911bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3912 if (Lex.getKind() == lltok::APSInt)
3913 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3914
3915 if (Lex.getKind() != lltok::DwarfCC)
3916 return TokError("expected DWARF calling convention");
3917
3918 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3919 if (!CC)
3920 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3921 "'");
3922 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3923 Result.assign(CC);
3924 Lex.Lex();
3925 return false;
3926}
3927
3928template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003929bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3930 if (Lex.getKind() == lltok::APSInt)
3931 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3932
3933 if (Lex.getKind() != lltok::EmissionKind)
3934 return TokError("expected emission kind");
3935
3936 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3937 if (!Kind)
3938 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3939 "'");
3940 assert(*Kind <= Result.Max && "Expected valid emission kind");
3941 Result.assign(*Kind);
3942 Lex.Lex();
3943 return false;
3944}
Fangrui Songf78650a2018-07-30 19:41:25 +00003945
Adrian Prantlb939a252016-03-31 23:56:58 +00003946template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003947bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikie66cf14d2018-08-16 21:29:55 +00003948 NameTableKindField &Result) {
3949 if (Lex.getKind() == lltok::APSInt)
3950 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3951
3952 if (Lex.getKind() != lltok::NameTableKind)
3953 return TokError("expected nameTable kind");
3954
3955 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3956 if (!Kind)
3957 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3958 "'");
3959 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3960 Result.assign((unsigned)*Kind);
3961 Lex.Lex();
3962 return false;
3963}
3964
3965template <>
3966bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003967 DwarfAttEncodingField &Result) {
3968 if (Lex.getKind() == lltok::APSInt)
3969 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3970
3971 if (Lex.getKind() != lltok::DwarfAttEncoding)
3972 return TokError("expected DWARF type attribute encoding");
3973
3974 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3975 if (!Encoding)
3976 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3977 Lex.getStrVal() + "'");
3978 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3979 Result.assign(Encoding);
3980 Lex.Lex();
3981 return false;
3982}
3983
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003984/// DIFlagField
3985/// ::= uint32
3986/// ::= DIFlagVector
3987/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3988template <>
3989bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003990
3991 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003992 auto parseFlag = [&](DINode::DIFlags &Val) {
3993 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3994 uint32_t TempVal = static_cast<uint32_t>(Val);
3995 bool Res = ParseUInt32(TempVal);
3996 Val = static_cast<DINode::DIFlags>(TempVal);
3997 return Res;
3998 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003999
4000 if (Lex.getKind() != lltok::DIFlag)
4001 return TokError("expected debug info flag");
4002
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004003 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004004 if (!Val)
4005 return TokError(Twine("invalid debug info flag flag '") +
4006 Lex.getStrVal() + "'");
4007 Lex.Lex();
4008 return false;
4009 };
4010
4011 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004012 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004013 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004014 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004015 if (parseFlag(Val))
4016 return true;
4017 Combined |= Val;
4018 } while (EatIfPresent(lltok::bar));
4019
4020 Result.assign(Combined);
4021 return false;
4022}
4023
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004024template <>
4025bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004026 MDSignedField &Result) {
4027 if (Lex.getKind() != lltok::APSInt)
4028 return TokError("expected signed integer");
4029
4030 auto &S = Lex.getAPSIntVal();
4031 if (S < Result.Min)
4032 return TokError("value for '" + Name + "' too small, limit is " +
4033 Twine(Result.Min));
4034 if (S > Result.Max)
4035 return TokError("value for '" + Name + "' too large, limit is " +
4036 Twine(Result.Max));
4037 Result.assign(S.getExtValue());
4038 assert(Result.Val >= Result.Min && "Expected value in range");
4039 assert(Result.Val <= Result.Max && "Expected value in range");
4040 Lex.Lex();
4041 return false;
4042}
4043
4044template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004045bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4046 switch (Lex.getKind()) {
4047 default:
4048 return TokError("expected 'true' or 'false'");
4049 case lltok::kw_true:
4050 Result.assign(true);
4051 break;
4052 case lltok::kw_false:
4053 Result.assign(false);
4054 break;
4055 }
4056 Lex.Lex();
4057 return false;
4058}
4059
4060template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004061bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004062 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004063 if (!Result.AllowNull)
4064 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004065 Lex.Lex();
4066 Result.assign(nullptr);
4067 return false;
4068 }
4069
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004070 Metadata *MD;
4071 if (ParseMetadata(MD, nullptr))
4072 return true;
4073
4074 Result.assign(MD);
4075 return false;
4076}
4077
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004078template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00004079bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4080 MDSignedOrMDField &Result) {
4081 // Try to parse a signed int.
4082 if (Lex.getKind() == lltok::APSInt) {
4083 MDSignedField Res = Result.A;
4084 if (!ParseMDField(Loc, Name, Res)) {
4085 Result.assign(Res);
4086 return false;
4087 }
4088 return true;
4089 }
4090
4091 // Otherwise, try to parse as an MDField.
4092 MDField Res = Result.B;
4093 if (!ParseMDField(Loc, Name, Res)) {
4094 Result.assign(Res);
4095 return false;
4096 }
4097
4098 return true;
4099}
4100
4101template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004102bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4103 MDSignedOrUnsignedField &Result) {
4104 if (Lex.getKind() != lltok::APSInt)
4105 return false;
4106
4107 if (Lex.getAPSIntVal().isSigned()) {
4108 MDSignedField Res = Result.A;
4109 if (ParseMDField(Loc, Name, Res))
4110 return true;
4111 Result.assign(Res);
4112 return false;
4113 }
4114
4115 MDUnsignedField Res = Result.B;
4116 if (ParseMDField(Loc, Name, Res))
4117 return true;
4118 Result.assign(Res);
4119 return false;
4120}
4121
4122template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004123bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004124 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004125 std::string S;
4126 if (ParseStringConstant(S))
4127 return true;
4128
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004129 if (!Result.AllowEmpty && S.empty())
4130 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4131
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004132 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004133 return false;
4134}
4135
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004136template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004137bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4138 SmallVector<Metadata *, 4> MDs;
4139 if (ParseMDNodeVector(MDs))
4140 return true;
4141
4142 Result.assign(std::move(MDs));
4143 return false;
4144}
4145
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004146template <>
4147bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4148 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004149 Optional<DIFile::ChecksumKind> CSKind =
4150 DIFile::getChecksumKind(Lex.getStrVal());
4151
4152 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004153 return TokError(
4154 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4155
Scott Linder71603842018-02-12 19:45:54 +00004156 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004157 Lex.Lex();
4158 return false;
4159}
4160
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004161} // end namespace llvm
4162
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004163template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004164bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004165 do {
4166 if (Lex.getKind() != lltok::LabelStr)
4167 return TokError("expected field label here");
4168
4169 if (parseField())
4170 return true;
4171 } while (EatIfPresent(lltok::comma));
4172
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004173 return false;
4174}
4175
4176template <class ParserTy>
4177bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4178 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4179 Lex.Lex();
4180
4181 if (ParseToken(lltok::lparen, "expected '(' here"))
4182 return true;
4183 if (Lex.getKind() != lltok::rparen)
4184 if (ParseMDFieldsImplBody(parseField))
4185 return true;
4186
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004187 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004188 return ParseToken(lltok::rparen, "expected ')' here");
4189}
4190
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004191template <class FieldTy>
4192bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4193 if (Result.Seen)
4194 return TokError("field '" + Name + "' cannot be specified more than once");
4195
4196 LocTy Loc = Lex.getLoc();
4197 Lex.Lex();
4198 return ParseMDField(Loc, Name, Result);
4199}
4200
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004201bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4202 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004203
4204#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004205 if (Lex.getStrVal() == #CLASS) \
4206 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004207#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004208
4209 return TokError("expected metadata type");
4210}
4211
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004212#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4213#define NOP_FIELD(NAME, TYPE, INIT)
4214#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4215 if (!NAME.Seen) \
4216 return Error(ClosingLoc, "missing required field '" #NAME "'");
4217#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004218 if (Lex.getStrVal() == #NAME) \
4219 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004220#define PARSE_MD_FIELDS() \
4221 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4222 do { \
4223 LocTy ClosingLoc; \
4224 if (ParseMDFieldsImpl([&]() -> bool { \
4225 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4226 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4227 }, ClosingLoc)) \
4228 return true; \
4229 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4230 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004231#define GET_OR_DISTINCT(CLASS, ARGS) \
4232 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004233
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004234/// ParseDILocationFields:
4235/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
4236bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004237#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004238 OPTIONAL(line, LineField, ); \
4239 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004240 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004241 OPTIONAL(inlinedAt, MDField, );
4242 PARSE_MD_FIELDS();
4243#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004244
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00004245 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004246 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004247 return false;
4248}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004249
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004250/// ParseGenericDINode:
4251/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4252bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004253#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004254 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004255 OPTIONAL(header, MDStringField, ); \
4256 OPTIONAL(operands, MDFieldList, );
4257 PARSE_MD_FIELDS();
4258#undef VISIT_MD_FIELDS
4259
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004260 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004261 (Context, tag.Val, header.Val, operands.Val));
4262 return false;
4263}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004264
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004265/// ParseDISubrange:
4266/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004267/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004268bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004269#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004270 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004271 OPTIONAL(lowerBound, MDSignedField, );
4272 PARSE_MD_FIELDS();
4273#undef VISIT_MD_FIELDS
4274
Sander de Smalenfdf40912018-01-24 09:56:07 +00004275 if (count.isMDSignedField())
4276 Result = GET_OR_DISTINCT(
4277 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4278 else if (count.isMDField())
4279 Result = GET_OR_DISTINCT(
4280 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4281 else
4282 return true;
4283
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004284 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004285}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004286
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004287/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004288/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004289bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004290#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004291 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004292 REQUIRED(value, MDSignedOrUnsignedField, ); \
4293 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004294 PARSE_MD_FIELDS();
4295#undef VISIT_MD_FIELDS
4296
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004297 if (isUnsigned.Val && value.isMDSignedField())
4298 return TokError("unsigned enumerator with negative value");
4299
4300 int64_t Value = value.isMDSignedField()
4301 ? value.getMDSignedValue()
4302 : static_cast<int64_t>(value.getMDUnsignedValue());
4303 Result =
4304 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4305
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004306 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004307}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004308
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004309/// ParseDIBasicType:
Adrian Prantl55f42622018-08-14 19:35:34 +00004310/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4311/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004312bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004313#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004314 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004315 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004316 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004317 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantl55f42622018-08-14 19:35:34 +00004318 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4319 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004320 PARSE_MD_FIELDS();
4321#undef VISIT_MD_FIELDS
4322
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004323 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantl55f42622018-08-14 19:35:34 +00004324 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004325 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004326}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004327
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004328/// ParseDIDerivedType:
4329/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004330/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004331/// align: 32, offset: 0, flags: 0, extraData: !3,
4332/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004333bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004334#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4335 REQUIRED(tag, DwarfTagField, ); \
4336 OPTIONAL(name, MDStringField, ); \
4337 OPTIONAL(file, MDField, ); \
4338 OPTIONAL(line, LineField, ); \
4339 OPTIONAL(scope, MDField, ); \
4340 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004341 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004342 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004343 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004344 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004345 OPTIONAL(extraData, MDField, ); \
4346 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004347 PARSE_MD_FIELDS();
4348#undef VISIT_MD_FIELDS
4349
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004350 Optional<unsigned> DWARFAddressSpace;
4351 if (dwarfAddressSpace.Val != UINT32_MAX)
4352 DWARFAddressSpace = dwarfAddressSpace.Val;
4353
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004354 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004355 (Context, tag.Val, name.Val, file.Val, line.Val,
4356 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004357 offset.Val, DWARFAddressSpace, flags.Val,
4358 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004359 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004360}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004361
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004362bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004363#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4364 REQUIRED(tag, DwarfTagField, ); \
4365 OPTIONAL(name, MDStringField, ); \
4366 OPTIONAL(file, MDField, ); \
4367 OPTIONAL(line, LineField, ); \
4368 OPTIONAL(scope, MDField, ); \
4369 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004370 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004371 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004372 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004373 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004374 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004375 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004376 OPTIONAL(vtableHolder, MDField, ); \
4377 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004378 OPTIONAL(identifier, MDStringField, ); \
4379 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004380 PARSE_MD_FIELDS();
4381#undef VISIT_MD_FIELDS
4382
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004383 // If this has an identifier try to build an ODR type.
4384 if (identifier.Val)
4385 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004386 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4387 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4388 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004389 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004390 Result = CT;
4391 return false;
4392 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004393
4394 // Create a new node, and save it in the context if it belongs in the type
4395 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004396 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004397 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004398 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4399 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004400 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4401 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004402 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004403}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004404
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004405bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004406#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004407 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004408 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004409 REQUIRED(types, MDField, );
4410 PARSE_MD_FIELDS();
4411#undef VISIT_MD_FIELDS
4412
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004413 Result = GET_OR_DISTINCT(DISubroutineType,
4414 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004415 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004416}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004417
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004418/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004419/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004420/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004421/// checksum: "000102030405060708090a0b0c0d0e0f",
4422/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004423bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004424 // The default constructed value for checksumkind is required, but will never
4425 // be used, as the parser checks if the field was actually Seen before using
4426 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004427#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4428 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004429 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004430 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004431 OPTIONAL(checksum, MDStringField, ); \
4432 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004433 PARSE_MD_FIELDS();
4434#undef VISIT_MD_FIELDS
4435
Scott Linder71603842018-02-12 19:45:54 +00004436 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4437 if (checksumkind.Seen && checksum.Seen)
4438 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4439 else if (checksumkind.Seen || checksum.Seen)
4440 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4441
Scott Linder16c7bda2018-02-23 23:01:06 +00004442 Optional<MDString *> OptSource;
4443 if (source.Seen)
4444 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004445 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004446 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004447 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004448}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004449
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004450/// ParseDICompileUnit:
4451/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004452/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004453/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004454/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004455/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004456bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004457 if (!IsDistinct)
4458 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4459
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004460#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4461 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004462 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004463 OPTIONAL(producer, MDStringField, ); \
4464 OPTIONAL(isOptimized, MDBoolField, ); \
4465 OPTIONAL(flags, MDStringField, ); \
4466 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4467 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004468 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004469 OPTIONAL(enums, MDField, ); \
4470 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004471 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004472 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004473 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004474 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004475 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004476 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikie66cf14d2018-08-16 21:29:55 +00004477 OPTIONAL(nameTableKind, NameTableKindField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004478 PARSE_MD_FIELDS();
4479#undef VISIT_MD_FIELDS
4480
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004481 Result = DICompileUnit::getDistinct(
4482 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4483 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004484 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikie66cf14d2018-08-16 21:29:55 +00004485 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004486 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004487}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004488
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004489/// ParseDISubprogram:
4490/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004491/// file: !1, line: 7, type: !2, isLocal: false,
4492/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004493/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004494/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004495/// isOptimized: false, templateParams: !4, declaration: !5,
Shiva Chen2c864552018-05-09 02:40:45 +00004496/// retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004497bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004498 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004499#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4500 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004501 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004502 OPTIONAL(linkageName, MDStringField, ); \
4503 OPTIONAL(file, MDField, ); \
4504 OPTIONAL(line, LineField, ); \
4505 OPTIONAL(type, MDField, ); \
4506 OPTIONAL(isLocal, MDBoolField, ); \
4507 OPTIONAL(isDefinition, MDBoolField, (true)); \
4508 OPTIONAL(scopeLine, LineField, ); \
4509 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004510 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004511 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004512 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004513 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004514 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004515 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004516 OPTIONAL(templateParams, MDField, ); \
4517 OPTIONAL(declaration, MDField, ); \
Shiva Chen2c864552018-05-09 02:40:45 +00004518 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004519 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004520 PARSE_MD_FIELDS();
4521#undef VISIT_MD_FIELDS
4522
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004523 if (isDefinition.Val && !IsDistinct)
4524 return Lex.Error(
4525 Loc,
4526 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4527
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004528 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004529 DISubprogram,
4530 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4531 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4532 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4533 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004534 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004535 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004536}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004537
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004538/// ParseDILexicalBlock:
4539/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4540bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004541#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004542 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004543 OPTIONAL(file, MDField, ); \
4544 OPTIONAL(line, LineField, ); \
4545 OPTIONAL(column, ColumnField, );
4546 PARSE_MD_FIELDS();
4547#undef VISIT_MD_FIELDS
4548
4549 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004550 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004551 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004552}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004553
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004554/// ParseDILexicalBlockFile:
4555/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4556bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004557#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004558 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004559 OPTIONAL(file, MDField, ); \
4560 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4561 PARSE_MD_FIELDS();
4562#undef VISIT_MD_FIELDS
4563
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004564 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004565 (Context, scope.Val, file.Val, discriminator.Val));
4566 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004567}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004568
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004569/// ParseDINamespace:
4570/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4571bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004572#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4573 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004574 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004575 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004576 PARSE_MD_FIELDS();
4577#undef VISIT_MD_FIELDS
4578
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004579 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004580 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004581 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004582}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004583
Amjad Abouda9bcf162015-12-10 12:56:35 +00004584/// ParseDIMacro:
4585/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4586bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4587#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4588 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004589 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004590 REQUIRED(name, MDStringField, ); \
4591 OPTIONAL(value, MDStringField, );
4592 PARSE_MD_FIELDS();
4593#undef VISIT_MD_FIELDS
4594
4595 Result = GET_OR_DISTINCT(DIMacro,
4596 (Context, type.Val, line.Val, name.Val, value.Val));
4597 return false;
4598}
4599
4600/// ParseDIMacroFile:
4601/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4602bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4603#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4604 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004605 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004606 REQUIRED(file, MDField, ); \
4607 OPTIONAL(nodes, MDField, );
4608 PARSE_MD_FIELDS();
4609#undef VISIT_MD_FIELDS
4610
4611 Result = GET_OR_DISTINCT(DIMacroFile,
4612 (Context, type.Val, line.Val, file.Val, nodes.Val));
4613 return false;
4614}
4615
Adrian Prantlab1243f2015-06-29 23:03:47 +00004616/// ParseDIModule:
4617/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4618/// includePath: "/usr/include", isysroot: "/")
4619bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4620#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4621 REQUIRED(scope, MDField, ); \
4622 REQUIRED(name, MDStringField, ); \
4623 OPTIONAL(configMacros, MDStringField, ); \
4624 OPTIONAL(includePath, MDStringField, ); \
4625 OPTIONAL(isysroot, MDStringField, );
4626 PARSE_MD_FIELDS();
4627#undef VISIT_MD_FIELDS
4628
4629 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4630 configMacros.Val, includePath.Val, isysroot.Val));
4631 return false;
4632}
4633
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004634/// ParseDITemplateTypeParameter:
4635/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4636bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004637#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004638 OPTIONAL(name, MDStringField, ); \
4639 REQUIRED(type, MDField, );
4640 PARSE_MD_FIELDS();
4641#undef VISIT_MD_FIELDS
4642
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004643 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004644 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004645 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004646}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004647
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004648/// ParseDITemplateValueParameter:
4649/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004650/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004651bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004652#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004653 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004654 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004655 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004656 REQUIRED(value, MDField, );
4657 PARSE_MD_FIELDS();
4658#undef VISIT_MD_FIELDS
4659
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004660 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004661 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004662 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004663}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004664
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004665/// ParseDIGlobalVariable:
4666/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004667/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004668/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004669bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004670#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004671 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004672 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004673 OPTIONAL(linkageName, MDStringField, ); \
4674 OPTIONAL(file, MDField, ); \
4675 OPTIONAL(line, LineField, ); \
4676 OPTIONAL(type, MDField, ); \
4677 OPTIONAL(isLocal, MDBoolField, ); \
4678 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004679 OPTIONAL(declaration, MDField, ); \
4680 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004681 PARSE_MD_FIELDS();
4682#undef VISIT_MD_FIELDS
4683
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004684 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004685 (Context, scope.Val, name.Val, linkageName.Val,
4686 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004687 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004688 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004689}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004690
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004691/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004692/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004693/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4694/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004695/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004696/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4697/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004698bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004699#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004700 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004701 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004702 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004703 OPTIONAL(file, MDField, ); \
4704 OPTIONAL(line, LineField, ); \
4705 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004706 OPTIONAL(flags, DIFlagField, ); \
4707 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004708 PARSE_MD_FIELDS();
4709#undef VISIT_MD_FIELDS
4710
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004711 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004712 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004713 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004714 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004715}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004716
Shiva Chen2c864552018-05-09 02:40:45 +00004717/// ParseDILabel:
4718/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4719bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4720#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4721 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4722 REQUIRED(name, MDStringField, ); \
4723 REQUIRED(file, MDField, ); \
4724 REQUIRED(line, LineField, );
4725 PARSE_MD_FIELDS();
4726#undef VISIT_MD_FIELDS
4727
4728 Result = GET_OR_DISTINCT(DILabel,
4729 (Context, scope.Val, name.Val, file.Val, line.Val));
4730 return false;
4731}
4732
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004733/// ParseDIExpression:
4734/// ::= !DIExpression(0, 7, -1)
4735bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004736 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4737 Lex.Lex();
4738
4739 if (ParseToken(lltok::lparen, "expected '(' here"))
4740 return true;
4741
4742 SmallVector<uint64_t, 8> Elements;
4743 if (Lex.getKind() != lltok::rparen)
4744 do {
4745 if (Lex.getKind() == lltok::DwarfOp) {
4746 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4747 Lex.Lex();
4748 Elements.push_back(Op);
4749 continue;
4750 }
4751 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4752 }
4753
4754 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4755 return TokError("expected unsigned integer");
4756
4757 auto &U = Lex.getAPSIntVal();
4758 if (U.ugt(UINT64_MAX))
4759 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4760 Elements.push_back(U.getZExtValue());
4761 Lex.Lex();
4762 } while (EatIfPresent(lltok::comma));
4763
4764 if (ParseToken(lltok::rparen, "expected ')' here"))
4765 return true;
4766
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004767 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004768 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004769}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004770
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004771/// ParseDIGlobalVariableExpression:
4772/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4773bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4774 bool IsDistinct) {
4775#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4776 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004777 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004778 PARSE_MD_FIELDS();
4779#undef VISIT_MD_FIELDS
4780
4781 Result =
4782 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4783 return false;
4784}
4785
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004786/// ParseDIObjCProperty:
4787/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004788/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004789bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004790#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004791 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004792 OPTIONAL(file, MDField, ); \
4793 OPTIONAL(line, LineField, ); \
4794 OPTIONAL(setter, MDStringField, ); \
4795 OPTIONAL(getter, MDStringField, ); \
4796 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4797 OPTIONAL(type, MDField, );
4798 PARSE_MD_FIELDS();
4799#undef VISIT_MD_FIELDS
4800
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004801 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004802 (Context, name.Val, file.Val, line.Val, setter.Val,
4803 getter.Val, attributes.Val, type.Val));
4804 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004805}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004806
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004807/// ParseDIImportedEntity:
4808/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004809/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004810bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004811#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4812 REQUIRED(tag, DwarfTagField, ); \
4813 REQUIRED(scope, MDField, ); \
4814 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004815 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004816 OPTIONAL(line, LineField, ); \
4817 OPTIONAL(name, MDStringField, );
4818 PARSE_MD_FIELDS();
4819#undef VISIT_MD_FIELDS
4820
Adrian Prantld63bfd22017-07-19 00:09:54 +00004821 Result = GET_OR_DISTINCT(
4822 DIImportedEntity,
4823 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004824 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004825}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004826
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004827#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004828#undef NOP_FIELD
4829#undef REQUIRE_FIELD
4830#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004831
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004832/// ParseMetadataAsValue
4833/// ::= metadata i32 %local
4834/// ::= metadata i32 @global
4835/// ::= metadata i32 7
4836/// ::= metadata !0
4837/// ::= metadata !{...}
4838/// ::= metadata !"string"
4839bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4840 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004841 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004842 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004843 return true;
4844
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004845 V = MetadataAsValue::get(Context, MD);
4846 return false;
4847}
4848
4849/// ParseValueAsMetadata
4850/// ::= i32 %local
4851/// ::= i32 @global
4852/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004853bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4854 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004855 Type *Ty;
4856 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004857 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004858 return true;
4859 if (Ty->isMetadataTy())
4860 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4861
4862 Value *V;
4863 if (ParseValue(Ty, V, PFS))
4864 return true;
4865
4866 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004867 return false;
4868}
4869
4870/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004871/// ::= i32 %local
4872/// ::= i32 @global
4873/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004874/// ::= !42
4875/// ::= !{...}
4876/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004877/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004878bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004879 if (Lex.getKind() == lltok::MetadataVar) {
4880 MDNode *N;
4881 if (ParseSpecializedMDNode(N))
4882 return true;
4883 MD = N;
4884 return false;
4885 }
4886
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004887 // ValueAsMetadata:
4888 // <type> <value>
4889 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004890 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004891
4892 // '!'.
4893 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4894 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004895
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004896 // MDString:
4897 // ::= '!' STRINGCONSTANT
4898 if (Lex.getKind() == lltok::StringConstant) {
4899 MDString *S;
4900 if (ParseMDString(S))
4901 return true;
4902 MD = S;
4903 return false;
4904 }
4905
Dan Gohman8939ba332010-07-14 18:26:50 +00004906 // MDNode:
4907 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004908 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004909 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004910 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004911 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004912 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004913 return false;
4914}
4915
Victor Hernandez9d75c962010-01-11 22:31:58 +00004916//===----------------------------------------------------------------------===//
4917// Function Parsing.
4918//===----------------------------------------------------------------------===//
4919
Chris Lattner229907c2011-07-18 04:54:35 +00004920bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004921 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004922 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004923 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004924
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004926 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004927 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004928 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004929 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004930 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004931 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004932 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004933 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004934 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004935 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004936 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004937 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4938 (ID.UIntVal >> 1) & 1,
4939 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004940 return false;
4941 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004942 case ValID::t_GlobalName:
4943 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004944 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004945 case ValID::t_GlobalID:
4946 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004947 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004949 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004951 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004952 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004953 return false;
4954 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004955 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4957 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004958
Dan Gohman518cda42011-12-17 00:04:22 +00004959 // The lexer has no type info, so builds all half, float, and double FP
4960 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004961 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004963 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004964 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004965 &Ignored);
4966 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004967 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004968 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004969 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004970 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004971
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004972 if (V->getType() != Ty)
4973 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004974 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004975
Chris Lattnerac161bf2009-01-02 07:01:27 +00004976 return false;
4977 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004978 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004980 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004981 return false;
4982 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004983 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004984 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004985 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004986 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004987 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004988 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004989 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004990 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004991 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004992 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004993 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004994 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004995 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004996 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004997 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004999 case ValID::t_None:
5000 if (!Ty->isTokenTy())
5001 return Error(ID.Loc, "invalid type for none constant");
5002 V = Constant::getNullValue(Ty);
5003 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005004 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00005005 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00005007
Chris Lattnerac161bf2009-01-02 07:01:27 +00005008 V = ID.ConstantVal;
5009 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005010 case ValID::t_ConstantStruct:
5011 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00005012 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005013 if (ST->getNumElements() != ID.UIntVal)
5014 return Error(ID.Loc,
5015 "initializer with struct type has wrong # elements");
5016 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5017 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005018
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005019 // Verify that the elements are compatible with the structtype.
5020 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5021 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5022 return Error(ID.Loc, "element " + Twine(i) +
5023 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005024
David Blaikieadbda4b2015-08-03 20:08:41 +00005025 V = ConstantStruct::get(
5026 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005027 } else
5028 return Error(ID.Loc, "constant expression type mismatch");
5029 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005030 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00005031 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005033
Alex Lorenzd2255952015-07-17 22:07:03 +00005034bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5035 C = nullptr;
5036 ValID ID;
5037 auto Loc = Lex.getLoc();
5038 if (ParseValID(ID, /*PFS=*/nullptr))
5039 return true;
5040 switch (ID.Kind) {
5041 case ValID::t_APSInt:
5042 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00005043 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00005044 case ValID::t_Constant:
5045 case ValID::t_ConstantStruct:
5046 case ValID::t_PackedConstantStruct: {
5047 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005048 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00005049 return true;
5050 assert(isa<Constant>(V) && "Expected a constant value");
5051 C = cast<Constant>(V);
5052 return false;
5053 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00005054 case ValID::t_Null:
5055 C = Constant::getNullValue(Ty);
5056 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00005057 default:
5058 return Error(Loc, "expected a constant value");
5059 }
5060}
5061
David Majnemer8a1c45d2015-12-12 05:38:55 +00005062bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005063 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005065 return ParseValID(ID, PFS) ||
5066 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005067}
5068
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005069bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005070 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005071 return ParseType(Ty) ||
5072 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005073}
5074
Chris Lattner3ed871f2009-10-27 19:13:16 +00005075bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5076 PerFunctionState &PFS) {
5077 Value *V;
5078 Loc = Lex.getLoc();
5079 if (ParseTypeAndValue(V, PFS)) return true;
5080 if (!isa<BasicBlock>(V))
5081 return Error(Loc, "expected a basic block");
5082 BB = cast<BasicBlock>(V);
5083 return false;
5084}
5085
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00005087/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5088/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5089/// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
5090/// OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00005091bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5092 // Parse the linkage.
5093 LocTy LinkageLoc = Lex.getLoc();
5094 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005095 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005096 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005097 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005098 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005099 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005100 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005101 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005102 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005103 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5104 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005105 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005106 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107 return true;
5108
5109 // Verify that the linkage is ok.
5110 switch ((GlobalValue::LinkageTypes)Linkage) {
5111 case GlobalValue::ExternalLinkage:
5112 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005113 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 if (isDefine)
5115 return Error(LinkageLoc, "invalid linkage for function definition");
5116 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005117 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005118 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005119 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005120 case GlobalValue::LinkOnceAnyLinkage:
5121 case GlobalValue::LinkOnceODRLinkage:
5122 case GlobalValue::WeakAnyLinkage:
5123 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005124 if (!isDefine)
5125 return Error(LinkageLoc, "invalid linkage for function declaration");
5126 break;
5127 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005128 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 return Error(LinkageLoc, "invalid function linkage type");
5130 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005132 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5133 return Error(LinkageLoc,
5134 "symbol with local linkage must have default visibility");
5135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005136 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005138
Chris Lattnerac161bf2009-01-02 07:01:27 +00005139 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005140
5141 std::string FunctionName;
5142 if (Lex.getKind() == lltok::GlobalVar) {
5143 FunctionName = Lex.getStrVal();
5144 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5145 unsigned NameID = Lex.getUIntVal();
5146
5147 if (NameID != NumberedVals.size())
5148 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005149 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005150 } else {
5151 return TokError("expected function name");
5152 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005153
Chris Lattner3822f632009-01-02 08:05:26 +00005154 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005155
Chris Lattner3822f632009-01-02 08:05:26 +00005156 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005157 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005158
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005159 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005161 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005162 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005163 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005164 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005165 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005166 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005167 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Craig Topper2617dcc2014-04-15 06:32:26 +00005168 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005169 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005170 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005171 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005172
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005173 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005174 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005175 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005176 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005177 (EatIfPresent(lltok::kw_section) &&
5178 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005179 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005180 ParseOptionalAlignment(Alignment) ||
5181 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005182 ParseStringConstant(GC)) ||
5183 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005184 ParseGlobalTypeAndValue(Prefix)) ||
5185 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005186 ParseGlobalTypeAndValue(Prologue)) ||
5187 (EatIfPresent(lltok::kw_personality) &&
5188 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005189 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190
Michael Gottesman41748d72013-06-27 00:25:01 +00005191 if (FuncAttrs.contains(Attribute::Builtin))
5192 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005193
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005195 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005196 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005197 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005198 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005199
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200 // Okay, if we got here, the function is syntactically valid. Convert types
5201 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005202 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005203 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005204
Chris Lattnerac161bf2009-01-02 07:01:27 +00005205 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005206 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005207 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 }
5209
Reid Kleckner7f720332017-04-13 00:58:09 +00005210 AttributeList PAL =
5211 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5212 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005213
Bill Wendling749a43d2012-12-30 13:50:49 +00005214 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005215 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5216
Chris Lattner229907c2011-07-18 04:54:35 +00005217 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005218 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00005219 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220
Craig Topper2617dcc2014-04-15 06:32:26 +00005221 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005222 if (!FunctionName.empty()) {
5223 // If this was a definition of a forward reference, remove the definition
5224 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005225 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005226 if (FRVI != ForwardRefVals.end()) {
5227 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005228 if (!Fn)
5229 return Error(FRVI->second.second, "invalid forward reference to "
5230 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005231 if (Fn->getType() != PFT)
5232 return Error(FRVI->second.second, "invalid forward reference to "
5233 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005234
Chris Lattnerac161bf2009-01-02 07:01:27 +00005235 ForwardRefVals.erase(FRVI);
5236 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005237 // Reject redefinitions.
5238 return Error(NameLoc, "invalid redefinition of function '" +
5239 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005240 } else if (M->getNamedValue(FunctionName)) {
5241 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005243
Dan Gohman399d6ae2009-08-29 23:37:49 +00005244 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 // If this is a definition of a forward referenced function, make sure the
5246 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005247 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 if (I != ForwardRefValIDs.end()) {
5249 Fn = cast<Function>(I->second.first);
5250 if (Fn->getType() != PFT)
5251 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005252 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005253 ForwardRefValIDs.erase(I);
5254 }
5255 }
5256
Craig Topper2617dcc2014-04-15 06:32:26 +00005257 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005258 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
5259 else // Move the forward-reference to the correct spot in the module.
5260 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5261
5262 if (FunctionName.empty())
5263 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005264
Chris Lattnerac161bf2009-01-02 07:01:27 +00005265 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005266 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005267 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005268 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269 Fn->setCallingConv(CC);
5270 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005271 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272 Fn->setAlignment(Alignment);
5273 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005274 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005275 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005276 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005277 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005278 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005279 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005280
Chris Lattnerac161bf2009-01-02 07:01:27 +00005281 // Add all of the arguments we parsed to the function.
5282 Function::arg_iterator ArgIt = Fn->arg_begin();
5283 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5284 // If the argument has a name, insert it into the argument symbol table.
5285 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005286
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 // Set the name, if it conflicted, it will be auto-renamed.
5288 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005289
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005290 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005291 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5292 ArgList[i].Name + "'");
5293 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005294
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005295 if (isDefine)
5296 return false;
5297
Robin Morisset039781e2014-08-29 21:53:01 +00005298 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005299 ValID ID;
5300 if (FunctionName.empty()) {
5301 ID.Kind = ValID::t_GlobalID;
5302 ID.UIntVal = NumberedVals.size() - 1;
5303 } else {
5304 ID.Kind = ValID::t_GlobalName;
5305 ID.StrVal = FunctionName;
5306 }
5307 auto Blocks = ForwardRefBlockAddresses.find(ID);
5308 if (Blocks != ForwardRefBlockAddresses.end())
5309 return Error(Blocks->first.Loc,
5310 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005311 return false;
5312}
5313
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005314bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5315 ValID ID;
5316 if (FunctionNumber == -1) {
5317 ID.Kind = ValID::t_GlobalName;
5318 ID.StrVal = F.getName();
5319 } else {
5320 ID.Kind = ValID::t_GlobalID;
5321 ID.UIntVal = FunctionNumber;
5322 }
5323
5324 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5325 if (Blocks == P.ForwardRefBlockAddresses.end())
5326 return false;
5327
5328 for (const auto &I : Blocks->second) {
5329 const ValID &BBID = I.first;
5330 GlobalValue *GV = I.second;
5331
5332 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5333 "Expected local id or name");
5334 BasicBlock *BB;
5335 if (BBID.Kind == ValID::t_LocalName)
5336 BB = GetBB(BBID.StrVal, BBID.Loc);
5337 else
5338 BB = GetBB(BBID.UIntVal, BBID.Loc);
5339 if (!BB)
5340 return P.Error(BBID.Loc, "referenced value is not a basic block");
5341
5342 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5343 GV->eraseFromParent();
5344 }
5345
5346 P.ForwardRefBlockAddresses.erase(Blocks);
5347 return false;
5348}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005349
5350/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005351/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005352bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005353 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005354 return TokError("expected '{' in function body");
5355 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005356
Chris Lattner3432c622009-10-28 03:39:23 +00005357 int FunctionNumber = -1;
5358 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005359
Chris Lattner3432c622009-10-28 03:39:23 +00005360 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005361
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005362 // Resolve block addresses and allow basic blocks to be forward-declared
5363 // within this function.
5364 if (PFS.resolveForwardRefBlockAddresses())
5365 return true;
5366 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5367
Chris Lattnerbbddd962010-01-09 19:20:07 +00005368 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005369 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005370 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005371
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005372 while (Lex.getKind() != lltok::rbrace &&
5373 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005374 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005375
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005376 while (Lex.getKind() != lltok::rbrace)
5377 if (ParseUseListOrder(&PFS))
5378 return true;
5379
Chris Lattnerac161bf2009-01-02 07:01:27 +00005380 // Eat the }.
5381 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005382
Chris Lattnerac161bf2009-01-02 07:01:27 +00005383 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005384 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385}
5386
5387/// ParseBasicBlock
5388/// ::= LabelStr? Instruction*
5389bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5390 // If this basic block starts out with a name, remember it.
5391 std::string Name;
5392 LocTy NameLoc = Lex.getLoc();
5393 if (Lex.getKind() == lltok::LabelStr) {
5394 Name = Lex.getStrVal();
5395 Lex.Lex();
5396 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005397
Chris Lattnerac161bf2009-01-02 07:01:27 +00005398 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005399 if (!BB)
5400 return Error(NameLoc,
5401 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005402
Chris Lattnerac161bf2009-01-02 07:01:27 +00005403 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005404
Chris Lattnerac161bf2009-01-02 07:01:27 +00005405 // Parse the instructions in this block until we get a terminator.
5406 Instruction *Inst;
5407 do {
5408 // This instruction may have three possibilities for a name: a) none
5409 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5410 LocTy NameLoc = Lex.getLoc();
5411 int NameID = -1;
5412 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005413
Chris Lattnerac161bf2009-01-02 07:01:27 +00005414 if (Lex.getKind() == lltok::LocalVarID) {
5415 NameID = Lex.getUIntVal();
5416 Lex.Lex();
5417 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5418 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005419 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420 NameStr = Lex.getStrVal();
5421 Lex.Lex();
5422 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5423 return true;
5424 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005425
Chris Lattner77b89dc2009-12-30 05:23:43 +00005426 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005427 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005428 case InstError: return true;
5429 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005430 BB->getInstList().push_back(Inst);
5431
Chris Lattner77b89dc2009-12-30 05:23:43 +00005432 // With a normal result, we check to see if the instruction is followed by
5433 // a comma and metadata.
5434 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005435 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005436 return true;
5437 break;
5438 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005439 BB->getInstList().push_back(Inst);
5440
Chris Lattner77b89dc2009-12-30 05:23:43 +00005441 // If the instruction parser ate an extra comma at the end of it, it
5442 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005443 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005444 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005445 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005446 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005447
Chris Lattnerac161bf2009-01-02 07:01:27 +00005448 // Set the name on the instruction.
5449 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5450 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005451
Chris Lattnerac161bf2009-01-02 07:01:27 +00005452 return false;
5453}
5454
5455//===----------------------------------------------------------------------===//
5456// Instruction Parsing.
5457//===----------------------------------------------------------------------===//
5458
5459/// ParseInstruction - Parse one of the many different instructions.
5460///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005461int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5462 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005463 lltok::Kind Token = Lex.getKind();
5464 if (Token == lltok::Eof)
5465 return TokError("found end of file when expecting more instructions");
5466 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005467 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005468 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005469
Chris Lattnerac161bf2009-01-02 07:01:27 +00005470 switch (Token) {
5471 default: return Error(Loc, "expected instruction opcode");
5472 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005473 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005474 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5475 case lltok::kw_br: return ParseBr(Inst, PFS);
5476 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005477 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005478 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005479 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005480 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5481 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005482 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5483 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005484 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005485 // Binary Operators.
5486 case lltok::kw_add:
5487 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005488 case lltok::kw_mul:
5489 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005490 bool NUW = EatIfPresent(lltok::kw_nuw);
5491 bool NSW = EatIfPresent(lltok::kw_nsw);
5492 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005493
Chris Lattnera676c0f2011-02-07 16:40:21 +00005494 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005495
Chris Lattnera676c0f2011-02-07 16:40:21 +00005496 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5497 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5498 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005499 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005500 case lltok::kw_fadd:
5501 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005502 case lltok::kw_fmul:
5503 case lltok::kw_fdiv:
5504 case lltok::kw_frem: {
5505 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5506 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5507 if (Res != 0)
5508 return Res;
5509 if (FMF.any())
5510 Inst->setFastMathFlags(FMF);
5511 return 0;
5512 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005513
Chris Lattner35315d02011-02-06 21:44:57 +00005514 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005515 case lltok::kw_udiv:
5516 case lltok::kw_lshr:
5517 case lltok::kw_ashr: {
5518 bool Exact = EatIfPresent(lltok::kw_exact);
5519
5520 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5521 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5522 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005523 }
5524
Chris Lattnerac161bf2009-01-02 07:01:27 +00005525 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005526 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005527 case lltok::kw_and:
5528 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005529 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005530 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5531 case lltok::kw_fcmp: {
5532 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5533 int Res = ParseCompare(Inst, PFS, KeywordVal);
5534 if (Res != 0)
5535 return Res;
5536 if (FMF.any())
5537 Inst->setFastMathFlags(FMF);
5538 return 0;
5539 }
5540
Chris Lattnerac161bf2009-01-02 07:01:27 +00005541 // Casts.
5542 case lltok::kw_trunc:
5543 case lltok::kw_zext:
5544 case lltok::kw_sext:
5545 case lltok::kw_fptrunc:
5546 case lltok::kw_fpext:
5547 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005548 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 case lltok::kw_uitofp:
5550 case lltok::kw_sitofp:
5551 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005552 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005554 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005555 // Other.
5556 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005557 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5559 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5560 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5561 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005562 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005563 // Call.
5564 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5565 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5566 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005567 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005568 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005569 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005570 case lltok::kw_load: return ParseLoad(Inst, PFS);
5571 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005572 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5573 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005574 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005575 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5576 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5577 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5578 }
5579}
5580
5581/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5582bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005583 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005584 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005585 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005586 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5587 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5588 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5589 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5590 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5591 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5592 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5593 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5594 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5595 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5596 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5597 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5598 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5599 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5600 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5601 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5602 }
5603 } else {
5604 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005605 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005606 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5607 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5608 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5609 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5610 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5611 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5612 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5613 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5614 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5615 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5616 }
5617 }
5618 Lex.Lex();
5619 return false;
5620}
5621
5622//===----------------------------------------------------------------------===//
5623// Terminator Instructions.
5624//===----------------------------------------------------------------------===//
5625
5626/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005627/// ::= 'ret' void (',' !dbg, !1)*
5628/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005629bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005630 PerFunctionState &PFS) {
5631 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005632 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005633 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005634
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005635 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005636
Chris Lattnerfdd87902009-10-05 05:54:46 +00005637 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005638 if (!ResType->isVoidTy())
5639 return Error(TypeLoc, "value doesn't match function result type '" +
5640 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005641
Owen Anderson55f1c092009-08-13 21:58:54 +00005642 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005643 return false;
5644 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005645
Chris Lattnerac161bf2009-01-02 07:01:27 +00005646 Value *RV;
5647 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005649 if (ResType != RV->getType())
5650 return Error(TypeLoc, "value doesn't match function result type '" +
5651 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005652
Owen Anderson55f1c092009-08-13 21:58:54 +00005653 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005654 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655}
5656
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657/// ParseBr
5658/// ::= 'br' TypeAndValue
5659/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5660bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5661 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005662 Value *Op0;
5663 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005665
Chris Lattnerac161bf2009-01-02 07:01:27 +00005666 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5667 Inst = BranchInst::Create(BB);
5668 return false;
5669 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005670
Owen Anderson55f1c092009-08-13 21:58:54 +00005671 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005672 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005673
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005675 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005676 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005677 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005679
Chris Lattner3ed871f2009-10-27 19:13:16 +00005680 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005681 return false;
5682}
5683
5684/// ParseSwitch
5685/// Instruction
5686/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5687/// JumpTable
5688/// ::= (TypeAndValue ',' TypeAndValue)*
5689bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5690 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005691 Value *Cond;
5692 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5694 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005695 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005696 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5697 return true;
5698
Duncan Sands19d0b472010-02-16 11:11:14 +00005699 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005701
Chris Lattnerac161bf2009-01-02 07:01:27 +00005702 // Parse the jump table pairs.
5703 SmallPtrSet<Value*, 32> SeenCases;
5704 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5705 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005706 Value *Constant;
5707 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005708
Chris Lattnerac161bf2009-01-02 07:01:27 +00005709 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5710 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005711 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005713
David Blaikie70573dc2014-11-19 07:49:26 +00005714 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 return Error(CondLoc, "duplicate case value in switch");
5716 if (!isa<ConstantInt>(Constant))
5717 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005718
Chris Lattner3ed871f2009-10-27 19:13:16 +00005719 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005721
Chris Lattnerac161bf2009-01-02 07:01:27 +00005722 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005723
Chris Lattner3ed871f2009-10-27 19:13:16 +00005724 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005725 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5726 SI->addCase(Table[i].first, Table[i].second);
5727 Inst = SI;
5728 return false;
5729}
5730
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005731/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005732/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005733/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5734bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005735 LocTy AddrLoc;
5736 Value *Address;
5737 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005738 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5739 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005740 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005741
Duncan Sands19d0b472010-02-16 11:11:14 +00005742 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005743 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005744
Chris Lattner3ed871f2009-10-27 19:13:16 +00005745 // Parse the destination list.
5746 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005747
Chris Lattner3ed871f2009-10-27 19:13:16 +00005748 if (Lex.getKind() != lltok::rsquare) {
5749 BasicBlock *DestBB;
5750 if (ParseTypeAndBasicBlock(DestBB, PFS))
5751 return true;
5752 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005753
Chris Lattner3ed871f2009-10-27 19:13:16 +00005754 while (EatIfPresent(lltok::comma)) {
5755 if (ParseTypeAndBasicBlock(DestBB, PFS))
5756 return true;
5757 DestList.push_back(DestBB);
5758 }
5759 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005760
Chris Lattner3ed871f2009-10-27 19:13:16 +00005761 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5762 return true;
5763
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005764 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005765 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5766 IBI->addDestination(DestList[i]);
5767 Inst = IBI;
5768 return false;
5769}
5770
Chris Lattnerac161bf2009-01-02 07:01:27 +00005771/// ParseInvoke
5772/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5773/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5774bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5775 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005776 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005777 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005778 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005779 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005780 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005781 LocTy RetTypeLoc;
5782 ValID CalleeID;
5783 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005784 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005785
Chris Lattner3ed871f2009-10-27 19:13:16 +00005786 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005787 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005788 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005789 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005790 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5791 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005792 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005793 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005794 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005795 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005796 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005797 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005798
Chris Lattnerac161bf2009-01-02 07:01:27 +00005799 // If RetType is a non-function pointer type, then this is the short syntax
5800 // for the call, which means that RetType is just the return type. Infer the
5801 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005802 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5803 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005804 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005805 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5807 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005808
Chris Lattnerac161bf2009-01-02 07:01:27 +00005809 if (!FunctionType::isValidReturnType(RetType))
5810 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005811
Owen Anderson4056ca92009-07-29 22:17:13 +00005812 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005814
David Blaikie41ba2b42015-07-27 23:32:19 +00005815 CalleeID.FTy = Ty;
5816
Chris Lattnerac161bf2009-01-02 07:01:27 +00005817 // Look up the callee.
5818 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005819 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
5820 /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005821 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005822
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005823 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005824 SmallVector<Value *, 8> Args;
5825 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005826
Chris Lattnerac161bf2009-01-02 07:01:27 +00005827 // Loop through FunctionType's arguments and ensure they are specified
5828 // correctly. Also, gather any parameter attributes.
5829 FunctionType::param_iterator I = Ty->param_begin();
5830 FunctionType::param_iterator E = Ty->param_end();
5831 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005832 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 if (I != E) {
5834 ExpectedTy = *I++;
5835 } else if (!Ty->isVarArg()) {
5836 return Error(ArgList[i].Loc, "too many arguments specified");
5837 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005838
Chris Lattnerac161bf2009-01-02 07:01:27 +00005839 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5840 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005841 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005842 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005843 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005845
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 if (I != E)
5847 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005848
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005849 if (FnAttrs.hasAlignmentAttr())
5850 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005851
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005852 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005853 AttributeList PAL =
5854 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5855 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005856
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005857 InvokeInst *II =
5858 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859 II->setCallingConv(CC);
5860 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005861 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005862 Inst = II;
5863 return false;
5864}
5865
Bill Wendlingf891bf82011-07-31 06:30:59 +00005866/// ParseResume
5867/// ::= 'resume' TypeAndValue
5868bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5869 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005870 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5871 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005872
Bill Wendlingf891bf82011-07-31 06:30:59 +00005873 ResumeInst *RI = ResumeInst::Create(Exn);
5874 Inst = RI;
5875 return false;
5876}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005877
David Majnemer654e1302015-07-31 17:58:14 +00005878bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5879 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005880 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005881 return true;
5882
5883 while (Lex.getKind() != lltok::rsquare) {
5884 // If this isn't the first argument, we need a comma.
5885 if (!Args.empty() &&
5886 ParseToken(lltok::comma, "expected ',' in argument list"))
5887 return true;
5888
5889 // Parse the argument.
5890 LocTy ArgLoc;
5891 Type *ArgTy = nullptr;
5892 if (ParseType(ArgTy, ArgLoc))
5893 return true;
5894
5895 Value *V;
5896 if (ArgTy->isMetadataTy()) {
5897 if (ParseMetadataAsValue(V, PFS))
5898 return true;
5899 } else {
5900 if (ParseValue(ArgTy, V, PFS))
5901 return true;
5902 }
5903 Args.push_back(V);
5904 }
5905
5906 Lex.Lex(); // Lex the ']'.
5907 return false;
5908}
5909
5910/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005911/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005912bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005913 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005914
David Majnemer8a1c45d2015-12-12 05:38:55 +00005915 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5916 return true;
5917
5918 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005919 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005920
5921 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5922 return true;
5923
5924 BasicBlock *UnwindBB = nullptr;
5925 if (Lex.getKind() == lltok::kw_to) {
5926 Lex.Lex();
5927 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5928 return true;
5929 } else {
5930 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5931 return true;
5932 }
5933 }
5934
David Majnemer8a1c45d2015-12-12 05:38:55 +00005935 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005936 return false;
5937}
5938
5939/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005940/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005941bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005942 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005943
David Majnemer8a1c45d2015-12-12 05:38:55 +00005944 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5945 return true;
5946
5947 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005948 return true;
5949
David Majnemer0bc0eef2015-08-15 02:46:08 +00005950 BasicBlock *BB;
5951 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5952 ParseTypeAndBasicBlock(BB, PFS))
5953 return true;
5954
David Majnemer8a1c45d2015-12-12 05:38:55 +00005955 Inst = CatchReturnInst::Create(CatchPad, BB);
5956 return false;
5957}
5958
5959/// ParseCatchSwitch
5960/// ::= 'catchswitch' within Parent
5961bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5962 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005963
5964 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5965 return true;
5966
5967 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5968 Lex.getKind() != lltok::LocalVarID)
5969 return TokError("expected scope value for catchswitch");
5970
5971 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5972 return true;
5973
5974 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5975 return true;
5976
5977 SmallVector<BasicBlock *, 32> Table;
5978 do {
5979 BasicBlock *DestBB;
5980 if (ParseTypeAndBasicBlock(DestBB, PFS))
5981 return true;
5982 Table.push_back(DestBB);
5983 } while (EatIfPresent(lltok::comma));
5984
5985 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5986 return true;
5987
5988 if (ParseToken(lltok::kw_unwind,
5989 "expected 'unwind' after catchswitch scope"))
5990 return true;
5991
5992 BasicBlock *UnwindBB = nullptr;
5993 if (EatIfPresent(lltok::kw_to)) {
5994 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5995 return true;
5996 } else {
5997 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5998 return true;
5999 }
6000
6001 auto *CatchSwitch =
6002 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6003 for (BasicBlock *DestBB : Table)
6004 CatchSwitch->addHandler(DestBB);
6005 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00006006 return false;
6007}
6008
6009/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006010/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006011bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006012 Value *CatchSwitch = nullptr;
6013
6014 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6015 return true;
6016
6017 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6018 return TokError("expected scope value for catchpad");
6019
6020 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6021 return true;
6022
David Majnemer654e1302015-07-31 17:58:14 +00006023 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006024 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006025 return true;
6026
David Majnemer8a1c45d2015-12-12 05:38:55 +00006027 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00006028 return false;
6029}
6030
David Majnemer654e1302015-07-31 17:58:14 +00006031/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00006032/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00006033bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006034 Value *ParentPad = nullptr;
6035
6036 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6037 return true;
6038
6039 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6040 Lex.getKind() != lltok::LocalVarID)
6041 return TokError("expected scope value for cleanuppad");
6042
6043 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6044 return true;
6045
David Majnemer654e1302015-07-31 17:58:14 +00006046 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006047 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006048 return true;
6049
David Majnemer8a1c45d2015-12-12 05:38:55 +00006050 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00006051 return false;
6052}
6053
Chris Lattnerac161bf2009-01-02 07:01:27 +00006054//===----------------------------------------------------------------------===//
6055// Binary Operators.
6056//===----------------------------------------------------------------------===//
6057
6058/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006059/// ::= ArithmeticOps TypeAndValue ',' Value
6060///
6061/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6062/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00006063bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006064 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006065 LocTy Loc; Value *LHS, *RHS;
6066 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6067 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6068 ParseValue(LHS->getType(), RHS, PFS))
6069 return true;
6070
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006071 bool Valid;
6072 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00006073 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006074 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00006075 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6076 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006077 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00006078 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6079 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006081
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006082 if (!Valid)
6083 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006084
Chris Lattnerac161bf2009-01-02 07:01:27 +00006085 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6086 return false;
6087}
6088
6089/// ParseLogical
6090/// ::= ArithmeticOps TypeAndValue ',' Value {
6091bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6092 unsigned Opc) {
6093 LocTy Loc; Value *LHS, *RHS;
6094 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6095 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6096 ParseValue(LHS->getType(), RHS, PFS))
6097 return true;
6098
Duncan Sands9dff9be2010-02-15 16:12:20 +00006099 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006100 return Error(Loc,"instruction requires integer or integer vector operands");
6101
6102 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6103 return false;
6104}
6105
Chris Lattnerac161bf2009-01-02 07:01:27 +00006106/// ParseCompare
6107/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6108/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006109bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6110 unsigned Opc) {
6111 // Parse the integer/fp comparison predicate.
6112 LocTy Loc;
6113 unsigned Pred;
6114 Value *LHS, *RHS;
6115 if (ParseCmpPredicate(Pred, Opc) ||
6116 ParseTypeAndValue(LHS, Loc, PFS) ||
6117 ParseToken(lltok::comma, "expected ',' after compare value") ||
6118 ParseValue(LHS->getType(), RHS, PFS))
6119 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006120
Chris Lattnerac161bf2009-01-02 07:01:27 +00006121 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006122 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006123 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006124 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006125 } else {
6126 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006127 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006128 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006129 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006130 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006131 }
6132 return false;
6133}
6134
6135//===----------------------------------------------------------------------===//
6136// Other Instructions.
6137//===----------------------------------------------------------------------===//
6138
6139
6140/// ParseCast
6141/// ::= CastOpc TypeAndValue 'to' Type
6142bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6143 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006144 LocTy Loc;
6145 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006146 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006147 if (ParseTypeAndValue(Op, Loc, PFS) ||
6148 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6149 ParseType(DestTy))
6150 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006151
Chris Lattner89d856e2009-03-01 00:53:13 +00006152 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6153 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006154 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006155 getTypeString(Op->getType()) + "' to '" +
6156 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006157 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006158 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6159 return false;
6160}
6161
6162/// ParseSelect
6163/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6164bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6165 LocTy Loc;
6166 Value *Op0, *Op1, *Op2;
6167 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6168 ParseToken(lltok::comma, "expected ',' after select condition") ||
6169 ParseTypeAndValue(Op1, PFS) ||
6170 ParseToken(lltok::comma, "expected ',' after select value") ||
6171 ParseTypeAndValue(Op2, PFS))
6172 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006173
Chris Lattnerac161bf2009-01-02 07:01:27 +00006174 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6175 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006176
Chris Lattnerac161bf2009-01-02 07:01:27 +00006177 Inst = SelectInst::Create(Op0, Op1, Op2);
6178 return false;
6179}
6180
Chris Lattnerb55ab542009-01-05 08:18:44 +00006181/// ParseVA_Arg
6182/// ::= 'va_arg' TypeAndValue ',' Type
6183bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006184 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006185 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006186 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006187 if (ParseTypeAndValue(Op, PFS) ||
6188 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006189 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006190 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006191
Chris Lattnerb55ab542009-01-05 08:18:44 +00006192 if (!EltTy->isFirstClassType())
6193 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006194
6195 Inst = new VAArgInst(Op, EltTy);
6196 return false;
6197}
6198
6199/// ParseExtractElement
6200/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6201bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6202 LocTy Loc;
6203 Value *Op0, *Op1;
6204 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6205 ParseToken(lltok::comma, "expected ',' after extract value") ||
6206 ParseTypeAndValue(Op1, PFS))
6207 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006208
Chris Lattnerac161bf2009-01-02 07:01:27 +00006209 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6210 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006211
Eric Christopherc9742252009-07-25 02:28:41 +00006212 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006213 return false;
6214}
6215
6216/// ParseInsertElement
6217/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6218bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6219 LocTy Loc;
6220 Value *Op0, *Op1, *Op2;
6221 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6222 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6223 ParseTypeAndValue(Op1, PFS) ||
6224 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6225 ParseTypeAndValue(Op2, PFS))
6226 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006227
Chris Lattnerac161bf2009-01-02 07:01:27 +00006228 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006229 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006230
Chris Lattnerac161bf2009-01-02 07:01:27 +00006231 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6232 return false;
6233}
6234
6235/// ParseShuffleVector
6236/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6237bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6238 LocTy Loc;
6239 Value *Op0, *Op1, *Op2;
6240 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6241 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6242 ParseTypeAndValue(Op1, PFS) ||
6243 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6244 ParseTypeAndValue(Op2, PFS))
6245 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006246
Chris Lattnerac161bf2009-01-02 07:01:27 +00006247 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006248 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006249
Chris Lattnerac161bf2009-01-02 07:01:27 +00006250 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6251 return false;
6252}
6253
6254/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006255/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006256int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006257 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006258 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006259
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006260 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006261 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6262 ParseValue(Ty, Op0, PFS) ||
6263 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006264 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006265 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6266 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006267
Chris Lattnerf4f03422009-12-30 05:27:33 +00006268 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006269 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006270
6271 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006272 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006273
Chris Lattner3822f632009-01-02 08:05:26 +00006274 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006275 break;
6276
Chris Lattnerf4f03422009-12-30 05:27:33 +00006277 if (Lex.getKind() == lltok::MetadataVar) {
6278 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006279 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006280 }
Devang Patel8f842d32009-10-16 18:45:49 +00006281
Chris Lattner3822f632009-01-02 08:05:26 +00006282 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006283 ParseValue(Ty, Op0, PFS) ||
6284 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006285 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006286 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6287 return true;
6288 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006289
Chris Lattnerac161bf2009-01-02 07:01:27 +00006290 if (!Ty->isFirstClassType())
6291 return Error(TypeLoc, "phi node must have first class type");
6292
Jay Foad52131342011-03-30 11:28:46 +00006293 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006294 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6295 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6296 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006297 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006298}
6299
Bill Wendlingfae14752011-08-12 20:24:12 +00006300/// ParseLandingPad
6301/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6302/// Clause
6303/// ::= 'catch' TypeAndValue
6304/// ::= 'filter'
6305/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6306bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006307 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006308
David Majnemer7fddecc2015-06-17 20:52:32 +00006309 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006310 return true;
6311
David Majnemer7fddecc2015-06-17 20:52:32 +00006312 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006313 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6314
6315 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6316 LandingPadInst::ClauseType CT;
6317 if (EatIfPresent(lltok::kw_catch))
6318 CT = LandingPadInst::Catch;
6319 else if (EatIfPresent(lltok::kw_filter))
6320 CT = LandingPadInst::Filter;
6321 else
6322 return TokError("expected 'catch' or 'filter' clause type");
6323
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006324 Value *V;
6325 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006326 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006327 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006328
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006329 // A 'catch' type expects a non-array constant. A filter clause expects an
6330 // array constant.
6331 if (CT == LandingPadInst::Catch) {
6332 if (isa<ArrayType>(V->getType()))
6333 Error(VLoc, "'catch' clause has an invalid type");
6334 } else {
6335 if (!isa<ArrayType>(V->getType()))
6336 Error(VLoc, "'filter' clause has an invalid type");
6337 }
6338
Owen Andersonf8f259d2015-03-09 07:13:42 +00006339 Constant *CV = dyn_cast<Constant>(V);
6340 if (!CV)
6341 return Error(VLoc, "clause argument must be a constant");
6342 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006343 }
6344
Owen Andersonf8f259d2015-03-09 07:13:42 +00006345 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006346 return false;
6347}
6348
Chris Lattnerac161bf2009-01-02 07:01:27 +00006349/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006350/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6351/// OptionalAttrs Type Value ParameterList OptionalAttrs
6352/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6353/// OptionalAttrs Type Value ParameterList OptionalAttrs
6354/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6355/// OptionalAttrs Type Value ParameterList OptionalAttrs
6356/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6357/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006358bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006359 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006360 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006361 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006362 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006363 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006364 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006365 LocTy RetTypeLoc;
6366 ValID CalleeID;
6367 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006368 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006369 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006370
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006371 if (TCK != CallInst::TCK_None &&
6372 ParseToken(lltok::kw_call,
6373 "expected 'tail call', 'musttail call', or 'notail call'"))
6374 return true;
6375
6376 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6377
6378 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006379 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006380 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006381 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6382 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006383 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6384 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006385 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006386
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006387 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6388 return Error(CallLoc, "fast-math-flags specified for call without "
6389 "floating-point scalar or vector return type");
6390
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 // If RetType is a non-function pointer type, then this is the short syntax
6392 // for the call, which means that RetType is just the return type. Infer the
6393 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006394 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6395 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006396 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006397 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006398 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6399 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006400
Chris Lattnerac161bf2009-01-02 07:01:27 +00006401 if (!FunctionType::isValidReturnType(RetType))
6402 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006403
Owen Anderson4056ca92009-07-29 22:17:13 +00006404 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006405 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006406
David Blaikie41ba2b42015-07-27 23:32:19 +00006407 CalleeID.FTy = Ty;
6408
Chris Lattnerac161bf2009-01-02 07:01:27 +00006409 // Look up the callee.
6410 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00006411 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6412 /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006413 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006414
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006415 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006416 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006417
Chris Lattnerac161bf2009-01-02 07:01:27 +00006418 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006419
Chris Lattnerac161bf2009-01-02 07:01:27 +00006420 // Loop through FunctionType's arguments and ensure they are specified
6421 // correctly. Also, gather any parameter attributes.
6422 FunctionType::param_iterator I = Ty->param_begin();
6423 FunctionType::param_iterator E = Ty->param_end();
6424 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006425 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006426 if (I != E) {
6427 ExpectedTy = *I++;
6428 } else if (!Ty->isVarArg()) {
6429 return Error(ArgList[i].Loc, "too many arguments specified");
6430 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006431
Chris Lattnerac161bf2009-01-02 07:01:27 +00006432 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6433 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006434 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006435 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006436 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006438
Chris Lattnerac161bf2009-01-02 07:01:27 +00006439 if (I != E)
6440 return Error(CallLoc, "not enough parameters specified for call");
6441
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006442 if (FnAttrs.hasAlignmentAttr())
6443 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006444
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006445 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006446 AttributeList PAL =
6447 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6448 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006449
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006450 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006451 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006452 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006453 if (FMF.any())
6454 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006455 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006456 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006457 Inst = CI;
6458 return false;
6459}
6460
6461//===----------------------------------------------------------------------===//
6462// Memory Instructions.
6463//===----------------------------------------------------------------------===//
6464
6465/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006466/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006467/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006468int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006469 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006470 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006471 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006472 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006473 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006474
6475 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006476 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006477
David Majnemera3b0eb22015-02-16 08:38:03 +00006478 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006479
David Majnemera3b0eb22015-02-16 08:38:03 +00006480 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6481 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006482
Chris Lattnerb2f39502009-12-30 05:44:30 +00006483 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006484 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006485 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006486 if (ParseOptionalAlignment(Alignment))
6487 return true;
6488 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6489 return true;
6490 } else if (Lex.getKind() == lltok::kw_addrspace) {
6491 ASLoc = Lex.getLoc();
6492 if (ParseOptionalAddrSpace(AddrSpace))
6493 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006494 } else if (Lex.getKind() == lltok::MetadataVar) {
6495 AteExtraComma = true;
6496 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006497 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006498 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006499 if (EatIfPresent(lltok::comma)) {
6500 if (Lex.getKind() == lltok::kw_align) {
6501 if (ParseOptionalAlignment(Alignment))
6502 return true;
6503 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6504 return true;
6505 } else if (Lex.getKind() == lltok::kw_addrspace) {
6506 ASLoc = Lex.getLoc();
6507 if (ParseOptionalAddrSpace(AddrSpace))
6508 return true;
6509 } else if (Lex.getKind() == lltok::MetadataVar) {
6510 AteExtraComma = true;
6511 }
6512 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006513 }
6514 }
6515
Dan Gohman2140a742010-05-28 01:14:11 +00006516 if (Size && !Size->getType()->isIntegerTy())
6517 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006518
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006519 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006520 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006521 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006522 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006523 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006524}
6525
6526/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006527/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006528/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006529/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006530int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006531 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006532 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006533 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006534 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006535 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006536 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006537
6538 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006539 isAtomic = true;
6540 Lex.Lex();
6541 }
6542
Chris Lattnerbc639292011-11-27 06:56:53 +00006543 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006544 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006545 isVolatile = true;
6546 Lex.Lex();
6547 }
6548
David Blaikie15d9a4c2015-04-06 20:59:48 +00006549 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006550 LocTy ExplicitTypeLoc = Lex.getLoc();
6551 if (ParseType(Ty) ||
6552 ParseToken(lltok::comma, "expected comma after load's type") ||
6553 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006554 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006555 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6556 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006557
David Blaikie15d9a4c2015-04-06 20:59:48 +00006558 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006559 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006560 if (isAtomic && !Alignment)
6561 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006562 if (Ordering == AtomicOrdering::Release ||
6563 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006564 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006565
David Blaikiea79ac142015-02-27 21:17:42 +00006566 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6567 return Error(ExplicitTypeLoc,
6568 "explicit pointee type doesn't match operand's pointee type");
6569
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006570 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006571 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006572}
6573
6574/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006575
6576/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6577/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006578/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006579int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006580 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006581 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006582 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006583 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006584 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006585 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006586
6587 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006588 isAtomic = true;
6589 Lex.Lex();
6590 }
6591
Chris Lattnerbc639292011-11-27 06:56:53 +00006592 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006593 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006594 isVolatile = true;
6595 Lex.Lex();
6596 }
6597
Chris Lattnerac161bf2009-01-02 07:01:27 +00006598 if (ParseTypeAndValue(Val, Loc, PFS) ||
6599 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006600 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006601 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006602 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006603 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006604
Duncan Sands19d0b472010-02-16 11:11:14 +00006605 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006606 return Error(PtrLoc, "store operand must be a pointer");
6607 if (!Val->getType()->isFirstClassType())
6608 return Error(Loc, "store operand must be a first class value");
6609 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6610 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006611 if (isAtomic && !Alignment)
6612 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006613 if (Ordering == AtomicOrdering::Acquire ||
6614 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006615 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006616
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006617 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006618 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006619}
6620
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006621/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006622/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6623/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006624int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006625 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6626 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006627 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6628 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006629 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006630 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006631 bool isWeak = false;
6632
6633 if (EatIfPresent(lltok::kw_weak))
6634 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006635
6636 if (EatIfPresent(lltok::kw_volatile))
6637 isVolatile = true;
6638
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006639 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6640 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6641 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6642 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6643 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006644 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006645 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006646 return true;
6647
JF Bastien800f87a2016-04-06 21:19:33 +00006648 if (SuccessOrdering == AtomicOrdering::Unordered ||
6649 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006650 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006651 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6652 return TokError("cmpxchg failure argument shall be no stronger than the "
6653 "success argument");
6654 if (FailureOrdering == AtomicOrdering::Release ||
6655 FailureOrdering == AtomicOrdering::AcquireRelease)
6656 return TokError(
6657 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006658 if (!Ptr->getType()->isPointerTy())
6659 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6660 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6661 return Error(CmpLoc, "compare value and pointer type do not match");
6662 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6663 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006664 if (!New->getType()->isFirstClassType())
6665 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006666 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006667 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006668 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006669 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006670 Inst = CXI;
6671 return AteExtraComma ? InstExtraComma : InstNormal;
6672}
6673
6674/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006675/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6676/// 'singlethread'? AtomicOrdering
6677int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006678 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6679 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006680 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006681 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006682 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006683 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006684
6685 if (EatIfPresent(lltok::kw_volatile))
6686 isVolatile = true;
6687
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006688 switch (Lex.getKind()) {
6689 default: return TokError("expected binary operation in atomicrmw");
6690 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6691 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6692 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6693 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6694 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6695 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6696 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6697 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6698 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6699 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6700 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6701 }
6702 Lex.Lex(); // Eat the operation.
6703
6704 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6705 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6706 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006707 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006708 return true;
6709
JF Bastien800f87a2016-04-06 21:19:33 +00006710 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006711 return TokError("atomicrmw cannot be unordered");
6712 if (!Ptr->getType()->isPointerTy())
6713 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6714 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6715 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6716 if (!Val->getType()->isIntegerTy())
6717 return Error(ValLoc, "atomicrmw operand must be an integer");
6718 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6719 if (Size < 8 || (Size & (Size - 1)))
6720 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6721 " integer");
6722
6723 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006724 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006725 RMWI->setVolatile(isVolatile);
6726 Inst = RMWI;
6727 return AteExtraComma ? InstExtraComma : InstNormal;
6728}
6729
Eli Friedmanfee02c62011-07-25 23:16:38 +00006730/// ParseFence
6731/// ::= 'fence' 'singlethread'? AtomicOrdering
6732int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006733 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006734 SyncScope::ID SSID = SyncScope::System;
6735 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006736 return true;
6737
JF Bastien800f87a2016-04-06 21:19:33 +00006738 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006739 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006740 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006741 return TokError("fence cannot be monotonic");
6742
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006743 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006744 return InstNormal;
6745}
6746
Chris Lattnerac161bf2009-01-02 07:01:27 +00006747/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006748/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006749int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006750 Value *Ptr = nullptr;
6751 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006752 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006753
Dan Gohman16cbbe42009-07-29 15:58:36 +00006754 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006755
David Blaikie79e6c742015-02-27 19:29:02 +00006756 Type *Ty = nullptr;
6757 LocTy ExplicitTypeLoc = Lex.getLoc();
6758 if (ParseType(Ty) ||
6759 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6760 ParseTypeAndValue(Ptr, Loc, PFS))
6761 return true;
6762
Eli Benderskyd9806682013-04-22 17:03:42 +00006763 Type *BaseType = Ptr->getType();
6764 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6765 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006766 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006767
David Blaikie8d757942015-03-09 23:08:44 +00006768 if (Ty != BasePointerType->getElementType())
6769 return Error(ExplicitTypeLoc,
6770 "explicit pointee type doesn't match operand's pointee type");
6771
Chris Lattnerac161bf2009-01-02 07:01:27 +00006772 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006773 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006774 // GEP returns a vector of pointers if at least one of parameters is a vector.
6775 // All vector parameters should have the same vector width.
6776 unsigned GEPWidth = BaseType->isVectorTy() ?
6777 BaseType->getVectorNumElements() : 0;
6778
Chris Lattner3822f632009-01-02 08:05:26 +00006779 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006780 if (Lex.getKind() == lltok::MetadataVar) {
6781 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006782 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006783 }
Chris Lattner3822f632009-01-02 08:05:26 +00006784 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006785 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006786 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006787
Nadav Rotem3924cb02011-12-05 06:29:09 +00006788 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006789 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6790 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006791 return Error(EltLoc,
6792 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006793 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006794 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006795 Indices.push_back(Val);
6796 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006797
Craig Toppere3dcce92015-08-01 22:20:21 +00006798 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006799 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006800 return Error(Loc, "base element of getelementptr must be sized");
6801
David Blaikied33bad32015-04-17 22:32:13 +00006802 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006803 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006804 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006805 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006806 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006807 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006808}
6809
6810/// ParseExtractValue
6811/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006812int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006813 Value *Val; LocTy Loc;
6814 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006815 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006816 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006817 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006818 return true;
6819
Chris Lattner392be582010-02-12 20:49:41 +00006820 if (!Val->getType()->isAggregateType())
6821 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006822
Jay Foad57aa6362011-07-13 10:26:04 +00006823 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006824 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006825 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006826 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006827}
6828
6829/// ParseInsertValue
6830/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006831int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006832 Value *Val0, *Val1; LocTy Loc0, Loc1;
6833 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006834 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006835 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6836 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6837 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006838 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006839 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006840
Chris Lattner392be582010-02-12 20:49:41 +00006841 if (!Val0->getType()->isAggregateType())
6842 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006843
David Majnemer30074532015-02-11 07:43:58 +00006844 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6845 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006846 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006847 if (IndexedType != Val1->getType())
6848 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6849 getTypeString(Val1->getType()) + "' instead of '" +
6850 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006851 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006852 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006853}
Nick Lewycky49f89192009-04-04 07:22:01 +00006854
6855//===----------------------------------------------------------------------===//
6856// Embedded metadata.
6857//===----------------------------------------------------------------------===//
6858
6859/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006860/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006861/// Element
6862/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006863bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006864 if (ParseToken(lltok::lbrace, "expected '{' here"))
6865 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006866
Dan Gohman1e0213a2010-07-13 19:33:27 +00006867 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006868 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006869 return false;
6870
Nick Lewycky49f89192009-04-04 07:22:01 +00006871 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006872 // Null is a special case since it is typeless.
6873 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006874 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006875 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006876 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006877
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006878 Metadata *MD;
6879 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006880 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006881 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006882 } while (EatIfPresent(lltok::comma));
6883
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006884 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006885}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006886
6887//===----------------------------------------------------------------------===//
6888// Use-list order directives.
6889//===----------------------------------------------------------------------===//
6890bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6891 SMLoc Loc) {
6892 if (V->use_empty())
6893 return Error(Loc, "value has no uses");
6894
6895 unsigned NumUses = 0;
6896 SmallDenseMap<const Use *, unsigned, 16> Order;
6897 for (const Use &U : V->uses()) {
6898 if (++NumUses > Indexes.size())
6899 break;
6900 Order[&U] = Indexes[NumUses - 1];
6901 }
6902 if (NumUses < 2)
6903 return Error(Loc, "value only has one use");
6904 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00006905 return Error(Loc,
6906 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006907
6908 V->sortUseList([&](const Use &L, const Use &R) {
6909 return Order.lookup(&L) < Order.lookup(&R);
6910 });
6911 return false;
6912}
6913
6914/// ParseUseListOrderIndexes
6915/// ::= '{' uint32 (',' uint32)+ '}'
6916bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6917 SMLoc Loc = Lex.getLoc();
6918 if (ParseToken(lltok::lbrace, "expected '{' here"))
6919 return true;
6920 if (Lex.getKind() == lltok::rbrace)
6921 return Lex.Error("expected non-empty list of uselistorder indexes");
6922
6923 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6924 // indexes should be distinct numbers in the range [0, size-1], and should
6925 // not be in order.
6926 unsigned Offset = 0;
6927 unsigned Max = 0;
6928 bool IsOrdered = true;
6929 assert(Indexes.empty() && "Expected empty order vector");
6930 do {
6931 unsigned Index;
6932 if (ParseUInt32(Index))
6933 return true;
6934
6935 // Update consistency checks.
6936 Offset += Index - Indexes.size();
6937 Max = std::max(Max, Index);
6938 IsOrdered &= Index == Indexes.size();
6939
6940 Indexes.push_back(Index);
6941 } while (EatIfPresent(lltok::comma));
6942
6943 if (ParseToken(lltok::rbrace, "expected '}' here"))
6944 return true;
6945
6946 if (Indexes.size() < 2)
6947 return Error(Loc, "expected >= 2 uselistorder indexes");
6948 if (Offset != 0 || Max >= Indexes.size())
6949 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6950 if (IsOrdered)
6951 return Error(Loc, "expected uselistorder indexes to change the order");
6952
6953 return false;
6954}
6955
6956/// ParseUseListOrder
6957/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6958bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6959 SMLoc Loc = Lex.getLoc();
6960 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6961 return true;
6962
6963 Value *V;
6964 SmallVector<unsigned, 16> Indexes;
6965 if (ParseTypeAndValue(V, PFS) ||
6966 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6967 ParseUseListOrderIndexes(Indexes))
6968 return true;
6969
6970 return sortUseListOrder(V, Indexes, Loc);
6971}
6972
6973/// ParseUseListOrderBB
6974/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6975bool LLParser::ParseUseListOrderBB() {
6976 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6977 SMLoc Loc = Lex.getLoc();
6978 Lex.Lex();
6979
6980 ValID Fn, Label;
6981 SmallVector<unsigned, 16> Indexes;
6982 if (ParseValID(Fn) ||
6983 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6984 ParseValID(Label) ||
6985 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6986 ParseUseListOrderIndexes(Indexes))
6987 return true;
6988
6989 // Check the function.
6990 GlobalValue *GV;
6991 if (Fn.Kind == ValID::t_GlobalName)
6992 GV = M->getNamedValue(Fn.StrVal);
6993 else if (Fn.Kind == ValID::t_GlobalID)
6994 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6995 else
6996 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6997 if (!GV)
6998 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6999 auto *F = dyn_cast<Function>(GV);
7000 if (!F)
7001 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7002 if (F->isDeclaration())
7003 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7004
7005 // Check the basic block.
7006 if (Label.Kind == ValID::t_LocalID)
7007 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7008 if (Label.Kind != ValID::t_LocalName)
7009 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00007010 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007011 if (!V)
7012 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7013 if (!isa<BasicBlock>(V))
7014 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7015
7016 return sortUseListOrder(V, Indexes, Loc);
7017}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007018
7019/// ModuleEntry
7020/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7021/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7022bool LLParser::ParseModuleEntry(unsigned ID) {
7023 assert(Lex.getKind() == lltok::kw_module);
7024 Lex.Lex();
7025
7026 std::string Path;
7027 if (ParseToken(lltok::colon, "expected ':' here") ||
7028 ParseToken(lltok::lparen, "expected '(' here") ||
7029 ParseToken(lltok::kw_path, "expected 'path' here") ||
7030 ParseToken(lltok::colon, "expected ':' here") ||
7031 ParseStringConstant(Path) ||
7032 ParseToken(lltok::comma, "expected ',' here") ||
7033 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7034 ParseToken(lltok::colon, "expected ':' here") ||
7035 ParseToken(lltok::lparen, "expected '(' here"))
7036 return true;
7037
7038 ModuleHash Hash;
7039 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7040 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7041 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7042 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7043 ParseUInt32(Hash[4]))
7044 return true;
7045
7046 if (ParseToken(lltok::rparen, "expected ')' here") ||
7047 ParseToken(lltok::rparen, "expected ')' here"))
7048 return true;
7049
7050 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7051 ModuleIdMap[ID] = ModuleEntry->first();
7052
7053 return false;
7054}
7055
7056/// TypeIdEntry
7057/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7058bool LLParser::ParseTypeIdEntry(unsigned ID) {
7059 assert(Lex.getKind() == lltok::kw_typeid);
7060 Lex.Lex();
7061
7062 std::string Name;
7063 if (ParseToken(lltok::colon, "expected ':' here") ||
7064 ParseToken(lltok::lparen, "expected '(' here") ||
7065 ParseToken(lltok::kw_name, "expected 'name' here") ||
7066 ParseToken(lltok::colon, "expected ':' here") ||
7067 ParseStringConstant(Name))
7068 return true;
7069
7070 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7071 if (ParseToken(lltok::comma, "expected ',' here") ||
7072 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7073 return true;
7074
7075 // Check if this ID was forward referenced, and if so, update the
7076 // corresponding GUIDs.
7077 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7078 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7079 for (auto TIDRef : FwdRefTIDs->second) {
7080 assert(!*TIDRef.first &&
7081 "Forward referenced type id GUID expected to be 0");
7082 *TIDRef.first = GlobalValue::getGUID(Name);
7083 }
7084 ForwardRefTypeIds.erase(FwdRefTIDs);
7085 }
7086
7087 return false;
7088}
7089
7090/// TypeIdSummary
7091/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7092bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7093 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7094 ParseToken(lltok::colon, "expected ':' here") ||
7095 ParseToken(lltok::lparen, "expected '(' here") ||
7096 ParseTypeTestResolution(TIS.TTRes))
7097 return true;
7098
7099 if (EatIfPresent(lltok::comma)) {
7100 // Expect optional wpdResolutions field
7101 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7102 return true;
7103 }
7104
7105 if (ParseToken(lltok::rparen, "expected ')' here"))
7106 return true;
7107
7108 return false;
7109}
7110
7111/// TypeTestResolution
7112/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7113/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7114/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7115/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7116/// [',' 'inlinesBits' ':' UInt64]? ')'
7117bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7118 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7119 ParseToken(lltok::colon, "expected ':' here") ||
7120 ParseToken(lltok::lparen, "expected '(' here") ||
7121 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7122 ParseToken(lltok::colon, "expected ':' here"))
7123 return true;
7124
7125 switch (Lex.getKind()) {
7126 case lltok::kw_unsat:
7127 TTRes.TheKind = TypeTestResolution::Unsat;
7128 break;
7129 case lltok::kw_byteArray:
7130 TTRes.TheKind = TypeTestResolution::ByteArray;
7131 break;
7132 case lltok::kw_inline:
7133 TTRes.TheKind = TypeTestResolution::Inline;
7134 break;
7135 case lltok::kw_single:
7136 TTRes.TheKind = TypeTestResolution::Single;
7137 break;
7138 case lltok::kw_allOnes:
7139 TTRes.TheKind = TypeTestResolution::AllOnes;
7140 break;
7141 default:
7142 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7143 }
7144 Lex.Lex();
7145
7146 if (ParseToken(lltok::comma, "expected ',' here") ||
7147 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7148 ParseToken(lltok::colon, "expected ':' here") ||
7149 ParseUInt32(TTRes.SizeM1BitWidth))
7150 return true;
7151
7152 // Parse optional fields
7153 while (EatIfPresent(lltok::comma)) {
7154 switch (Lex.getKind()) {
7155 case lltok::kw_alignLog2:
7156 Lex.Lex();
7157 if (ParseToken(lltok::colon, "expected ':'") ||
7158 ParseUInt64(TTRes.AlignLog2))
7159 return true;
7160 break;
7161 case lltok::kw_sizeM1:
7162 Lex.Lex();
7163 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7164 return true;
7165 break;
7166 case lltok::kw_bitMask: {
7167 unsigned Val;
7168 Lex.Lex();
7169 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7170 return true;
7171 assert(Val <= 0xff);
7172 TTRes.BitMask = (uint8_t)Val;
7173 break;
7174 }
7175 case lltok::kw_inlineBits:
7176 Lex.Lex();
7177 if (ParseToken(lltok::colon, "expected ':'") ||
7178 ParseUInt64(TTRes.InlineBits))
7179 return true;
7180 break;
7181 default:
7182 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7183 }
7184 }
7185
7186 if (ParseToken(lltok::rparen, "expected ')' here"))
7187 return true;
7188
7189 return false;
7190}
7191
7192/// OptionalWpdResolutions
7193/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7194/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7195bool LLParser::ParseOptionalWpdResolutions(
7196 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7197 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7198 ParseToken(lltok::colon, "expected ':' here") ||
7199 ParseToken(lltok::lparen, "expected '(' here"))
7200 return true;
7201
7202 do {
7203 uint64_t Offset;
7204 WholeProgramDevirtResolution WPDRes;
7205 if (ParseToken(lltok::lparen, "expected '(' here") ||
7206 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7207 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7208 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7209 ParseToken(lltok::rparen, "expected ')' here"))
7210 return true;
7211 WPDResMap[Offset] = WPDRes;
7212 } while (EatIfPresent(lltok::comma));
7213
7214 if (ParseToken(lltok::rparen, "expected ')' here"))
7215 return true;
7216
7217 return false;
7218}
7219
7220/// WpdRes
7221/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7222/// [',' OptionalResByArg]? ')'
7223/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7224/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7225/// [',' OptionalResByArg]? ')'
7226/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7227/// [',' OptionalResByArg]? ')'
7228bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7229 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7230 ParseToken(lltok::colon, "expected ':' here") ||
7231 ParseToken(lltok::lparen, "expected '(' here") ||
7232 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7233 ParseToken(lltok::colon, "expected ':' here"))
7234 return true;
7235
7236 switch (Lex.getKind()) {
7237 case lltok::kw_indir:
7238 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7239 break;
7240 case lltok::kw_singleImpl:
7241 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7242 break;
7243 case lltok::kw_branchFunnel:
7244 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7245 break;
7246 default:
7247 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7248 }
7249 Lex.Lex();
7250
7251 // Parse optional fields
7252 while (EatIfPresent(lltok::comma)) {
7253 switch (Lex.getKind()) {
7254 case lltok::kw_singleImplName:
7255 Lex.Lex();
7256 if (ParseToken(lltok::colon, "expected ':' here") ||
7257 ParseStringConstant(WPDRes.SingleImplName))
7258 return true;
7259 break;
7260 case lltok::kw_resByArg:
7261 if (ParseOptionalResByArg(WPDRes.ResByArg))
7262 return true;
7263 break;
7264 default:
7265 return Error(Lex.getLoc(),
7266 "expected optional WholeProgramDevirtResolution field");
7267 }
7268 }
7269
7270 if (ParseToken(lltok::rparen, "expected ')' here"))
7271 return true;
7272
7273 return false;
7274}
7275
7276/// OptionalResByArg
7277/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7278/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7279/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7280/// 'virtualConstProp' )
7281/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7282/// [',' 'bit' ':' UInt32]? ')'
7283bool LLParser::ParseOptionalResByArg(
7284 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7285 &ResByArg) {
7286 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7287 ParseToken(lltok::colon, "expected ':' here") ||
7288 ParseToken(lltok::lparen, "expected '(' here"))
7289 return true;
7290
7291 do {
7292 std::vector<uint64_t> Args;
7293 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7294 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7295 ParseToken(lltok::colon, "expected ':' here") ||
7296 ParseToken(lltok::lparen, "expected '(' here") ||
7297 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7298 ParseToken(lltok::colon, "expected ':' here"))
7299 return true;
7300
7301 WholeProgramDevirtResolution::ByArg ByArg;
7302 switch (Lex.getKind()) {
7303 case lltok::kw_indir:
7304 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7305 break;
7306 case lltok::kw_uniformRetVal:
7307 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7308 break;
7309 case lltok::kw_uniqueRetVal:
7310 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7311 break;
7312 case lltok::kw_virtualConstProp:
7313 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7314 break;
7315 default:
7316 return Error(Lex.getLoc(),
7317 "unexpected WholeProgramDevirtResolution::ByArg kind");
7318 }
7319 Lex.Lex();
7320
7321 // Parse optional fields
7322 while (EatIfPresent(lltok::comma)) {
7323 switch (Lex.getKind()) {
7324 case lltok::kw_info:
7325 Lex.Lex();
7326 if (ParseToken(lltok::colon, "expected ':' here") ||
7327 ParseUInt64(ByArg.Info))
7328 return true;
7329 break;
7330 case lltok::kw_byte:
7331 Lex.Lex();
7332 if (ParseToken(lltok::colon, "expected ':' here") ||
7333 ParseUInt32(ByArg.Byte))
7334 return true;
7335 break;
7336 case lltok::kw_bit:
7337 Lex.Lex();
7338 if (ParseToken(lltok::colon, "expected ':' here") ||
7339 ParseUInt32(ByArg.Bit))
7340 return true;
7341 break;
7342 default:
7343 return Error(Lex.getLoc(),
7344 "expected optional whole program devirt field");
7345 }
7346 }
7347
7348 if (ParseToken(lltok::rparen, "expected ')' here"))
7349 return true;
7350
7351 ResByArg[Args] = ByArg;
7352 } while (EatIfPresent(lltok::comma));
7353
7354 if (ParseToken(lltok::rparen, "expected ')' here"))
7355 return true;
7356
7357 return false;
7358}
7359
7360/// OptionalResByArg
7361/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7362bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7363 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7364 ParseToken(lltok::colon, "expected ':' here") ||
7365 ParseToken(lltok::lparen, "expected '(' here"))
7366 return true;
7367
7368 do {
7369 uint64_t Val;
7370 if (ParseUInt64(Val))
7371 return true;
7372 Args.push_back(Val);
7373 } while (EatIfPresent(lltok::comma));
7374
7375 if (ParseToken(lltok::rparen, "expected ')' here"))
7376 return true;
7377
7378 return false;
7379}
7380
7381static ValueInfo EmptyVI =
7382 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7383
7384/// Stores the given Name/GUID and associated summary into the Index.
7385/// Also updates any forward references to the associated entry ID.
7386void LLParser::AddGlobalValueToIndex(
7387 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7388 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7389 // First create the ValueInfo utilizing the Name or GUID.
7390 ValueInfo VI;
7391 if (GUID != 0) {
7392 assert(Name.empty());
7393 VI = Index->getOrInsertValueInfo(GUID);
7394 } else {
7395 assert(!Name.empty());
7396 if (M) {
7397 auto *GV = M->getNamedValue(Name);
7398 assert(GV);
7399 VI = Index->getOrInsertValueInfo(GV);
7400 } else {
7401 assert(
7402 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7403 "Need a source_filename to compute GUID for local");
7404 GUID = GlobalValue::getGUID(
7405 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7406 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7407 }
7408 }
7409
7410 // Add the summary if one was provided.
7411 if (Summary)
7412 Index->addGlobalValueSummary(VI, std::move(Summary));
7413
7414 // Resolve forward references from calls/refs
7415 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7416 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7417 for (auto VIRef : FwdRefVIs->second) {
7418 assert(*VIRef.first == EmptyVI &&
7419 "Forward referenced ValueInfo expected to be empty");
7420 *VIRef.first = VI;
7421 }
7422 ForwardRefValueInfos.erase(FwdRefVIs);
7423 }
7424
7425 // Resolve forward references from aliases
7426 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7427 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7428 for (auto AliaseeRef : FwdRefAliasees->second) {
7429 assert(!AliaseeRef.first->hasAliasee() &&
7430 "Forward referencing alias already has aliasee");
7431 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7432 }
7433 ForwardRefAliasees.erase(FwdRefAliasees);
7434 }
7435
7436 // Save the associated ValueInfo for use in later references by ID.
7437 if (ID == NumberedValueInfos.size())
7438 NumberedValueInfos.push_back(VI);
7439 else {
7440 // Handle non-continuous numbers (to make test simplification easier).
7441 if (ID > NumberedValueInfos.size())
7442 NumberedValueInfos.resize(ID + 1);
7443 NumberedValueInfos[ID] = VI;
7444 }
7445}
7446
7447/// ParseGVEntry
7448/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7449/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7450/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7451bool LLParser::ParseGVEntry(unsigned ID) {
7452 assert(Lex.getKind() == lltok::kw_gv);
7453 Lex.Lex();
7454
7455 if (ParseToken(lltok::colon, "expected ':' here") ||
7456 ParseToken(lltok::lparen, "expected '(' here"))
7457 return true;
7458
7459 std::string Name;
7460 GlobalValue::GUID GUID = 0;
7461 switch (Lex.getKind()) {
7462 case lltok::kw_name:
7463 Lex.Lex();
7464 if (ParseToken(lltok::colon, "expected ':' here") ||
7465 ParseStringConstant(Name))
7466 return true;
7467 // Can't create GUID/ValueInfo until we have the linkage.
7468 break;
7469 case lltok::kw_guid:
7470 Lex.Lex();
7471 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7472 return true;
7473 break;
7474 default:
7475 return Error(Lex.getLoc(), "expected name or guid tag");
7476 }
7477
7478 if (!EatIfPresent(lltok::comma)) {
7479 // No summaries. Wrap up.
7480 if (ParseToken(lltok::rparen, "expected ')' here"))
7481 return true;
7482 // This was created for a call to an external or indirect target.
7483 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7484 // created for indirect calls with VP. A Name with no GUID came from
7485 // an external definition. We pass ExternalLinkage since that is only
7486 // used when the GUID must be computed from Name, and in that case
7487 // the symbol must have external linkage.
7488 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7489 nullptr);
7490 return false;
7491 }
7492
7493 // Have a list of summaries
7494 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7495 ParseToken(lltok::colon, "expected ':' here"))
7496 return true;
7497
7498 do {
7499 if (ParseToken(lltok::lparen, "expected '(' here"))
7500 return true;
7501 switch (Lex.getKind()) {
7502 case lltok::kw_function:
7503 if (ParseFunctionSummary(Name, GUID, ID))
7504 return true;
7505 break;
7506 case lltok::kw_variable:
7507 if (ParseVariableSummary(Name, GUID, ID))
7508 return true;
7509 break;
7510 case lltok::kw_alias:
7511 if (ParseAliasSummary(Name, GUID, ID))
7512 return true;
7513 break;
7514 default:
7515 return Error(Lex.getLoc(), "expected summary type");
7516 }
7517 if (ParseToken(lltok::rparen, "expected ')' here"))
7518 return true;
7519 } while (EatIfPresent(lltok::comma));
7520
7521 if (ParseToken(lltok::rparen, "expected ')' here"))
7522 return true;
7523
7524 return false;
7525}
7526
7527/// FunctionSummary
7528/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7529/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7530/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7531bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7532 unsigned ID) {
7533 assert(Lex.getKind() == lltok::kw_function);
7534 Lex.Lex();
7535
7536 StringRef ModulePath;
7537 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7538 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7539 /*Live=*/false, /*IsLocal=*/false);
7540 unsigned InstCount;
7541 std::vector<FunctionSummary::EdgeTy> Calls;
7542 FunctionSummary::TypeIdInfo TypeIdInfo;
7543 std::vector<ValueInfo> Refs;
7544 // Default is all-zeros (conservative values).
7545 FunctionSummary::FFlags FFlags = {};
7546 if (ParseToken(lltok::colon, "expected ':' here") ||
7547 ParseToken(lltok::lparen, "expected '(' here") ||
7548 ParseModuleReference(ModulePath) ||
7549 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7550 ParseToken(lltok::comma, "expected ',' here") ||
7551 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7552 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7553 return true;
7554
7555 // Parse optional fields
7556 while (EatIfPresent(lltok::comma)) {
7557 switch (Lex.getKind()) {
7558 case lltok::kw_funcFlags:
7559 if (ParseOptionalFFlags(FFlags))
7560 return true;
7561 break;
7562 case lltok::kw_calls:
7563 if (ParseOptionalCalls(Calls))
7564 return true;
7565 break;
7566 case lltok::kw_typeIdInfo:
7567 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7568 return true;
7569 break;
7570 case lltok::kw_refs:
7571 if (ParseOptionalRefs(Refs))
7572 return true;
7573 break;
7574 default:
7575 return Error(Lex.getLoc(), "expected optional function summary field");
7576 }
7577 }
7578
7579 if (ParseToken(lltok::rparen, "expected ')' here"))
7580 return true;
7581
7582 auto FS = llvm::make_unique<FunctionSummary>(
7583 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
7584 std::move(TypeIdInfo.TypeTests),
7585 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7586 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7587 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7588 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7589
7590 FS->setModulePath(ModulePath);
7591
7592 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7593 ID, std::move(FS));
7594
7595 return false;
7596}
7597
7598/// VariableSummary
7599/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7600/// [',' OptionalRefs]? ')'
7601bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7602 unsigned ID) {
7603 assert(Lex.getKind() == lltok::kw_variable);
7604 Lex.Lex();
7605
7606 StringRef ModulePath;
7607 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7608 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7609 /*Live=*/false, /*IsLocal=*/false);
7610 std::vector<ValueInfo> Refs;
7611 if (ParseToken(lltok::colon, "expected ':' here") ||
7612 ParseToken(lltok::lparen, "expected '(' here") ||
7613 ParseModuleReference(ModulePath) ||
7614 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags))
7615 return true;
7616
7617 // Parse optional refs field
7618 if (EatIfPresent(lltok::comma)) {
7619 if (ParseOptionalRefs(Refs))
7620 return true;
7621 }
7622
7623 if (ParseToken(lltok::rparen, "expected ')' here"))
7624 return true;
7625
7626 auto GS = llvm::make_unique<GlobalVarSummary>(GVFlags, std::move(Refs));
7627
7628 GS->setModulePath(ModulePath);
7629
7630 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7631 ID, std::move(GS));
7632
7633 return false;
7634}
7635
7636/// AliasSummary
7637/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7638/// 'aliasee' ':' GVReference ')'
7639bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7640 unsigned ID) {
7641 assert(Lex.getKind() == lltok::kw_alias);
7642 LocTy Loc = Lex.getLoc();
7643 Lex.Lex();
7644
7645 StringRef ModulePath;
7646 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7647 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7648 /*Live=*/false, /*IsLocal=*/false);
7649 if (ParseToken(lltok::colon, "expected ':' here") ||
7650 ParseToken(lltok::lparen, "expected '(' here") ||
7651 ParseModuleReference(ModulePath) ||
7652 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7653 ParseToken(lltok::comma, "expected ',' here") ||
7654 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7655 ParseToken(lltok::colon, "expected ':' here"))
7656 return true;
7657
7658 ValueInfo AliaseeVI;
7659 unsigned GVId;
7660 if (ParseGVReference(AliaseeVI, GVId))
7661 return true;
7662
7663 if (ParseToken(lltok::rparen, "expected ')' here"))
7664 return true;
7665
7666 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7667
7668 AS->setModulePath(ModulePath);
7669
7670 // Record forward reference if the aliasee is not parsed yet.
7671 if (AliaseeVI == EmptyVI) {
7672 auto FwdRef = ForwardRefAliasees.insert(
7673 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7674 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7675 } else
7676 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7677
7678 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7679 ID, std::move(AS));
7680
7681 return false;
7682}
7683
7684/// Flag
7685/// ::= [0|1]
7686bool LLParser::ParseFlag(unsigned &Val) {
7687 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7688 return TokError("expected integer");
7689 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7690 Lex.Lex();
7691 return false;
7692}
7693
7694/// OptionalFFlags
7695/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7696/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7697/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
7698bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7699 assert(Lex.getKind() == lltok::kw_funcFlags);
7700 Lex.Lex();
7701
7702 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7703 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7704 return true;
7705
7706 do {
7707 unsigned Val;
7708 switch (Lex.getKind()) {
7709 case lltok::kw_readNone:
7710 Lex.Lex();
7711 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7712 return true;
7713 FFlags.ReadNone = Val;
7714 break;
7715 case lltok::kw_readOnly:
7716 Lex.Lex();
7717 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7718 return true;
7719 FFlags.ReadOnly = Val;
7720 break;
7721 case lltok::kw_noRecurse:
7722 Lex.Lex();
7723 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7724 return true;
7725 FFlags.NoRecurse = Val;
7726 break;
7727 case lltok::kw_returnDoesNotAlias:
7728 Lex.Lex();
7729 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7730 return true;
7731 FFlags.ReturnDoesNotAlias = Val;
7732 break;
7733 default:
7734 return Error(Lex.getLoc(), "expected function flag type");
7735 }
7736 } while (EatIfPresent(lltok::comma));
7737
7738 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
7739 return true;
7740
7741 return false;
7742}
7743
7744/// OptionalCalls
7745/// := 'calls' ':' '(' Call [',' Call]* ')'
7746/// Call ::= '(' 'callee' ':' GVReference
7747/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7748bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7749 assert(Lex.getKind() == lltok::kw_calls);
7750 Lex.Lex();
7751
7752 if (ParseToken(lltok::colon, "expected ':' in calls") |
7753 ParseToken(lltok::lparen, "expected '(' in calls"))
7754 return true;
7755
7756 IdToIndexMapType IdToIndexMap;
7757 // Parse each call edge
7758 do {
7759 ValueInfo VI;
7760 if (ParseToken(lltok::lparen, "expected '(' in call") ||
7761 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
7762 ParseToken(lltok::colon, "expected ':'"))
7763 return true;
7764
7765 LocTy Loc = Lex.getLoc();
7766 unsigned GVId;
7767 if (ParseGVReference(VI, GVId))
7768 return true;
7769
7770 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7771 unsigned RelBF = 0;
7772 if (EatIfPresent(lltok::comma)) {
7773 // Expect either hotness or relbf
7774 if (EatIfPresent(lltok::kw_hotness)) {
7775 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
7776 return true;
7777 } else {
7778 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
7779 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
7780 return true;
7781 }
7782 }
7783 // Keep track of the Call array index needing a forward reference.
7784 // We will save the location of the ValueInfo needing an update, but
7785 // can only do so once the std::vector is finalized.
7786 if (VI == EmptyVI)
7787 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7788 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
7789
7790 if (ParseToken(lltok::rparen, "expected ')' in call"))
7791 return true;
7792 } while (EatIfPresent(lltok::comma));
7793
7794 // Now that the Calls vector is finalized, it is safe to save the locations
7795 // of any forward GV references that need updating later.
7796 for (auto I : IdToIndexMap) {
7797 for (auto P : I.second) {
7798 assert(Calls[P.first].first == EmptyVI &&
7799 "Forward referenced ValueInfo expected to be empty");
7800 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7801 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7802 FwdRef.first->second.push_back(
7803 std::make_pair(&Calls[P.first].first, P.second));
7804 }
7805 }
7806
7807 if (ParseToken(lltok::rparen, "expected ')' in calls"))
7808 return true;
7809
7810 return false;
7811}
7812
7813/// Hotness
7814/// := ('unknown'|'cold'|'none'|'hot'|'critical')
7815bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
7816 switch (Lex.getKind()) {
7817 case lltok::kw_unknown:
7818 Hotness = CalleeInfo::HotnessType::Unknown;
7819 break;
7820 case lltok::kw_cold:
7821 Hotness = CalleeInfo::HotnessType::Cold;
7822 break;
7823 case lltok::kw_none:
7824 Hotness = CalleeInfo::HotnessType::None;
7825 break;
7826 case lltok::kw_hot:
7827 Hotness = CalleeInfo::HotnessType::Hot;
7828 break;
7829 case lltok::kw_critical:
7830 Hotness = CalleeInfo::HotnessType::Critical;
7831 break;
7832 default:
7833 return Error(Lex.getLoc(), "invalid call edge hotness");
7834 }
7835 Lex.Lex();
7836 return false;
7837}
7838
7839/// OptionalRefs
7840/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
7841bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
7842 assert(Lex.getKind() == lltok::kw_refs);
7843 Lex.Lex();
7844
7845 if (ParseToken(lltok::colon, "expected ':' in refs") |
7846 ParseToken(lltok::lparen, "expected '(' in refs"))
7847 return true;
7848
7849 IdToIndexMapType IdToIndexMap;
7850 // Parse each ref edge
7851 do {
7852 ValueInfo VI;
7853 LocTy Loc = Lex.getLoc();
7854 unsigned GVId;
7855 if (ParseGVReference(VI, GVId))
7856 return true;
7857
7858 // Keep track of the Refs array index needing a forward reference.
7859 // We will save the location of the ValueInfo needing an update, but
7860 // can only do so once the std::vector is finalized.
7861 if (VI == EmptyVI)
7862 IdToIndexMap[GVId].push_back(std::make_pair(Refs.size(), Loc));
7863 Refs.push_back(VI);
7864 } while (EatIfPresent(lltok::comma));
7865
7866 // Now that the Refs vector is finalized, it is safe to save the locations
7867 // of any forward GV references that need updating later.
7868 for (auto I : IdToIndexMap) {
7869 for (auto P : I.second) {
7870 assert(Refs[P.first] == EmptyVI &&
7871 "Forward referenced ValueInfo expected to be empty");
7872 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7873 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7874 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
7875 }
7876 }
7877
7878 if (ParseToken(lltok::rparen, "expected ')' in refs"))
7879 return true;
7880
7881 return false;
7882}
7883
7884/// OptionalTypeIdInfo
7885/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
7886/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
7887/// [',' TypeCheckedLoadConstVCalls]? ')'
7888bool LLParser::ParseOptionalTypeIdInfo(
7889 FunctionSummary::TypeIdInfo &TypeIdInfo) {
7890 assert(Lex.getKind() == lltok::kw_typeIdInfo);
7891 Lex.Lex();
7892
7893 if (ParseToken(lltok::colon, "expected ':' here") ||
7894 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
7895 return true;
7896
7897 do {
7898 switch (Lex.getKind()) {
7899 case lltok::kw_typeTests:
7900 if (ParseTypeTests(TypeIdInfo.TypeTests))
7901 return true;
7902 break;
7903 case lltok::kw_typeTestAssumeVCalls:
7904 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
7905 TypeIdInfo.TypeTestAssumeVCalls))
7906 return true;
7907 break;
7908 case lltok::kw_typeCheckedLoadVCalls:
7909 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
7910 TypeIdInfo.TypeCheckedLoadVCalls))
7911 return true;
7912 break;
7913 case lltok::kw_typeTestAssumeConstVCalls:
7914 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
7915 TypeIdInfo.TypeTestAssumeConstVCalls))
7916 return true;
7917 break;
7918 case lltok::kw_typeCheckedLoadConstVCalls:
7919 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
7920 TypeIdInfo.TypeCheckedLoadConstVCalls))
7921 return true;
7922 break;
7923 default:
7924 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
7925 }
7926 } while (EatIfPresent(lltok::comma));
7927
7928 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
7929 return true;
7930
7931 return false;
7932}
7933
7934/// TypeTests
7935/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
7936/// [',' (SummaryID | UInt64)]* ')'
7937bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
7938 assert(Lex.getKind() == lltok::kw_typeTests);
7939 Lex.Lex();
7940
7941 if (ParseToken(lltok::colon, "expected ':' here") ||
7942 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
7943 return true;
7944
7945 IdToIndexMapType IdToIndexMap;
7946 do {
7947 GlobalValue::GUID GUID = 0;
7948 if (Lex.getKind() == lltok::SummaryID) {
7949 unsigned ID = Lex.getUIntVal();
7950 LocTy Loc = Lex.getLoc();
7951 // Keep track of the TypeTests array index needing a forward reference.
7952 // We will save the location of the GUID needing an update, but
7953 // can only do so once the std::vector is finalized.
7954 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
7955 Lex.Lex();
7956 } else if (ParseUInt64(GUID))
7957 return true;
7958 TypeTests.push_back(GUID);
7959 } while (EatIfPresent(lltok::comma));
7960
7961 // Now that the TypeTests vector is finalized, it is safe to save the
7962 // locations of any forward GV references that need updating later.
7963 for (auto I : IdToIndexMap) {
7964 for (auto P : I.second) {
7965 assert(TypeTests[P.first] == 0 &&
7966 "Forward referenced type id GUID expected to be 0");
7967 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
7968 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
7969 FwdRef.first->second.push_back(
7970 std::make_pair(&TypeTests[P.first], P.second));
7971 }
7972 }
7973
7974 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
7975 return true;
7976
7977 return false;
7978}
7979
7980/// VFuncIdList
7981/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
7982bool LLParser::ParseVFuncIdList(
7983 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
7984 assert(Lex.getKind() == Kind);
7985 Lex.Lex();
7986
7987 if (ParseToken(lltok::colon, "expected ':' here") ||
7988 ParseToken(lltok::lparen, "expected '(' here"))
7989 return true;
7990
7991 IdToIndexMapType IdToIndexMap;
7992 do {
7993 FunctionSummary::VFuncId VFuncId;
7994 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
7995 return true;
7996 VFuncIdList.push_back(VFuncId);
7997 } while (EatIfPresent(lltok::comma));
7998
7999 if (ParseToken(lltok::rparen, "expected ')' here"))
8000 return true;
8001
8002 // Now that the VFuncIdList vector is finalized, it is safe to save the
8003 // locations of any forward GV references that need updating later.
8004 for (auto I : IdToIndexMap) {
8005 for (auto P : I.second) {
8006 assert(VFuncIdList[P.first].GUID == 0 &&
8007 "Forward referenced type id GUID expected to be 0");
8008 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8009 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8010 FwdRef.first->second.push_back(
8011 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8012 }
8013 }
8014
8015 return false;
8016}
8017
8018/// ConstVCallList
8019/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8020bool LLParser::ParseConstVCallList(
8021 lltok::Kind Kind,
8022 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8023 assert(Lex.getKind() == Kind);
8024 Lex.Lex();
8025
8026 if (ParseToken(lltok::colon, "expected ':' here") ||
8027 ParseToken(lltok::lparen, "expected '(' here"))
8028 return true;
8029
8030 IdToIndexMapType IdToIndexMap;
8031 do {
8032 FunctionSummary::ConstVCall ConstVCall;
8033 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8034 return true;
8035 ConstVCallList.push_back(ConstVCall);
8036 } while (EatIfPresent(lltok::comma));
8037
8038 if (ParseToken(lltok::rparen, "expected ')' here"))
8039 return true;
8040
8041 // Now that the ConstVCallList vector is finalized, it is safe to save the
8042 // locations of any forward GV references that need updating later.
8043 for (auto I : IdToIndexMap) {
8044 for (auto P : I.second) {
8045 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8046 "Forward referenced type id GUID expected to be 0");
8047 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8048 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8049 FwdRef.first->second.push_back(
8050 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8051 }
8052 }
8053
8054 return false;
8055}
8056
8057/// ConstVCall
Teresa Johnsonc7816802018-08-14 01:49:33 +00008058/// ::= '(' VFuncId ',' Args ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008059bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8060 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsonc7816802018-08-14 01:49:33 +00008061 if (ParseToken(lltok::lparen, "expected '(' here") ||
8062 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8063 return true;
8064
8065 if (EatIfPresent(lltok::comma))
8066 if (ParseArgs(ConstVCall.Args))
8067 return true;
8068
8069 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008070 return true;
8071
8072 return false;
8073}
8074
8075/// VFuncId
8076/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8077/// 'offset' ':' UInt64 ')'
8078bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8079 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8080 assert(Lex.getKind() == lltok::kw_vFuncId);
8081 Lex.Lex();
8082
8083 if (ParseToken(lltok::colon, "expected ':' here") ||
8084 ParseToken(lltok::lparen, "expected '(' here"))
8085 return true;
8086
8087 if (Lex.getKind() == lltok::SummaryID) {
8088 VFuncId.GUID = 0;
8089 unsigned ID = Lex.getUIntVal();
8090 LocTy Loc = Lex.getLoc();
8091 // Keep track of the array index needing a forward reference.
8092 // We will save the location of the GUID needing an update, but
8093 // can only do so once the caller's std::vector is finalized.
8094 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8095 Lex.Lex();
8096 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8097 ParseToken(lltok::colon, "expected ':' here") ||
8098 ParseUInt64(VFuncId.GUID))
8099 return true;
8100
8101 if (ParseToken(lltok::comma, "expected ',' here") ||
8102 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8103 ParseToken(lltok::colon, "expected ':' here") ||
8104 ParseUInt64(VFuncId.Offset) ||
8105 ParseToken(lltok::rparen, "expected ')' here"))
8106 return true;
8107
8108 return false;
8109}
8110
8111/// GVFlags
8112/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8113/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8114/// 'dsoLocal' ':' Flag ')'
8115bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8116 assert(Lex.getKind() == lltok::kw_flags);
8117 Lex.Lex();
8118
8119 bool HasLinkage;
8120 if (ParseToken(lltok::colon, "expected ':' here") ||
8121 ParseToken(lltok::lparen, "expected '(' here") ||
8122 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8123 ParseToken(lltok::colon, "expected ':' here"))
8124 return true;
8125
8126 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8127 assert(HasLinkage && "Linkage not optional in summary entry");
8128 Lex.Lex();
8129
8130 unsigned Flag;
8131 if (ParseToken(lltok::comma, "expected ',' here") ||
8132 ParseToken(lltok::kw_notEligibleToImport,
8133 "expected 'notEligibleToImport' here") ||
8134 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8135 return true;
8136 GVFlags.NotEligibleToImport = Flag;
8137
8138 if (ParseToken(lltok::comma, "expected ',' here") ||
8139 ParseToken(lltok::kw_live, "expected 'live' here") ||
8140 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8141 return true;
8142 GVFlags.Live = Flag;
8143
8144 if (ParseToken(lltok::comma, "expected ',' here") ||
8145 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8146 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8147 return true;
8148 GVFlags.DSOLocal = Flag;
8149
8150 if (ParseToken(lltok::rparen, "expected ')' here"))
8151 return true;
8152
8153 return false;
8154}
8155
8156/// ModuleReference
8157/// ::= 'module' ':' UInt
8158bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8159 // Parse module id.
8160 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8161 ParseToken(lltok::colon, "expected ':' here") ||
8162 ParseToken(lltok::SummaryID, "expected module ID"))
8163 return true;
8164
8165 unsigned ModuleID = Lex.getUIntVal();
8166 auto I = ModuleIdMap.find(ModuleID);
8167 // We should have already parsed all module IDs
8168 assert(I != ModuleIdMap.end());
8169 ModulePath = I->second;
8170 return false;
8171}
8172
8173/// GVReference
8174/// ::= SummaryID
8175bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8176 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8177 return true;
8178
8179 GVId = Lex.getUIntVal();
8180
8181 // Check if we already have a VI for this GV
8182 if (GVId < NumberedValueInfos.size()) {
8183 assert(NumberedValueInfos[GVId] != EmptyVI);
8184 VI = NumberedValueInfos[GVId];
8185 } else
8186 // We will create a forward reference to the stored location.
8187 VI = EmptyVI;
8188
8189 return false;
8190}