blob: 5ef171fe965398e2227bf9c83b030f4f288236e8 [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;
Teresa Johnson4fcf3b12019-01-17 15:49:03 +0000825 case lltok::kw_typeidMetadata:
826 return ParseTypeIdMetadataEntry(SummaryID);
827 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000828 default:
829 return Error(Lex.getLoc(), "unexpected summary kind");
830 }
831 Lex.setIgnoreColonInIdentifiers(false);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000832 return false;
833}
834
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000835static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
836 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
837 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
838}
839
Rafael Espindolae4b02312018-01-11 22:15:05 +0000840// If there was an explicit dso_local, update GV. In the absence of an explicit
841// dso_local we keep the default value.
842static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
843 if (DSOLocal)
844 GV.setDSOLocal(true);
845}
846
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000847/// parseIndirectSymbol:
Fangrui Songf78650a2018-07-30 19:41:25 +0000848/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertilec70d28b2017-10-26 15:00:26 +0000849/// OptionalVisibility OptionalDLLStorageClass
850/// OptionalThreadLocal OptionalUnnamedAddr
851// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000852///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000853/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000854/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000855///
Eric Christopher536f0a92015-05-28 23:07:39 +0000856/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000857///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000858bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
859 unsigned L, unsigned Visibility,
860 unsigned DLLStorageClass, bool DSOLocal,
861 GlobalVariable::ThreadLocalMode TLM,
862 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000863 bool IsAlias;
864 if (Lex.getKind() == lltok::kw_alias)
865 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000866 else if (Lex.getKind() == lltok::kw_ifunc)
867 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000868 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000869 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000870 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000871
Rafael Espindola78527052013-10-06 15:10:43 +0000872 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
873
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000874 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000875 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000876
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000877 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000878 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000879 "symbol with local linkage must have default visibility");
880
David Blaikie2f408302015-09-11 03:22:04 +0000881 Type *Ty;
882 LocTy ExplicitTypeLoc = Lex.getLoc();
883 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000884 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000885 return true;
886
Rafael Espindola64c1e182014-06-03 02:41:57 +0000887 Constant *Aliasee;
888 LocTy AliaseeLoc = Lex.getLoc();
889 if (Lex.getKind() != lltok::kw_bitcast &&
890 Lex.getKind() != lltok::kw_getelementptr &&
891 Lex.getKind() != lltok::kw_addrspacecast &&
892 Lex.getKind() != lltok::kw_inttoptr) {
893 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000894 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000895 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000896 // The bitcast dest type is not present, it is implied by the dest type.
897 ValID ID;
898 if (ParseValID(ID))
899 return true;
900 if (ID.Kind != ValID::t_Constant)
901 return Error(AliaseeLoc, "invalid aliasee");
902 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000903 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000904
Rafael Espindola64c1e182014-06-03 02:41:57 +0000905 Type *AliaseeType = Aliasee->getType();
906 auto *PTy = dyn_cast<PointerType>(AliaseeType);
907 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000908 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000909 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000910
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000911 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000912 return Error(
913 ExplicitTypeLoc,
914 "explicit pointee type doesn't match operand's pointee type");
915
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000916 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
917 return Error(
918 ExplicitTypeLoc,
919 "explicit pointee type should be a function type");
920
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000921 GlobalValue *GVal = nullptr;
922
923 // See if the alias was forward referenced, if so, prepare to replace the
924 // forward reference.
925 if (!Name.empty()) {
926 GVal = M->getNamedValue(Name);
927 if (GVal) {
928 if (!ForwardRefVals.erase(Name))
929 return Error(NameLoc, "redefinition of global '@" + Name + "'");
930 }
931 } else {
932 auto I = ForwardRefValIDs.find(NumberedVals.size());
933 if (I != ForwardRefValIDs.end()) {
934 GVal = I->second.first;
935 ForwardRefValIDs.erase(I);
936 }
937 }
938
Chris Lattnerac161bf2009-01-02 07:01:27 +0000939 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000940 std::unique_ptr<GlobalIndirectSymbol> GA;
941 if (IsAlias)
942 GA.reset(GlobalAlias::create(Ty, AddrSpace,
943 (GlobalValue::LinkageTypes)Linkage, Name,
944 Aliasee, /*Parent*/ nullptr));
945 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000946 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
947 (GlobalValue::LinkageTypes)Linkage, Name,
948 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000949 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000950 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000951 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000952 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000953 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000954
Rafael Espindola54fc2982015-06-17 17:53:31 +0000955 if (Name.empty())
956 NumberedVals.push_back(GA.get());
957
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000958 if (GVal) {
959 // Verify that types agree.
960 if (GVal->getType() != GA->getType())
961 return Error(
962 ExplicitTypeLoc,
963 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000964
Chris Lattnerac161bf2009-01-02 07:01:27 +0000965 // If they agree, just RAUW the old value with the alias and remove the
966 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000967 GVal->replaceAllUsesWith(GA.get());
968 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000969 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000970
Chris Lattnerac161bf2009-01-02 07:01:27 +0000971 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000972 if (IsAlias)
973 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
974 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000975 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000976 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000977
Rafael Espindolaaa273822014-05-09 21:49:17 +0000978 // The module owns this now
979 GA.release();
980
Chris Lattnerac161bf2009-01-02 07:01:27 +0000981 return false;
982}
983
984/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000985/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
986/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000987/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000988/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000989/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
990/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
991/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
992/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000993///
Eric Christopher536f0a92015-05-28 23:07:39 +0000994/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000995/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000996///
997bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
998 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000999 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001000 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001001 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00001002 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1003 return Error(NameLoc,
1004 "symbol with local linkage must have default visibility");
1005
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001007 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001008 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001009 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001010
Craig Topper2617dcc2014-04-15 06:32:26 +00001011 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001012 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001013 ParseOptionalToken(lltok::kw_externally_initialized,
1014 IsExternallyInitialized,
1015 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001016 ParseGlobalType(IsConstant) ||
1017 ParseType(Ty, TyLoc))
1018 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001019
Chris Lattnerac161bf2009-01-02 07:01:27 +00001020 // If the linkage is specified and is external, then no initializer is
1021 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +00001022 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +00001023 if (!HasLinkage ||
1024 !GlobalValue::isValidDeclarationLinkage(
1025 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001026 if (ParseGlobalValue(Ty, Init))
1027 return true;
1028 }
1029
David Majnemer49b3d9b2015-02-16 08:41:08 +00001030 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +00001031 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001032
David Majnemer598bd052014-12-09 05:56:09 +00001033 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001034
1035 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +00001036 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +00001037 GVal = M->getNamedValue(Name);
1038 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +00001039 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +00001040 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00001041 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001042 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +00001043 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00001044 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +00001045 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001046 ForwardRefValIDs.erase(I);
1047 }
1048 }
1049
David Majnemer598bd052014-12-09 05:56:09 +00001050 GlobalVariable *GV;
1051 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1053 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001054 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +00001056 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001057 return Error(TyLoc,
1058 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001059
David Majnemer598bd052014-12-09 05:56:09 +00001060 GV = cast<GlobalVariable>(GVal);
1061
Chris Lattnerac161bf2009-01-02 07:01:27 +00001062 // Move the forward-reference to the correct spot in the module.
1063 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1064 }
1065
1066 if (Name.empty())
1067 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001068
Chris Lattnerac161bf2009-01-02 07:01:27 +00001069 // Set the parsed properties on the global.
1070 if (Init)
1071 GV->setInitializer(Init);
1072 GV->setConstant(IsConstant);
1073 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00001074 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001075 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001076 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001077 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001078 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001079 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001080
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 // Parse attributes on the global.
1082 while (Lex.getKind() == lltok::comma) {
1083 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001084
Chris Lattnerac161bf2009-01-02 07:01:27 +00001085 if (Lex.getKind() == lltok::kw_section) {
1086 Lex.Lex();
1087 GV->setSection(Lex.getStrVal());
1088 if (ParseToken(lltok::StringConstant, "expected global section string"))
1089 return true;
1090 } else if (Lex.getKind() == lltok::kw_align) {
1091 unsigned Alignment;
1092 if (ParseOptionalAlignment(Alignment)) return true;
1093 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001094 } else if (Lex.getKind() == lltok::MetadataVar) {
1095 if (ParseGlobalObjectMetadataAttachment(*GV))
1096 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001097 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001098 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001099 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +00001100 return true;
1101 if (C)
1102 GV->setComdat(C);
1103 else
1104 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001105 }
1106 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001107
Javed Absarf3d79042017-05-11 12:28:08 +00001108 AttrBuilder Attrs;
1109 LocTy BuiltinLoc;
1110 std::vector<unsigned> FwdRefAttrGrps;
1111 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1112 return true;
1113 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1114 GV->setAttributes(AttributeSet::get(Context, Attrs));
1115 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1116 }
1117
Chris Lattnerac161bf2009-01-02 07:01:27 +00001118 return false;
1119}
1120
Bill Wendling63b88192013-02-06 06:52:58 +00001121/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001122/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001123bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001124 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001125 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001126 Lex.Lex();
1127
David Majnemerb39e22b2014-12-09 18:33:57 +00001128 if (Lex.getKind() != lltok::AttrGrpID)
1129 return TokError("expected attribute group id");
1130
Bill Wendling63b88192013-02-06 06:52:58 +00001131 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001132 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001133 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001134 Lex.Lex();
1135
1136 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001137 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001138 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001139 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001140 ParseToken(lltok::rbrace, "expected end of attribute group"))
1141 return true;
1142
Bill Wendlingb32b0412013-02-08 06:32:06 +00001143 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001144 return Error(AttrGrpLoc, "attribute group has no attributes");
1145
1146 return false;
1147}
1148
Bill Wendling8b0321d2013-02-08 00:52:31 +00001149/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001150/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001151bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1152 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001153 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001154 bool HaveError = false;
1155
1156 B.clear();
1157
Bill Wendling63b88192013-02-06 06:52:58 +00001158 while (true) {
1159 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001160 if (Token == lltok::kw_builtin)
1161 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001162 switch (Token) {
1163 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001164 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001165 return Error(Lex.getLoc(), "unterminated attribute group");
1166 case lltok::rbrace:
1167 // Finished.
1168 return false;
1169
Bill Wendlingb32b0412013-02-08 06:32:06 +00001170 case lltok::AttrGrpID: {
1171 // Allow a function to reference an attribute group:
1172 //
1173 // define void @foo() #1 { ... }
1174 if (inAttrGrp)
1175 HaveError |=
1176 Error(Lex.getLoc(),
1177 "cannot have an attribute group reference in an attribute group");
1178
1179 unsigned AttrGrpNum = Lex.getUIntVal();
1180 if (inAttrGrp) break;
1181
1182 // Save the reference to the attribute group. We'll fill it in later.
1183 FwdRefAttrGrps.push_back(AttrGrpNum);
1184 break;
1185 }
Bill Wendling63b88192013-02-06 06:52:58 +00001186 // Target-dependent attributes:
1187 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001188 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001189 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001190 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001191 }
1192
1193 // Target-independent attributes:
1194 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001195 // As a hack, we allow function alignment to be initially parsed as an
1196 // attribute on a function declaration/definition or added to an attribute
1197 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001198 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001199 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001200 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001201 if (ParseToken(lltok::equal, "expected '=' here") ||
1202 ParseUInt32(Alignment))
1203 return true;
1204 } else {
1205 if (ParseOptionalAlignment(Alignment))
1206 return true;
1207 }
Bill Wendling63b88192013-02-06 06:52:58 +00001208 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001209 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001210 }
1211 case lltok::kw_alignstack: {
1212 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001213 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001214 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001215 if (ParseToken(lltok::equal, "expected '=' here") ||
1216 ParseUInt32(Alignment))
1217 return true;
1218 } else {
1219 if (ParseOptionalStackAlignment(Alignment))
1220 return true;
1221 }
Bill Wendling63b88192013-02-06 06:52:58 +00001222 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001223 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001224 }
George Burgess IV278199f2016-04-12 01:05:35 +00001225 case lltok::kw_allocsize: {
1226 unsigned ElemSizeArg;
1227 Optional<unsigned> NumElemsArg;
1228 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1229 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1230 return true;
1231 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1232 continue;
1233 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001234 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1235 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1236 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1237 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1238 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001239 case lltok::kw_inaccessiblememonly:
1240 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1241 case lltok::kw_inaccessiblemem_or_argmemonly:
1242 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001243 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1244 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1245 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1246 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1247 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1248 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1249 case lltok::kw_noimplicitfloat:
1250 B.addAttribute(Attribute::NoImplicitFloat); break;
1251 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1252 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1253 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1254 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001255 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001256 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001257 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001258 case lltok::kw_optforfuzzing:
1259 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001260 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1261 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1262 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1263 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1264 case lltok::kw_returns_twice:
1265 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001266 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001267 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1268 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1269 case lltok::kw_sspstrong:
1270 B.addAttribute(Attribute::StackProtectStrong); break;
1271 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001272 case lltok::kw_shadowcallstack:
1273 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001274 case lltok::kw_sanitize_address:
1275 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001276 case lltok::kw_sanitize_hwaddress:
1277 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001278 case lltok::kw_sanitize_thread:
1279 B.addAttribute(Attribute::SanitizeThread); break;
1280 case lltok::kw_sanitize_memory:
1281 B.addAttribute(Attribute::SanitizeMemory); break;
Chandler Carruth664aa862018-09-04 12:38:00 +00001282 case lltok::kw_speculative_load_hardening:
1283 B.addAttribute(Attribute::SpeculativeLoadHardening);
1284 break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001285 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001286 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001287 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001288
1289 // Error handling.
1290 case lltok::kw_inreg:
1291 case lltok::kw_signext:
1292 case lltok::kw_zeroext:
1293 HaveError |=
1294 Error(Lex.getLoc(),
1295 "invalid use of attribute on a function");
1296 break;
1297 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001298 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001299 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001300 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001301 case lltok::kw_nest:
1302 case lltok::kw_noalias:
1303 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001304 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001305 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001306 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001307 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001308 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001309 HaveError |=
1310 Error(Lex.getLoc(),
1311 "invalid use of parameter-only attribute on a function");
1312 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001313 }
1314
1315 Lex.Lex();
1316 }
1317}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001318
1319//===----------------------------------------------------------------------===//
1320// GlobalValue Reference/Resolution Routines.
1321//===----------------------------------------------------------------------===//
1322
Karl Schimpf77729782015-09-03 18:06:44 +00001323static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1324 const std::string &Name) {
1325 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001326 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1327 PTy->getAddressSpace(), Name, M);
Karl Schimpf77729782015-09-03 18:06:44 +00001328 else
1329 return new GlobalVariable(*M, PTy->getElementType(), false,
1330 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1331 nullptr, GlobalVariable::NotThreadLocal,
1332 PTy->getAddressSpace());
1333}
1334
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001335Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1336 Value *Val, bool IsCall) {
1337 if (Val->getType() == Ty)
1338 return Val;
1339 // For calls we also accept variables in the program address space.
1340 Type *SuggestedTy = Ty;
1341 if (IsCall && isa<PointerType>(Ty)) {
1342 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1343 M->getDataLayout().getProgramAddressSpace());
1344 SuggestedTy = TyInProgAS;
1345 if (Val->getType() == TyInProgAS)
1346 return Val;
1347 }
1348 if (Ty->isLabelTy())
1349 Error(Loc, "'" + Name + "' is not a basic block");
1350 else
1351 Error(Loc, "'" + Name + "' defined with type '" +
1352 getTypeString(Val->getType()) + "' but expected '" +
1353 getTypeString(SuggestedTy) + "'");
1354 return nullptr;
1355}
1356
Chris Lattnerac161bf2009-01-02 07:01:27 +00001357/// GetGlobalVal - Get a value with the specified name or ID, creating a
1358/// forward reference record if needed. This can return null if the value
1359/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001360GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001361 LocTy Loc, bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001362 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001363 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001365 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001366 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001367
Chris Lattnerac161bf2009-01-02 07:01:27 +00001368 // Look this name up in the normal function symbol table.
1369 GlobalValue *Val =
1370 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001371
Chris Lattnerac161bf2009-01-02 07:01:27 +00001372 // If this is a forward reference for the value, see if we already created a
1373 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001374 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001375 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001376 if (I != ForwardRefVals.end())
1377 Val = I->second.first;
1378 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001379
Chris Lattnerac161bf2009-01-02 07:01:27 +00001380 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001381 if (Val)
1382 return cast_or_null<GlobalValue>(
1383 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001384
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001386 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001387 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1388 return FwdVal;
1389}
1390
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001391GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1392 bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001393 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001394 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001395 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001396 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001397 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001398
Craig Topper2617dcc2014-04-15 06:32:26 +00001399 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001400
Chris Lattnerac161bf2009-01-02 07:01:27 +00001401 // If this is a forward reference for the value, see if we already created a
1402 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001403 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001404 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001405 if (I != ForwardRefValIDs.end())
1406 Val = I->second.first;
1407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001408
Chris Lattnerac161bf2009-01-02 07:01:27 +00001409 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001410 if (Val)
1411 return cast_or_null<GlobalValue>(
1412 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001413
Chris Lattnerac161bf2009-01-02 07:01:27 +00001414 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001415 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001416 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1417 return FwdVal;
1418}
1419
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001421// Comdat Reference/Resolution Routines.
1422//===----------------------------------------------------------------------===//
1423
1424Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1425 // Look this name up in the comdat symbol table.
1426 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1427 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1428 if (I != ComdatSymTab.end())
1429 return &I->second;
1430
1431 // Otherwise, create a new forward reference for this value and remember it.
1432 Comdat *C = M->getOrInsertComdat(Name);
1433 ForwardRefComdats[Name] = Loc;
1434 return C;
1435}
1436
David Majnemerdad0a642014-06-27 18:19:56 +00001437//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001438// Helper Routines.
1439//===----------------------------------------------------------------------===//
1440
1441/// ParseToken - If the current token has the specified kind, eat it and return
1442/// success. Otherwise, emit the specified error and return failure.
1443bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1444 if (Lex.getKind() != T)
1445 return TokError(ErrMsg);
1446 Lex.Lex();
1447 return false;
1448}
1449
Chris Lattner3822f632009-01-02 08:05:26 +00001450/// ParseStringConstant
1451/// ::= StringConstant
1452bool LLParser::ParseStringConstant(std::string &Result) {
1453 if (Lex.getKind() != lltok::StringConstant)
1454 return TokError("expected string constant");
1455 Result = Lex.getStrVal();
1456 Lex.Lex();
1457 return false;
1458}
1459
1460/// ParseUInt32
1461/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001462bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001463 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1464 return TokError("expected integer");
1465 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1466 if (Val64 != unsigned(Val64))
1467 return TokError("expected 32-bit integer (too large)");
1468 Val = Val64;
1469 Lex.Lex();
1470 return false;
1471}
1472
Hal Finkelb0407ba2014-07-18 15:51:28 +00001473/// ParseUInt64
1474/// ::= uint64
1475bool LLParser::ParseUInt64(uint64_t &Val) {
1476 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1477 return TokError("expected integer");
1478 Val = Lex.getAPSIntVal().getLimitedValue();
1479 Lex.Lex();
1480 return false;
1481}
1482
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001483/// ParseTLSModel
1484/// := 'localdynamic'
1485/// := 'initialexec'
1486/// := 'localexec'
1487bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1488 switch (Lex.getKind()) {
1489 default:
1490 return TokError("expected localdynamic, initialexec or localexec");
1491 case lltok::kw_localdynamic:
1492 TLM = GlobalVariable::LocalDynamicTLSModel;
1493 break;
1494 case lltok::kw_initialexec:
1495 TLM = GlobalVariable::InitialExecTLSModel;
1496 break;
1497 case lltok::kw_localexec:
1498 TLM = GlobalVariable::LocalExecTLSModel;
1499 break;
1500 }
1501
1502 Lex.Lex();
1503 return false;
1504}
1505
1506/// ParseOptionalThreadLocal
1507/// := /*empty*/
1508/// := 'thread_local'
1509/// := 'thread_local' '(' tlsmodel ')'
1510bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1511 TLM = GlobalVariable::NotThreadLocal;
1512 if (!EatIfPresent(lltok::kw_thread_local))
1513 return false;
1514
1515 TLM = GlobalVariable::GeneralDynamicTLSModel;
1516 if (Lex.getKind() == lltok::lparen) {
1517 Lex.Lex();
1518 return ParseTLSModel(TLM) ||
1519 ParseToken(lltok::rparen, "expected ')' after thread local model");
1520 }
1521 return false;
1522}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001523
1524/// ParseOptionalAddrSpace
1525/// := /*empty*/
1526/// := 'addrspace' '(' uint32 ')'
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001527bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1528 AddrSpace = DefaultAS;
Chris Lattner3822f632009-01-02 08:05:26 +00001529 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001531 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001532 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001533 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001534}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001535
Artur Pilipenko17376c42015-08-03 14:31:49 +00001536/// ParseStringAttribute
1537/// := StringConstant
1538/// := StringConstant '=' StringConstant
1539bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1540 std::string Attr = Lex.getStrVal();
1541 Lex.Lex();
1542 std::string Val;
1543 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1544 return true;
1545 B.addAttribute(Attr, Val);
1546 return false;
1547}
1548
Bill Wendling34c2eb22012-12-04 23:40:58 +00001549/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1550bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1551 bool HaveError = false;
1552
1553 B.clear();
1554
Eugene Zelenko1804a772016-08-25 00:45:04 +00001555 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001556 lltok::Kind Token = Lex.getKind();
1557 switch (Token) {
1558 default: // End of attributes.
1559 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001560 case lltok::StringConstant: {
1561 if (ParseStringAttribute(B))
1562 return true;
1563 continue;
1564 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001565 case lltok::kw_align: {
1566 unsigned Alignment;
1567 if (ParseOptionalAlignment(Alignment))
1568 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001569 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001570 continue;
1571 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001572 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001573 case lltok::kw_dereferenceable: {
1574 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001575 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001576 return true;
1577 B.addDereferenceableAttr(Bytes);
1578 continue;
1579 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001580 case lltok::kw_dereferenceable_or_null: {
1581 uint64_t Bytes;
1582 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1583 return true;
1584 B.addDereferenceableOrNullAttr(Bytes);
1585 continue;
1586 }
Reid Klecknera534a382013-12-19 02:14:12 +00001587 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001588 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1589 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1590 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1591 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001592 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001593 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1594 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001595 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001596 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1597 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001598 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001599 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001600 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001601 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001602
Stephen Lin7577ed52013-04-20 13:16:13 +00001603 case lltok::kw_alignstack:
1604 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001605 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001606 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001607 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001608 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001609 case lltok::kw_minsize:
1610 case lltok::kw_naked:
1611 case lltok::kw_nobuiltin:
1612 case lltok::kw_noduplicate:
1613 case lltok::kw_noimplicitfloat:
1614 case lltok::kw_noinline:
1615 case lltok::kw_nonlazybind:
1616 case lltok::kw_noredzone:
1617 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001618 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001619 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001620 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001621 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001622 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001623 case lltok::kw_returns_twice:
1624 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001625 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001626 case lltok::kw_sanitize_memory:
1627 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001628 case lltok::kw_speculative_load_hardening:
Stephen Lin7577ed52013-04-20 13:16:13 +00001629 case lltok::kw_ssp:
1630 case lltok::kw_sspreq:
1631 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001632 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001633 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001634 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001635 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001636 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1637 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001639
Bill Wendling34c2eb22012-12-04 23:40:58 +00001640 Lex.Lex();
1641 }
1642}
1643
1644/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1645bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1646 bool HaveError = false;
1647
1648 B.clear();
1649
Eugene Zelenko1804a772016-08-25 00:45:04 +00001650 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001651 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001652 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001653 default: // End of attributes.
1654 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001655 case lltok::StringConstant: {
1656 if (ParseStringAttribute(B))
1657 return true;
1658 continue;
1659 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001660 case lltok::kw_dereferenceable: {
1661 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001662 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001663 return true;
1664 B.addDereferenceableAttr(Bytes);
1665 continue;
1666 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001667 case lltok::kw_dereferenceable_or_null: {
1668 uint64_t Bytes;
1669 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1670 return true;
1671 B.addDereferenceableOrNullAttr(Bytes);
1672 continue;
1673 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001674 case lltok::kw_align: {
1675 unsigned Alignment;
1676 if (ParseOptionalAlignment(Alignment))
1677 return true;
1678 B.addAlignmentAttr(Alignment);
1679 continue;
1680 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001681 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1682 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001683 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001684 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1685 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001686
Bill Wendling34c2eb22012-12-04 23:40:58 +00001687 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001688 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001689 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001690 case lltok::kw_nest:
1691 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001692 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001693 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001694 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001695 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001696 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001697 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001698
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001699 case lltok::kw_alignstack:
1700 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001701 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001702 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001703 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001704 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001705 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001706 case lltok::kw_minsize:
1707 case lltok::kw_naked:
1708 case lltok::kw_nobuiltin:
1709 case lltok::kw_noduplicate:
1710 case lltok::kw_noimplicitfloat:
1711 case lltok::kw_noinline:
1712 case lltok::kw_nonlazybind:
1713 case lltok::kw_noredzone:
1714 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001715 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001716 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001717 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001718 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001719 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001720 case lltok::kw_returns_twice:
1721 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001722 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001723 case lltok::kw_sanitize_memory:
1724 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001725 case lltok::kw_speculative_load_hardening:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001726 case lltok::kw_ssp:
1727 case lltok::kw_sspreq:
1728 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001729 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001730 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001731 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001732 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001733 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001734 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001735
1736 case lltok::kw_readnone:
1737 case lltok::kw_readonly:
1738 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001739 }
1740
Chris Lattnerac161bf2009-01-02 07:01:27 +00001741 Lex.Lex();
1742 }
1743}
1744
Rafael Espindolac6269912016-05-10 17:16:45 +00001745static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1746 HasLinkage = true;
1747 switch (Kind) {
1748 default:
1749 HasLinkage = false;
1750 return GlobalValue::ExternalLinkage;
1751 case lltok::kw_private:
1752 return GlobalValue::PrivateLinkage;
1753 case lltok::kw_internal:
1754 return GlobalValue::InternalLinkage;
1755 case lltok::kw_weak:
1756 return GlobalValue::WeakAnyLinkage;
1757 case lltok::kw_weak_odr:
1758 return GlobalValue::WeakODRLinkage;
1759 case lltok::kw_linkonce:
1760 return GlobalValue::LinkOnceAnyLinkage;
1761 case lltok::kw_linkonce_odr:
1762 return GlobalValue::LinkOnceODRLinkage;
1763 case lltok::kw_available_externally:
1764 return GlobalValue::AvailableExternallyLinkage;
1765 case lltok::kw_appending:
1766 return GlobalValue::AppendingLinkage;
1767 case lltok::kw_common:
1768 return GlobalValue::CommonLinkage;
1769 case lltok::kw_extern_weak:
1770 return GlobalValue::ExternalWeakLinkage;
1771 case lltok::kw_external:
1772 return GlobalValue::ExternalLinkage;
1773 }
1774}
1775
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776/// ParseOptionalLinkage
1777/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001778/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779/// ::= 'internal'
1780/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001781/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001783/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001784/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001786/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787/// ::= 'extern_weak'
1788/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001789bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1790 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001791 unsigned &DLLStorageClass,
1792 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001793 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1794 if (HasLinkage)
1795 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001796 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001797 ParseOptionalVisibility(Visibility);
1798 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001799
1800 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1801 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1802 }
1803
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 return false;
1805}
1806
Sean Fertilec70d28b2017-10-26 15:00:26 +00001807void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1808 switch (Lex.getKind()) {
1809 default:
1810 DSOLocal = false;
1811 break;
1812 case lltok::kw_dso_local:
1813 DSOLocal = true;
1814 Lex.Lex();
1815 break;
1816 case lltok::kw_dso_preemptable:
1817 DSOLocal = false;
1818 Lex.Lex();
1819 break;
1820 }
1821}
1822
Chris Lattnerac161bf2009-01-02 07:01:27 +00001823/// ParseOptionalVisibility
1824/// ::= /*empty*/
1825/// ::= 'default'
1826/// ::= 'hidden'
1827/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001828///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001829void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001830 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001831 default:
1832 Res = GlobalValue::DefaultVisibility;
1833 return;
1834 case lltok::kw_default:
1835 Res = GlobalValue::DefaultVisibility;
1836 break;
1837 case lltok::kw_hidden:
1838 Res = GlobalValue::HiddenVisibility;
1839 break;
1840 case lltok::kw_protected:
1841 Res = GlobalValue::ProtectedVisibility;
1842 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001843 }
1844 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001845}
1846
Nico Rieck7157bb72014-01-14 15:22:47 +00001847/// ParseOptionalDLLStorageClass
1848/// ::= /*empty*/
1849/// ::= 'dllimport'
1850/// ::= 'dllexport'
1851///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001852void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001853 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001854 default:
1855 Res = GlobalValue::DefaultStorageClass;
1856 return;
1857 case lltok::kw_dllimport:
1858 Res = GlobalValue::DLLImportStorageClass;
1859 break;
1860 case lltok::kw_dllexport:
1861 Res = GlobalValue::DLLExportStorageClass;
1862 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001863 }
1864 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001865}
1866
Chris Lattnerac161bf2009-01-02 07:01:27 +00001867/// ParseOptionalCallingConv
1868/// ::= /*empty*/
1869/// ::= 'ccc'
1870/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001871/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001872/// ::= 'coldcc'
1873/// ::= 'x86_stdcallcc'
1874/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001875/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001876/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001877/// ::= 'arm_apcscc'
1878/// ::= 'arm_aapcscc'
1879/// ::= 'arm_aapcs_vfpcc'
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001880/// ::= 'aarch64_vector_pcs'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001881/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001882/// ::= 'avr_intrcc'
1883/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001884/// ::= 'ptx_kernel'
1885/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001886/// ::= 'spir_func'
1887/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001888/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001889/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001890/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001891/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001892/// ::= 'preserve_mostcc'
1893/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001894/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001895/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001896/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001897/// ::= 'hhvmcc'
1898/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001899/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001900/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001901/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001902/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001903/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001904/// ::= 'amdgpu_gs'
1905/// ::= 'amdgpu_ps'
1906/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001907/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001908/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001909///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001910bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001911 switch (Lex.getKind()) {
1912 default: CC = CallingConv::C; return false;
1913 case lltok::kw_ccc: CC = CallingConv::C; break;
1914 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1915 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1916 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1917 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001918 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001919 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001920 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001921 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1922 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1923 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001924 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001925 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001926 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1927 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001928 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1929 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001930 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1931 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001932 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001933 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001934 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001935 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001936 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001937 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1938 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001939 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001940 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001941 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001942 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1943 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001944 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001945 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001946 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001947 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001948 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001949 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1950 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1951 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001952 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001953 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001954 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001955 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001956 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001957 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 Lex.Lex();
1960 return false;
1961}
1962
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001963/// ParseMetadataAttachment
1964/// ::= !dbg !42
1965bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1966 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1967
1968 std::string Name = Lex.getStrVal();
1969 Kind = M->getMDKindID(Name);
1970 Lex.Lex();
1971
1972 return ParseMDNode(MD);
1973}
1974
Chris Lattner5c427632009-12-30 05:31:19 +00001975/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001976/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001977bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001978 do {
1979 if (Lex.getKind() != lltok::MetadataVar)
1980 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001981
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001982 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001983 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001984 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001985 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001987 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001988 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001989 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001990
Chris Lattner596760d2009-12-29 21:25:40 +00001991 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001992 } while (EatIfPresent(lltok::comma));
1993 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001994}
1995
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001996/// ParseGlobalObjectMetadataAttachment
1997/// ::= !dbg !57
1998bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1999 unsigned MDK;
2000 MDNode *N;
2001 if (ParseMetadataAttachment(MDK, N))
2002 return true;
2003
Peter Collingbourne382d81c2016-06-01 01:17:57 +00002004 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002005 return false;
2006}
2007
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002008/// ParseOptionalFunctionMetadata
2009/// ::= (!dbg !57)*
2010bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002011 while (Lex.getKind() == lltok::MetadataVar)
2012 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002013 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002014 return false;
2015}
2016
Chris Lattnerac161bf2009-01-02 07:01:27 +00002017/// ParseOptionalAlignment
2018/// ::= /* empty */
2019/// ::= 'align' 4
2020bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2021 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002022 if (!EatIfPresent(lltok::kw_align))
2023 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00002024 LocTy AlignLoc = Lex.getLoc();
2025 if (ParseUInt32(Alignment)) return true;
2026 if (!isPowerOf2_32(Alignment))
2027 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00002028 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00002029 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00002030 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031}
2032
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002033/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00002034/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002035/// ::= AttrKind '(' 4 ')'
2036///
2037/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2038bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2039 uint64_t &Bytes) {
2040 assert((AttrKind == lltok::kw_dereferenceable ||
2041 AttrKind == lltok::kw_dereferenceable_or_null) &&
2042 "contract!");
2043
Hal Finkelb0407ba2014-07-18 15:51:28 +00002044 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002045 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00002046 return false;
2047 LocTy ParenLoc = Lex.getLoc();
2048 if (!EatIfPresent(lltok::lparen))
2049 return Error(ParenLoc, "expected '('");
2050 LocTy DerefLoc = Lex.getLoc();
2051 if (ParseUInt64(Bytes)) return true;
2052 ParenLoc = Lex.getLoc();
2053 if (!EatIfPresent(lltok::rparen))
2054 return Error(ParenLoc, "expected ')'");
2055 if (!Bytes)
2056 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2057 return false;
2058}
2059
Chris Lattnerb2f39502009-12-30 05:44:30 +00002060/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002061/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00002062/// ::= ',' align 4
2063///
2064/// This returns with AteExtraComma set to true if it ate an excess comma at the
2065/// end.
2066bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2067 bool &AteExtraComma) {
2068 AteExtraComma = false;
2069 while (EatIfPresent(lltok::comma)) {
2070 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00002071 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00002072 AteExtraComma = true;
2073 return false;
2074 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002075
Chris Lattner95b0ff42010-04-23 00:50:50 +00002076 if (Lex.getKind() != lltok::kw_align)
2077 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00002078
Chris Lattner95b0ff42010-04-23 00:50:50 +00002079 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00002080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002081
Devang Patelea8a4b92009-09-17 23:04:48 +00002082 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083}
2084
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002085/// ParseOptionalCommaAddrSpace
2086/// ::=
2087/// ::= ',' addrspace(1)
2088///
2089/// This returns with AteExtraComma set to true if it ate an excess comma at the
2090/// end.
2091bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2092 LocTy &Loc,
2093 bool &AteExtraComma) {
2094 AteExtraComma = false;
2095 while (EatIfPresent(lltok::comma)) {
2096 // Metadata at the end is an early exit.
2097 if (Lex.getKind() == lltok::MetadataVar) {
2098 AteExtraComma = true;
2099 return false;
2100 }
2101
2102 Loc = Lex.getLoc();
2103 if (Lex.getKind() != lltok::kw_addrspace)
2104 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2105
2106 if (ParseOptionalAddrSpace(AddrSpace))
2107 return true;
2108 }
2109
2110 return false;
2111}
2112
George Burgess IV278199f2016-04-12 01:05:35 +00002113bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2114 Optional<unsigned> &HowManyArg) {
2115 Lex.Lex();
2116
2117 auto StartParen = Lex.getLoc();
2118 if (!EatIfPresent(lltok::lparen))
2119 return Error(StartParen, "expected '('");
2120
2121 if (ParseUInt32(BaseSizeArg))
2122 return true;
2123
2124 if (EatIfPresent(lltok::comma)) {
2125 auto HowManyAt = Lex.getLoc();
2126 unsigned HowMany;
2127 if (ParseUInt32(HowMany))
2128 return true;
2129 if (HowMany == BaseSizeArg)
2130 return Error(HowManyAt,
2131 "'allocsize' indices can't refer to the same parameter");
2132 HowManyArg = HowMany;
2133 } else
2134 HowManyArg = None;
2135
2136 auto EndParen = Lex.getLoc();
2137 if (!EatIfPresent(lltok::rparen))
2138 return Error(EndParen, "expected ')'");
2139 return false;
2140}
2141
Eli Friedmanfee02c62011-07-25 23:16:38 +00002142/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002143/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002144/// else: ::=
2145///
2146/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002147bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002148 AtomicOrdering &Ordering) {
2149 if (!isAtomic)
2150 return false;
2151
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002152 return ParseScope(SSID) || ParseOrdering(Ordering);
2153}
Tim Northovere94a5182014-03-11 10:48:52 +00002154
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002155/// ParseScope
2156/// ::= syncscope("singlethread" | "<target scope>")?
2157///
2158/// This sets synchronization scope ID to the ID of the parsed value.
2159bool LLParser::ParseScope(SyncScope::ID &SSID) {
2160 SSID = SyncScope::System;
2161 if (EatIfPresent(lltok::kw_syncscope)) {
2162 auto StartParenAt = Lex.getLoc();
2163 if (!EatIfPresent(lltok::lparen))
2164 return Error(StartParenAt, "Expected '(' in syncscope");
2165
2166 std::string SSN;
2167 auto SSNAt = Lex.getLoc();
2168 if (ParseStringConstant(SSN))
2169 return Error(SSNAt, "Expected synchronization scope name");
2170
2171 auto EndParenAt = Lex.getLoc();
2172 if (!EatIfPresent(lltok::rparen))
2173 return Error(EndParenAt, "Expected ')' in syncscope");
2174
2175 SSID = Context.getOrInsertSyncScopeID(SSN);
2176 }
2177
2178 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002179}
2180
2181/// ParseOrdering
2182/// ::= AtomicOrdering
2183///
2184/// This sets Ordering to the parsed value.
2185bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002186 switch (Lex.getKind()) {
2187 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002188 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2189 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2190 // Not specified yet:
2191 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2192 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2193 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2194 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2195 case lltok::kw_seq_cst:
2196 Ordering = AtomicOrdering::SequentiallyConsistent;
2197 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002198 }
2199 Lex.Lex();
2200 return false;
2201}
2202
Charles Davisbe5557e2010-02-12 00:31:15 +00002203/// ParseOptionalStackAlignment
2204/// ::= /* empty */
2205/// ::= 'alignstack' '(' 4 ')'
2206bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2207 Alignment = 0;
2208 if (!EatIfPresent(lltok::kw_alignstack))
2209 return false;
2210 LocTy ParenLoc = Lex.getLoc();
2211 if (!EatIfPresent(lltok::lparen))
2212 return Error(ParenLoc, "expected '('");
2213 LocTy AlignLoc = Lex.getLoc();
2214 if (ParseUInt32(Alignment)) return true;
2215 ParenLoc = Lex.getLoc();
2216 if (!EatIfPresent(lltok::rparen))
2217 return Error(ParenLoc, "expected ')'");
2218 if (!isPowerOf2_32(Alignment))
2219 return Error(AlignLoc, "stack alignment is not a power of two");
2220 return false;
2221}
Devang Patelea8a4b92009-09-17 23:04:48 +00002222
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002223/// ParseIndexList - This parses the index list for an insert/extractvalue
2224/// instruction. This sets AteExtraComma in the case where we eat an extra
2225/// comma at the end of the line and find that it is followed by metadata.
2226/// Clients that don't allow metadata can call the version of this function that
2227/// only takes one argument.
2228///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229/// ParseIndexList
2230/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002231///
2232bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2233 bool &AteExtraComma) {
2234 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002235
Chris Lattnerac161bf2009-01-02 07:01:27 +00002236 if (Lex.getKind() != lltok::comma)
2237 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238
Chris Lattner3822f632009-01-02 08:05:26 +00002239 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002240 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002241 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002242 AteExtraComma = true;
2243 return false;
2244 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002245 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002246 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 Indices.push_back(Idx);
2248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 return false;
2251}
2252
2253//===----------------------------------------------------------------------===//
2254// Type Parsing.
2255//===----------------------------------------------------------------------===//
2256
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002257/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002258bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002259 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 switch (Lex.getKind()) {
2261 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002262 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002269 // Type ::= StructType
2270 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 return true;
2272 break;
2273 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002274 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 Lex.Lex(); // eat the lsquare.
2276 if (ParseArrayVectorType(Result, false))
2277 return true;
2278 break;
2279 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002281 Lex.Lex();
2282 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002283 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002284 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 } else if (ParseArrayVectorType(Result, true))
2287 return true;
2288 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289 case lltok::LocalVar: {
2290 // Type ::= %foo
2291 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002292
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002293 // If the type hasn't been defined yet, create a forward definition and
2294 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002295 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002296 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002297 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002298 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002299 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 Lex.Lex();
2301 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002302 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002303
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002304 case lltok::LocalVarID: {
2305 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002306 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002307
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308 // If the type hasn't been defined yet, create a forward definition and
2309 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002310 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002311 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002312 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002314 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 Lex.Lex();
2316 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 }
2318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002319
2320 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002321 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322 switch (Lex.getKind()) {
2323 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002324 default:
2325 if (!AllowVoid && Result->isVoidTy())
2326 return Error(TypeLoc, "void type only allowed for function results");
2327 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002329 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002330 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002331 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002333 if (Result->isVoidTy())
2334 return TokError("pointers to void are invalid - use i8* instead");
2335 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002336 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002337 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338 Lex.Lex();
2339 break;
2340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002343 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002345 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002346 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002347 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002348 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 unsigned AddrSpace;
2350 if (ParseOptionalAddrSpace(AddrSpace) ||
2351 ParseToken(lltok::star, "expected '*' in address space"))
2352 return true;
2353
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002354 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002355 break;
2356 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002357
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2359 case lltok::lparen:
2360 if (ParseFunctionType(Result))
2361 return true;
2362 break;
2363 }
2364 }
2365}
2366
2367/// ParseParameterList
2368/// ::= '(' ')'
2369/// ::= '(' Arg (',' Arg)* ')'
2370/// Arg
2371/// ::= Type OptionalAttributes Value OptionalAttributes
2372bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002373 PerFunctionState &PFS, bool IsMustTailCall,
2374 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 if (ParseToken(lltok::lparen, "expected '(' in call"))
2376 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 while (Lex.getKind() != lltok::rparen) {
2379 // If this isn't the first argument, we need a comma.
2380 if (!ArgList.empty() &&
2381 ParseToken(lltok::comma, "expected ',' in argument list"))
2382 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002383
Reid Kleckner83498642014-08-26 00:33:28 +00002384 // Parse an ellipsis if this is a musttail call in a variadic function.
2385 if (Lex.getKind() == lltok::dotdotdot) {
2386 const char *Msg = "unexpected ellipsis in argument list for ";
2387 if (!IsMustTailCall)
2388 return TokError(Twine(Msg) + "non-musttail call");
2389 if (!InVarArgsFunc)
2390 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2391 Lex.Lex(); // Lex the '...', it is purely for readability.
2392 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2393 }
2394
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 // Parse the argument.
2396 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002397 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002398 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002400 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002402
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002403 if (ArgTy->isMetadataTy()) {
2404 if (ParseMetadataAsValue(V, PFS))
2405 return true;
2406 } else {
2407 // Otherwise, handle normal operands.
2408 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2409 return true;
2410 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002411 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002412 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 }
2414
Reid Kleckner83498642014-08-26 00:33:28 +00002415 if (IsMustTailCall && InVarArgsFunc)
2416 return TokError("expected '...' at end of argument list for musttail call "
2417 "in varargs function");
2418
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 Lex.Lex(); // Lex the ')'.
2420 return false;
2421}
2422
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002423/// ParseOptionalOperandBundles
2424/// ::= /*empty*/
2425/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2426///
2427/// OperandBundle
2428/// ::= bundle-tag '(' ')'
2429/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2430///
2431/// bundle-tag ::= String Constant
2432bool LLParser::ParseOptionalOperandBundles(
2433 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2434 LocTy BeginLoc = Lex.getLoc();
2435 if (!EatIfPresent(lltok::lsquare))
2436 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002438 while (Lex.getKind() != lltok::rsquare) {
2439 // If this isn't the first operand bundle, we need a comma.
2440 if (!BundleList.empty() &&
2441 ParseToken(lltok::comma, "expected ',' in input list"))
2442 return true;
2443
2444 std::string Tag;
2445 if (ParseStringConstant(Tag))
2446 return true;
2447
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002448 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2449 return true;
2450
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002451 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002452 while (Lex.getKind() != lltok::rparen) {
2453 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002454 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002455 ParseToken(lltok::comma, "expected ',' in input list"))
2456 return true;
2457
2458 Type *Ty = nullptr;
2459 Value *Input = nullptr;
2460 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2461 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002462 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002463 }
2464
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002465 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2466
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002467 Lex.Lex(); // Lex the ')'.
2468 }
2469
2470 if (BundleList.empty())
2471 return Error(BeginLoc, "operand bundle set must not be empty");
2472
2473 Lex.Lex(); // Lex the ']'.
2474 return false;
2475}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476
Chris Lattner2ed06b42009-01-05 18:34:07 +00002477/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002478/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479/// ::= '(' ArgTypeListI ')'
2480/// ArgTypeListI
2481/// ::= /*empty*/
2482/// ::= '...'
2483/// ::= ArgTypeList ',' '...'
2484/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002485///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002486bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2487 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 isVarArg = false;
2489 assert(Lex.getKind() == lltok::lparen);
2490 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 if (Lex.getKind() == lltok::rparen) {
2493 // empty
2494 } else if (Lex.getKind() == lltok::dotdotdot) {
2495 isVarArg = true;
2496 Lex.Lex();
2497 } else {
2498 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002499 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002500 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002502
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002503 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002504 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505
Chris Lattnerfdd87902009-10-05 05:54:46 +00002506 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002507 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002508
Chris Lattnerdef19492011-06-17 06:36:20 +00002509 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002510 Name = Lex.getStrVal();
2511 Lex.Lex();
2512 }
Chris Lattner3822f632009-01-02 08:05:26 +00002513
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002514 if (!FunctionType::isValidArgumentType(ArgTy))
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),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002519 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002520
Chris Lattner3822f632009-01-02 08:05:26 +00002521 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002523 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 break;
2526 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002527
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 // Otherwise must be an argument type.
2529 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002530 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002531
Chris Lattnerfdd87902009-10-05 05:54:46 +00002532 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002533 return Error(TypeLoc, "argument can not have void type");
2534
Chris Lattnerdef19492011-06-17 06:36:20 +00002535 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002536 Name = Lex.getStrVal();
2537 Lex.Lex();
2538 } else {
2539 Name = "";
2540 }
Chris Lattner3822f632009-01-02 08:05:26 +00002541
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002542 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002543 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002545 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002546 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002547 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 }
2549 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002550
Chris Lattner3822f632009-01-02 08:05:26 +00002551 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002553
Chris Lattnerac161bf2009-01-02 07:01:27 +00002554/// ParseFunctionType
2555/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002556bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 assert(Lex.getKind() == lltok::lparen);
2558
Chris Lattnerce473c72009-01-05 08:04:33 +00002559 if (!FunctionType::isValidReturnType(Result))
2560 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002561
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002562 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002564 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 // Reject names on the arguments lists.
2568 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2569 if (!ArgList[i].Name.empty())
2570 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002571 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002572 return Error(ArgList[i].Loc,
2573 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575
Jay Foadb804a2b2011-07-12 14:06:48 +00002576 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002578 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002579
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002580 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581 return false;
2582}
2583
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002584/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2585/// other structs.
2586bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2587 SmallVector<Type*, 8> Elts;
2588 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002589
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002590 Result = StructType::get(Context, Elts, Packed);
2591 return false;
2592}
2593
2594/// ParseStructDefinition - Parse a struct in a 'type' definition.
2595bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2596 std::pair<Type*, LocTy> &Entry,
2597 Type *&ResultTy) {
2598 // If the type was already defined, diagnose the redefinition.
2599 if (Entry.first && !Entry.second.isValid())
2600 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002601
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002602 // If we have opaque, just return without filling in the definition for the
2603 // struct. This counts as a definition as far as the .ll file goes.
2604 if (EatIfPresent(lltok::kw_opaque)) {
2605 // This type is being defined, so clear the location to indicate this.
2606 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002607
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002608 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002609 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002610 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002611 ResultTy = Entry.first;
2612 return false;
2613 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002614
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002615 // If the type starts with '<', then it is either a packed struct or a vector.
2616 bool isPacked = EatIfPresent(lltok::less);
2617
2618 // If we don't have a struct, then we have a random type alias, which we
2619 // accept for compatibility with old files. These types are not allowed to be
2620 // forward referenced and not allowed to be recursive.
2621 if (Lex.getKind() != lltok::lbrace) {
2622 if (Entry.first)
2623 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002624
Craig Topper2617dcc2014-04-15 06:32:26 +00002625 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002626 if (isPacked)
2627 return ParseArrayVectorType(ResultTy, true);
2628 return ParseType(ResultTy);
2629 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002630
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002631 // This type is being defined, so clear the location to indicate this.
2632 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002634 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002635 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002636 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002637
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002638 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002639
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002640 SmallVector<Type*, 8> Body;
2641 if (ParseStructBody(Body) ||
2642 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2643 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002644
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002645 STy->setBody(Body, isPacked);
2646 ResultTy = STy;
2647 return false;
2648}
2649
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002651/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002652/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002653/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002655/// ::= '<' '{' Type (',' Type)* '}' '>'
2656bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 assert(Lex.getKind() == lltok::lbrace);
2658 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002659
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002660 // Handle the empty struct.
2661 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663
Chris Lattnerf880ca22009-03-09 04:49:14 +00002664 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002665 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002666 if (ParseType(Ty)) return true;
2667 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002668
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002669 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002670 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002671
Chris Lattner3822f632009-01-02 08:05:26 +00002672 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002673 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002674 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002675
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002676 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002677 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002678
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002679 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002681
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002682 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683}
2684
2685/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2686/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002687/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688/// ::= '[' APSINTVAL 'x' Types ']'
2689/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002690bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002691 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2692 Lex.getAPSIntVal().getBitWidth() > 64)
2693 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002694
Chris Lattnerac161bf2009-01-02 07:01:27 +00002695 LocTy SizeLoc = Lex.getLoc();
2696 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002697 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002698
Chris Lattner3822f632009-01-02 08:05:26 +00002699 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2700 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701
2702 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002703 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002704 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002705
Chris Lattner3822f632009-01-02 08:05:26 +00002706 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2707 "expected end of sequential type"))
2708 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002709
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002711 if (Size == 0)
2712 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 if ((unsigned)Size != Size)
2714 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002715 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002716 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002717 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002718 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002719 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002720 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002721 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 }
2723 return false;
2724}
2725
2726//===----------------------------------------------------------------------===//
2727// Function Semantic Analysis.
2728//===----------------------------------------------------------------------===//
2729
Chris Lattner3432c622009-10-28 03:39:23 +00002730LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2731 int functionNumber)
2732 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733
2734 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002735 for (Argument &A : F.args())
2736 if (!A.hasName())
2737 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002738}
2739
2740LLParser::PerFunctionState::~PerFunctionState() {
2741 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
David Blaikie9ebdc692015-09-21 21:07:50 +00002743 for (const auto &P : ForwardRefVals) {
2744 if (isa<BasicBlock>(P.second.first))
2745 continue;
2746 P.second.first->replaceAllUsesWith(
2747 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002748 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002749 }
2750
2751 for (const auto &P : ForwardRefValIDs) {
2752 if (isa<BasicBlock>(P.second.first))
2753 continue;
2754 P.second.first->replaceAllUsesWith(
2755 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002756 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002757 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758}
2759
Chris Lattner3432c622009-10-28 03:39:23 +00002760bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 if (!ForwardRefVals.empty())
2762 return P.Error(ForwardRefVals.begin()->second.second,
2763 "use of undefined value '%" + ForwardRefVals.begin()->first +
2764 "'");
2765 if (!ForwardRefValIDs.empty())
2766 return P.Error(ForwardRefValIDs.begin()->second.second,
2767 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002768 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002769 return false;
2770}
2771
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772/// GetVal - Get a value with the specified name or ID, creating a
2773/// forward reference record if needed. This can return null if the value
2774/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002775Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002776 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002778 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002779
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 // If this is a forward reference for the value, see if we already created a
2781 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002782 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002783 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 if (I != ForwardRefVals.end())
2785 Val = I->second.first;
2786 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002789 if (Val)
2790 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002791
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002793 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002795 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797
Chris Lattnerac161bf2009-01-02 07:01:27 +00002798 // Otherwise, create a new forward reference for this value and remember it.
2799 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002800 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002801 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002802 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002803 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002804 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002805
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2807 return FwdVal;
2808}
2809
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002810Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2811 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002812 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002813 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002814
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 // If this is a forward reference for the value, see if we already created a
2816 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002817 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002818 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002819 if (I != ForwardRefValIDs.end())
2820 Val = I->second.first;
2821 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002822
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002824 if (Val)
2825 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002827 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002829 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002831
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 // Otherwise, create a new forward reference for this value and remember it.
2833 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002834 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002835 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002836 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002837 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002838 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002839
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2841 return FwdVal;
2842}
2843
2844/// SetInstName - After an instruction is parsed and inserted into its
2845/// basic block, this installs its name.
2846bool LLParser::PerFunctionState::SetInstName(int NameID,
2847 const std::string &NameStr,
2848 LocTy NameLoc, Instruction *Inst) {
2849 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002850 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 if (NameID != -1 || !NameStr.empty())
2852 return P.Error(NameLoc, "instructions returning void cannot have a name");
2853 return false;
2854 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002855
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 // If this was a numbered instruction, verify that the instruction is the
2857 // expected value and resolve any forward references.
2858 if (NameStr.empty()) {
2859 // If neither a name nor an ID was specified, just use the next ID.
2860 if (NameID == -1)
2861 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002862
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 if (unsigned(NameID) != NumberedVals.size())
2864 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002865 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002866
David Blaikie9ebdc692015-09-21 21:07:50 +00002867 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002869 Value *Sentinel = FI->second.first;
2870 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002871 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002872 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002873
2874 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002875 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 ForwardRefValIDs.erase(FI);
2877 }
2878
2879 NumberedVals.push_back(Inst);
2880 return false;
2881 }
2882
2883 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002884 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002886 Value *Sentinel = FI->second.first;
2887 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002888 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002889 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002890
2891 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002892 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 ForwardRefVals.erase(FI);
2894 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895
Chris Lattnerac161bf2009-01-02 07:01:27 +00002896 // Set the name on the instruction.
2897 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002898
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002899 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002900 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 NameStr + "'");
2902 return false;
2903}
2904
2905/// GetBB - Get a basic block with the specified name or ID, creating a
2906/// forward reference record if needed.
2907BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2908 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002909 return dyn_cast_or_null<BasicBlock>(
2910 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002911}
2912
2913BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002914 return dyn_cast_or_null<BasicBlock>(
2915 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002916}
2917
2918/// DefineBB - Define the specified basic block, which is either named or
2919/// unnamed. If there is an error, this returns null otherwise it returns
2920/// the block being defined.
2921BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2922 LocTy Loc) {
2923 BasicBlock *BB;
2924 if (Name.empty())
2925 BB = GetBB(NumberedVals.size(), Loc);
2926 else
2927 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002928 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002929
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 // Move the block to the end of the function. Forward ref'd blocks are
2931 // inserted wherever they happen to be referenced.
2932 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002933
Chris Lattnerac161bf2009-01-02 07:01:27 +00002934 // Remove the block from forward ref sets.
2935 if (Name.empty()) {
2936 ForwardRefValIDs.erase(NumberedVals.size());
2937 NumberedVals.push_back(BB);
2938 } else {
2939 // BB forward references are already in the function symbol table.
2940 ForwardRefVals.erase(Name);
2941 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942
Chris Lattnerac161bf2009-01-02 07:01:27 +00002943 return BB;
2944}
2945
2946//===----------------------------------------------------------------------===//
2947// Constants.
2948//===----------------------------------------------------------------------===//
2949
2950/// ParseValID - Parse an abstract value that doesn't necessarily have a
2951/// type implied. For example, if we parse "4" we don't know what integer type
2952/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002953/// sanity. PFS is used to convert function-local operands of metadata (since
2954/// metadata operands are not just parsed here but also converted to values).
2955/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002956bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002957 ID.Loc = Lex.getLoc();
2958 switch (Lex.getKind()) {
2959 default: return TokError("expected value token");
2960 case lltok::GlobalID: // @42
2961 ID.UIntVal = Lex.getUIntVal();
2962 ID.Kind = ValID::t_GlobalID;
2963 break;
2964 case lltok::GlobalVar: // @foo
2965 ID.StrVal = Lex.getStrVal();
2966 ID.Kind = ValID::t_GlobalName;
2967 break;
2968 case lltok::LocalVarID: // %42
2969 ID.UIntVal = Lex.getUIntVal();
2970 ID.Kind = ValID::t_LocalID;
2971 break;
2972 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002973 ID.StrVal = Lex.getStrVal();
2974 ID.Kind = ValID::t_LocalName;
2975 break;
2976 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002977 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 ID.Kind = ValID::t_APSInt;
2979 break;
2980 case lltok::APFloat:
2981 ID.APFloatVal = Lex.getAPFloatVal();
2982 ID.Kind = ValID::t_APFloat;
2983 break;
2984 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002985 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 ID.Kind = ValID::t_Constant;
2987 break;
2988 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002989 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002990 ID.Kind = ValID::t_Constant;
2991 break;
2992 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2993 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2994 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002995 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002996
Chris Lattnerac161bf2009-01-02 07:01:27 +00002997 case lltok::lbrace: {
2998 // ValID ::= '{' ConstVector '}'
2999 Lex.Lex();
3000 SmallVector<Constant*, 16> Elts;
3001 if (ParseGlobalValueVector(Elts) ||
3002 ParseToken(lltok::rbrace, "expected end of struct constant"))
3003 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003004
David Blaikieadbda4b2015-08-03 20:08:41 +00003005 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003006 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00003007 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3008 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003009 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003010 return false;
3011 }
3012 case lltok::less: {
3013 // ValID ::= '<' ConstVector '>' --> Vector.
3014 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3015 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00003016 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003017
Chris Lattnerac161bf2009-01-02 07:01:27 +00003018 SmallVector<Constant*, 16> Elts;
3019 LocTy FirstEltLoc = Lex.getLoc();
3020 if (ParseGlobalValueVector(Elts) ||
3021 (isPackedStruct &&
3022 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3023 ParseToken(lltok::greater, "expected end of constant"))
3024 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003025
Chris Lattnerac161bf2009-01-02 07:01:27 +00003026 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00003027 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3028 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3029 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003030 ID.UIntVal = Elts.size();
3031 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 return false;
3033 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003034
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 if (Elts.empty())
3036 return Error(ID.Loc, "constant vector must not be empty");
3037
Duncan Sands9dff9be2010-02-15 16:12:20 +00003038 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003039 !Elts[0]->getType()->isFloatingPointTy() &&
3040 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003042 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003043
Chris Lattnerac161bf2009-01-02 07:01:27 +00003044 // Verify that all the vector elements have the same type.
3045 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3046 if (Elts[i]->getType() != Elts[0]->getType())
3047 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003048 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003049 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003050
Chris Lattner69229312011-02-15 00:14:00 +00003051 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 ID.Kind = ValID::t_Constant;
3053 return false;
3054 }
3055 case lltok::lsquare: { // Array Constant
3056 Lex.Lex();
3057 SmallVector<Constant*, 16> Elts;
3058 LocTy FirstEltLoc = Lex.getLoc();
3059 if (ParseGlobalValueVector(Elts) ||
3060 ParseToken(lltok::rsquare, "expected end of array constant"))
3061 return true;
3062
3063 // Handle empty element.
3064 if (Elts.empty()) {
3065 // Use undef instead of an array because it's inconvenient to determine
3066 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003067 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 return false;
3069 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003070
Chris Lattnerac161bf2009-01-02 07:01:27 +00003071 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003072 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003073 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003074
Owen Anderson4056ca92009-07-29 22:17:13 +00003075 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003076
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003078 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 if (Elts[i]->getType() != Elts[0]->getType())
3080 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003081 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003082 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084
Jay Foad83be3612011-06-22 09:24:39 +00003085 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 ID.Kind = ValID::t_Constant;
3087 return false;
3088 }
3089 case lltok::kw_c: // c "foo"
3090 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003091 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3092 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3094 ID.Kind = ValID::t_Constant;
3095 return false;
3096
3097 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003098 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3099 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003100 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003101 Lex.Lex();
3102 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003103 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003104 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003105 ParseStringConstant(ID.StrVal) ||
3106 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003107 ParseToken(lltok::StringConstant, "expected constraint string"))
3108 return true;
3109 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003110 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003111 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112 ID.Kind = ValID::t_InlineAsm;
3113 return false;
3114 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003115
Chris Lattner3432c622009-10-28 03:39:23 +00003116 case lltok::kw_blockaddress: {
3117 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3118 Lex.Lex();
3119
3120 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003121
Chris Lattner3432c622009-10-28 03:39:23 +00003122 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3123 ParseValID(Fn) ||
3124 ParseToken(lltok::comma, "expected comma in block address expression")||
3125 ParseValID(Label) ||
3126 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3127 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003128
Chris Lattner3432c622009-10-28 03:39:23 +00003129 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3130 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003131 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003132 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003133
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003134 // Try to find the function (but skip it if it's forward-referenced).
3135 GlobalValue *GV = nullptr;
3136 if (Fn.Kind == ValID::t_GlobalID) {
3137 if (Fn.UIntVal < NumberedVals.size())
3138 GV = NumberedVals[Fn.UIntVal];
3139 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3140 GV = M->getNamedValue(Fn.StrVal);
3141 }
3142 Function *F = nullptr;
3143 if (GV) {
3144 // Confirm that it's actually a function with a definition.
3145 if (!isa<Function>(GV))
3146 return Error(Fn.Loc, "expected function name in blockaddress");
3147 F = cast<Function>(GV);
3148 if (F->isDeclaration())
3149 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3150 }
3151
3152 if (!F) {
3153 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003154 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003155 ForwardRefBlockAddresses.insert(std::make_pair(
3156 std::move(Fn),
3157 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003158 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3159 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003160 if (!FwdRef)
3161 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3162 GlobalValue::InternalLinkage, nullptr, "");
3163 ID.ConstantVal = FwdRef;
3164 ID.Kind = ValID::t_Constant;
3165 return false;
3166 }
3167
3168 // We found the function; now find the basic block. Don't use PFS, since we
3169 // might be inside a constant expression.
3170 BasicBlock *BB;
3171 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3172 if (Label.Kind == ValID::t_LocalID)
3173 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3174 else
3175 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3176 if (!BB)
3177 return Error(Label.Loc, "referenced value is not a basic block");
3178 } else {
3179 if (Label.Kind == ValID::t_LocalID)
3180 return Error(Label.Loc, "cannot take address of numeric label after "
3181 "the function is defined");
3182 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003183 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003184 if (!BB)
3185 return Error(Label.Loc, "referenced value is not a basic block");
3186 }
3187
3188 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003189 ID.Kind = ValID::t_Constant;
3190 return false;
3191 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003192
Chris Lattnerac161bf2009-01-02 07:01:27 +00003193 case lltok::kw_trunc:
3194 case lltok::kw_zext:
3195 case lltok::kw_sext:
3196 case lltok::kw_fptrunc:
3197 case lltok::kw_fpext:
3198 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003199 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 case lltok::kw_uitofp:
3201 case lltok::kw_sitofp:
3202 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003203 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003204 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003205 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003206 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003207 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 Constant *SrcVal;
3209 Lex.Lex();
3210 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3211 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003212 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 ParseType(DestTy) ||
3214 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3215 return true;
3216 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3217 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003218 getTypeString(SrcVal->getType()) + "' to '" +
3219 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003220 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003221 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003222 ID.Kind = ValID::t_Constant;
3223 return false;
3224 }
3225 case lltok::kw_extractvalue: {
3226 Lex.Lex();
3227 Constant *Val;
3228 SmallVector<unsigned, 4> Indices;
3229 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3230 ParseGlobalTypeAndValue(Val) ||
3231 ParseIndexList(Indices) ||
3232 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3233 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003234
Chris Lattner392be582010-02-12 20:49:41 +00003235 if (!Val->getType()->isAggregateType())
3236 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003237 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003238 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003239 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003240 ID.Kind = ValID::t_Constant;
3241 return false;
3242 }
3243 case lltok::kw_insertvalue: {
3244 Lex.Lex();
3245 Constant *Val0, *Val1;
3246 SmallVector<unsigned, 4> Indices;
3247 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3248 ParseGlobalTypeAndValue(Val0) ||
3249 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3250 ParseGlobalTypeAndValue(Val1) ||
3251 ParseIndexList(Indices) ||
3252 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3253 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003254 if (!Val0->getType()->isAggregateType())
3255 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003256 Type *IndexedType =
3257 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3258 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003259 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003260 if (IndexedType != Val1->getType())
3261 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3262 getTypeString(Val1->getType()) +
3263 "' instead of '" + getTypeString(IndexedType) +
3264 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003265 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003266 ID.Kind = ValID::t_Constant;
3267 return false;
3268 }
3269 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003270 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003271 unsigned PredVal, Opc = Lex.getUIntVal();
3272 Constant *Val0, *Val1;
3273 Lex.Lex();
3274 if (ParseCmpPredicate(PredVal, Opc) ||
3275 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3276 ParseGlobalTypeAndValue(Val0) ||
3277 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3278 ParseGlobalTypeAndValue(Val1) ||
3279 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3280 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003281
Chris Lattnerac161bf2009-01-02 07:01:27 +00003282 if (Val0->getType() != Val1->getType())
3283 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003284
Chris Lattnerac161bf2009-01-02 07:01:27 +00003285 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003286
Chris Lattnerac161bf2009-01-02 07:01:27 +00003287 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003288 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003289 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003290 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003291 } else {
3292 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003293 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003294 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003295 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003296 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003297 }
3298 ID.Kind = ValID::t_Constant;
3299 return false;
3300 }
Cameron McInallycbde0d92018-11-13 18:15:47 +00003301
3302 // Unary Operators.
3303 case lltok::kw_fneg: {
3304 unsigned Opc = Lex.getUIntVal();
3305 Constant *Val;
3306 Lex.Lex();
3307 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3308 ParseGlobalTypeAndValue(Val) ||
3309 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3310 return true;
3311
3312 // Check that the type is valid for the operator.
3313 switch (Opc) {
3314 case Instruction::FNeg:
3315 if (!Val->getType()->isFPOrFPVectorTy())
3316 return Error(ID.Loc, "constexpr requires fp operands");
3317 break;
3318 default: llvm_unreachable("Unknown unary operator!");
3319 }
3320 unsigned Flags = 0;
3321 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3322 ID.ConstantVal = C;
3323 ID.Kind = ValID::t_Constant;
3324 return false;
3325 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003326 // Binary Operators.
3327 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003328 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003329 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003330 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003331 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003332 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003333 case lltok::kw_udiv:
3334 case lltok::kw_sdiv:
3335 case lltok::kw_fdiv:
3336 case lltok::kw_urem:
3337 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003338 case lltok::kw_frem:
3339 case lltok::kw_shl:
3340 case lltok::kw_lshr:
3341 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003342 bool NUW = false;
3343 bool NSW = false;
3344 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345 unsigned Opc = Lex.getUIntVal();
3346 Constant *Val0, *Val1;
3347 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003348 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003349 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3350 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003351 if (EatIfPresent(lltok::kw_nuw))
3352 NUW = true;
3353 if (EatIfPresent(lltok::kw_nsw)) {
3354 NSW = true;
3355 if (EatIfPresent(lltok::kw_nuw))
3356 NUW = true;
3357 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003358 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3359 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003360 if (EatIfPresent(lltok::kw_exact))
3361 Exact = true;
3362 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003363 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3364 ParseGlobalTypeAndValue(Val0) ||
3365 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3366 ParseGlobalTypeAndValue(Val1) ||
3367 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3368 return true;
3369 if (Val0->getType() != Val1->getType())
3370 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003371 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003372 if (NUW)
3373 return Error(ModifierLoc, "nuw only applies to integer operations");
3374 if (NSW)
3375 return Error(ModifierLoc, "nsw only applies to integer operations");
3376 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003377 // Check that the type is valid for the operator.
3378 switch (Opc) {
3379 case Instruction::Add:
3380 case Instruction::Sub:
3381 case Instruction::Mul:
3382 case Instruction::UDiv:
3383 case Instruction::SDiv:
3384 case Instruction::URem:
3385 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003386 case Instruction::Shl:
3387 case Instruction::AShr:
3388 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003389 if (!Val0->getType()->isIntOrIntVectorTy())
3390 return Error(ID.Loc, "constexpr requires integer operands");
3391 break;
3392 case Instruction::FAdd:
3393 case Instruction::FSub:
3394 case Instruction::FMul:
3395 case Instruction::FDiv:
3396 case Instruction::FRem:
3397 if (!Val0->getType()->isFPOrFPVectorTy())
3398 return Error(ID.Loc, "constexpr requires fp operands");
3399 break;
3400 default: llvm_unreachable("Unknown binary operator!");
3401 }
Dan Gohman1b849082009-09-07 23:54:19 +00003402 unsigned Flags = 0;
3403 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3404 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003405 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003406 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003407 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003408 ID.Kind = ValID::t_Constant;
3409 return false;
3410 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003411
Chris Lattnerac161bf2009-01-02 07:01:27 +00003412 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003413 case lltok::kw_and:
3414 case lltok::kw_or:
3415 case lltok::kw_xor: {
3416 unsigned Opc = Lex.getUIntVal();
3417 Constant *Val0, *Val1;
3418 Lex.Lex();
3419 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3420 ParseGlobalTypeAndValue(Val0) ||
3421 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3422 ParseGlobalTypeAndValue(Val1) ||
3423 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3424 return true;
3425 if (Val0->getType() != Val1->getType())
3426 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003427 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003428 return Error(ID.Loc,
3429 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003430 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003431 ID.Kind = ValID::t_Constant;
3432 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003433 }
3434
Chris Lattnerac161bf2009-01-02 07:01:27 +00003435 case lltok::kw_getelementptr:
3436 case lltok::kw_shufflevector:
3437 case lltok::kw_insertelement:
3438 case lltok::kw_extractelement:
3439 case lltok::kw_select: {
3440 unsigned Opc = Lex.getUIntVal();
3441 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003442 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003443 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003444 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003445
Dan Gohman1639c392009-07-27 21:53:46 +00003446 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003447 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003448
3449 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3450 return true;
3451
3452 LocTy ExplicitTypeLoc = Lex.getLoc();
3453 if (Opc == Instruction::GetElementPtr) {
3454 if (ParseType(Ty) ||
3455 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3456 return true;
3457 }
3458
Peter Collingbourned93620b2016-11-10 22:34:55 +00003459 Optional<unsigned> InRangeOp;
3460 if (ParseGlobalValueVector(
3461 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003462 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3463 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003464
Chris Lattnerac161bf2009-01-02 07:01:27 +00003465 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003466 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003467 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003468 return Error(ID.Loc, "base of getelementptr must be a pointer");
3469
3470 Type *BaseType = Elts[0]->getType();
3471 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003472 if (Ty != BasePointerType->getElementType())
3473 return Error(
3474 ExplicitTypeLoc,
3475 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003476
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003477 unsigned GEPWidth =
3478 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3479
Jay Foaded8db7d2011-07-21 14:31:17 +00003480 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003481 for (Constant *Val : Indices) {
3482 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003483 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003484 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003485 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003486 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003487 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003488 return Error(
3489 ID.Loc,
3490 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003491 // GEPWidth may have been unknown because the base is a scalar,
3492 // but it is known now.
3493 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003494 }
3495 }
3496
Craig Toppere3dcce92015-08-01 22:20:21 +00003497 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003498 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003499 return Error(ID.Loc, "base element of getelementptr must be sized");
3500
David Blaikie4a2e73b2015-04-02 18:55:32 +00003501 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003502 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003503
3504 if (InRangeOp) {
3505 if (*InRangeOp == 0)
3506 return Error(ID.Loc,
3507 "inrange keyword may not appear on pointer operand");
3508 --*InRangeOp;
3509 }
3510
3511 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3512 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003513 } else if (Opc == Instruction::Select) {
3514 if (Elts.size() != 3)
3515 return Error(ID.Loc, "expected three operands to select");
3516 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3517 Elts[2]))
3518 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003519 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003520 } else if (Opc == Instruction::ShuffleVector) {
3521 if (Elts.size() != 3)
3522 return Error(ID.Loc, "expected three operands to shufflevector");
3523 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3524 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003525 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003526 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003527 } else if (Opc == Instruction::ExtractElement) {
3528 if (Elts.size() != 2)
3529 return Error(ID.Loc, "expected two operands to extractelement");
3530 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3531 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003532 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003533 } else {
3534 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3535 if (Elts.size() != 3)
3536 return Error(ID.Loc, "expected three operands to insertelement");
3537 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3538 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003539 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003540 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003541 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003542
Chris Lattnerac161bf2009-01-02 07:01:27 +00003543 ID.Kind = ValID::t_Constant;
3544 return false;
3545 }
3546 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003547
Chris Lattnerac161bf2009-01-02 07:01:27 +00003548 Lex.Lex();
3549 return false;
3550}
3551
3552/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003553bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003554 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003555 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003556 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003557 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003558 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003559 if (V && !(C = dyn_cast<Constant>(V)))
3560 return Error(ID.Loc, "global values must be constants");
3561 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003562}
3563
Victor Hernandez9d75c962010-01-11 22:31:58 +00003564bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003565 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003566 return ParseType(Ty) ||
3567 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003568}
3569
Rafael Espindola83a362c2015-01-06 22:55:16 +00003570bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003571 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003572
3573 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003574 if (!EatIfPresent(lltok::kw_comdat))
3575 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003576
3577 if (EatIfPresent(lltok::lparen)) {
3578 if (Lex.getKind() != lltok::ComdatVar)
3579 return TokError("expected comdat variable");
3580 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3581 Lex.Lex();
3582 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3583 return true;
3584 } else {
3585 if (GlobalName.empty())
3586 return TokError("comdat cannot be unnamed");
3587 C = getComdat(GlobalName, KwLoc);
3588 }
3589
David Majnemerdad0a642014-06-27 18:19:56 +00003590 return false;
3591}
3592
Victor Hernandez9d75c962010-01-11 22:31:58 +00003593/// ParseGlobalValueVector
3594/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003595/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3596bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3597 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003598 // Empty list.
3599 if (Lex.getKind() == lltok::rbrace ||
3600 Lex.getKind() == lltok::rsquare ||
3601 Lex.getKind() == lltok::greater ||
3602 Lex.getKind() == lltok::rparen)
3603 return false;
3604
Peter Collingbourned93620b2016-11-10 22:34:55 +00003605 do {
3606 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3607 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003608
Peter Collingbourned93620b2016-11-10 22:34:55 +00003609 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003610 if (ParseGlobalTypeAndValue(C)) return true;
3611 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003612 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003613
3614 return false;
3615}
3616
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003617bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003618 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003619 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003620 return true;
3621
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003622 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003623 return false;
3624}
3625
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003626/// MDNode:
3627/// ::= !{ ... }
3628/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003629/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003630bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003631 if (Lex.getKind() == lltok::MetadataVar)
3632 return ParseSpecializedMDNode(N);
3633
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003634 return ParseToken(lltok::exclaim, "expected '!' here") ||
3635 ParseMDNodeTail(N);
3636}
3637
3638bool LLParser::ParseMDNodeTail(MDNode *&N) {
3639 // !{ ... }
3640 if (Lex.getKind() == lltok::lbrace)
3641 return ParseMDTuple(N);
3642
3643 // !42
3644 return ParseMDNodeID(N);
3645}
3646
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003647namespace {
3648
3649/// Structure to represent an optional metadata field.
3650template <class FieldTy> struct MDFieldImpl {
3651 typedef MDFieldImpl ImplTy;
3652 FieldTy Val;
3653 bool Seen;
3654
3655 void assign(FieldTy Val) {
3656 Seen = true;
3657 this->Val = std::move(Val);
3658 }
3659
3660 explicit MDFieldImpl(FieldTy Default)
3661 : Val(std::move(Default)), Seen(false) {}
3662};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003663
Sander de Smalenfdf40912018-01-24 09:56:07 +00003664/// Structure to represent an optional metadata field that
3665/// can be of either type (A or B) and encapsulates the
3666/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3667/// to reimplement the specifics for representing each Field.
3668template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3669 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3670 FieldTypeA A;
3671 FieldTypeB B;
3672 bool Seen;
3673
3674 enum {
3675 IsInvalid = 0,
3676 IsTypeA = 1,
3677 IsTypeB = 2
3678 } WhatIs;
3679
3680 void assign(FieldTypeA A) {
3681 Seen = true;
3682 this->A = std::move(A);
3683 WhatIs = IsTypeA;
3684 }
3685
3686 void assign(FieldTypeB B) {
3687 Seen = true;
3688 this->B = std::move(B);
3689 WhatIs = IsTypeB;
3690 }
3691
3692 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3693 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3694 WhatIs(IsInvalid) {}
3695};
3696
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003697struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3698 uint64_t Max;
3699
3700 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3701 : ImplTy(Default), Max(Max) {}
3702};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003703
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003704struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003705 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003706};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003707
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003708struct ColumnField : public MDUnsignedField {
3709 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3710};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003711
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003712struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003713 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003714 DwarfTagField(dwarf::Tag DefaultTag)
3715 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003716};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003717
Amjad Abouda9bcf162015-12-10 12:56:35 +00003718struct DwarfMacinfoTypeField : public MDUnsignedField {
3719 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3720 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3721 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3722};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003723
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003724struct DwarfAttEncodingField : public MDUnsignedField {
3725 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3726};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003727
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003728struct DwarfVirtualityField : public MDUnsignedField {
3729 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3730};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003731
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003732struct DwarfLangField : public MDUnsignedField {
3733 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3734};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003735
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003736struct DwarfCCField : public MDUnsignedField {
3737 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3738};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003739
Adrian Prantlb939a252016-03-31 23:56:58 +00003740struct EmissionKindField : public MDUnsignedField {
3741 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3742};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003743
David Blaikie66cf14d2018-08-16 21:29:55 +00003744struct NameTableKindField : public MDUnsignedField {
3745 NameTableKindField()
3746 : MDUnsignedField(
3747 0, (unsigned)
3748 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3749};
3750
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003751struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3752 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003753};
3754
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00003755struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3756 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3757};
3758
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003759struct MDSignedField : public MDFieldImpl<int64_t> {
3760 int64_t Min;
3761 int64_t Max;
3762
3763 MDSignedField(int64_t Default = 0)
3764 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3765 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3766 : ImplTy(Default), Min(Min), Max(Max) {}
3767};
3768
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003769struct MDBoolField : public MDFieldImpl<bool> {
3770 MDBoolField(bool Default = false) : ImplTy(Default) {}
3771};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003772
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003773struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003774 bool AllowNull;
3775
3776 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003777};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003778
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003779struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3780 MDConstant() : ImplTy(nullptr) {}
3781};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003782
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003783struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003784 bool AllowEmpty;
3785 MDStringField(bool AllowEmpty = true)
3786 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003787};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003788
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003789struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3790 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3791};
3792
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003793struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003794 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3795};
3796
Sander de Smalenfdf40912018-01-24 09:56:07 +00003797struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3798 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3799 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3800
3801 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3802 bool AllowNull = true)
3803 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3804
3805 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3806 bool isMDField() const { return WhatIs == IsTypeB; }
3807 int64_t getMDSignedValue() const {
3808 assert(isMDSignedField() && "Wrong field type");
3809 return A.Val;
3810 }
3811 Metadata *getMDFieldValue() const {
3812 assert(isMDField() && "Wrong field type");
3813 return B.Val;
3814 }
3815};
3816
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003817struct MDSignedOrUnsignedField
3818 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3819 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3820
3821 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3822 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3823 int64_t getMDSignedValue() const {
3824 assert(isMDSignedField() && "Wrong field type");
3825 return A.Val;
3826 }
3827 uint64_t getMDUnsignedValue() const {
3828 assert(isMDUnsignedField() && "Wrong field type");
3829 return B.Val;
3830 }
3831};
3832
Eugene Zelenko1804a772016-08-25 00:45:04 +00003833} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003834
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003835namespace llvm {
3836
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003837template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003838bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003839 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003840 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3841 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003842
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003843 auto &U = Lex.getAPSIntVal();
3844 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003845 return TokError("value for '" + Name + "' too large, limit is " +
3846 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003847 Result.assign(U.getZExtValue());
3848 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003849 Lex.Lex();
3850 return false;
3851}
3852
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003853template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003854bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3855 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3856}
3857template <>
3858bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3859 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3860}
3861
3862template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003863bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3864 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003865 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003866
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003867 if (Lex.getKind() != lltok::DwarfTag)
3868 return TokError("expected DWARF tag");
3869
3870 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3871 if (Tag == dwarf::DW_TAG_invalid)
3872 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003873 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003874
3875 Result.assign(Tag);
3876 Lex.Lex();
3877 return false;
3878}
3879
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003880template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003881bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003882 DwarfMacinfoTypeField &Result) {
3883 if (Lex.getKind() == lltok::APSInt)
3884 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3885
3886 if (Lex.getKind() != lltok::DwarfMacinfo)
3887 return TokError("expected DWARF macinfo type");
3888
3889 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3890 if (Macinfo == dwarf::DW_MACINFO_invalid)
3891 return TokError(
3892 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3893 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3894
3895 Result.assign(Macinfo);
3896 Lex.Lex();
3897 return false;
3898}
3899
3900template <>
3901bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003902 DwarfVirtualityField &Result) {
3903 if (Lex.getKind() == lltok::APSInt)
3904 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3905
3906 if (Lex.getKind() != lltok::DwarfVirtuality)
3907 return TokError("expected DWARF virtuality code");
3908
3909 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003910 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003911 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3912 Lex.getStrVal() + "'");
3913 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3914 Result.assign(Virtuality);
3915 Lex.Lex();
3916 return false;
3917}
3918
3919template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003920bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3921 if (Lex.getKind() == lltok::APSInt)
3922 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3923
3924 if (Lex.getKind() != lltok::DwarfLang)
3925 return TokError("expected DWARF language");
3926
3927 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3928 if (!Lang)
3929 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3930 "'");
3931 assert(Lang <= Result.Max && "Expected valid DWARF language");
3932 Result.assign(Lang);
3933 Lex.Lex();
3934 return false;
3935}
3936
3937template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003938bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3939 if (Lex.getKind() == lltok::APSInt)
3940 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3941
3942 if (Lex.getKind() != lltok::DwarfCC)
3943 return TokError("expected DWARF calling convention");
3944
3945 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3946 if (!CC)
3947 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3948 "'");
3949 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3950 Result.assign(CC);
3951 Lex.Lex();
3952 return false;
3953}
3954
3955template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003956bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3957 if (Lex.getKind() == lltok::APSInt)
3958 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3959
3960 if (Lex.getKind() != lltok::EmissionKind)
3961 return TokError("expected emission kind");
3962
3963 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3964 if (!Kind)
3965 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3966 "'");
3967 assert(*Kind <= Result.Max && "Expected valid emission kind");
3968 Result.assign(*Kind);
3969 Lex.Lex();
3970 return false;
3971}
Fangrui Songf78650a2018-07-30 19:41:25 +00003972
Adrian Prantlb939a252016-03-31 23:56:58 +00003973template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003974bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikie66cf14d2018-08-16 21:29:55 +00003975 NameTableKindField &Result) {
3976 if (Lex.getKind() == lltok::APSInt)
3977 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3978
3979 if (Lex.getKind() != lltok::NameTableKind)
3980 return TokError("expected nameTable kind");
3981
3982 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3983 if (!Kind)
3984 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3985 "'");
3986 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3987 Result.assign((unsigned)*Kind);
3988 Lex.Lex();
3989 return false;
3990}
3991
3992template <>
3993bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003994 DwarfAttEncodingField &Result) {
3995 if (Lex.getKind() == lltok::APSInt)
3996 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3997
3998 if (Lex.getKind() != lltok::DwarfAttEncoding)
3999 return TokError("expected DWARF type attribute encoding");
4000
4001 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4002 if (!Encoding)
4003 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4004 Lex.getStrVal() + "'");
4005 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4006 Result.assign(Encoding);
4007 Lex.Lex();
4008 return false;
4009}
4010
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004011/// DIFlagField
4012/// ::= uint32
4013/// ::= DIFlagVector
4014/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4015template <>
4016bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004017
4018 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004019 auto parseFlag = [&](DINode::DIFlags &Val) {
4020 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4021 uint32_t TempVal = static_cast<uint32_t>(Val);
4022 bool Res = ParseUInt32(TempVal);
4023 Val = static_cast<DINode::DIFlags>(TempVal);
4024 return Res;
4025 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004026
4027 if (Lex.getKind() != lltok::DIFlag)
4028 return TokError("expected debug info flag");
4029
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004030 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004031 if (!Val)
4032 return TokError(Twine("invalid debug info flag flag '") +
4033 Lex.getStrVal() + "'");
4034 Lex.Lex();
4035 return false;
4036 };
4037
4038 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004039 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004040 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004041 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004042 if (parseFlag(Val))
4043 return true;
4044 Combined |= Val;
4045 } while (EatIfPresent(lltok::bar));
4046
4047 Result.assign(Combined);
4048 return false;
4049}
4050
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004051/// DISPFlagField
4052/// ::= uint32
4053/// ::= DISPFlagVector
4054/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4055template <>
4056bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4057
4058 // Parser for a single flag.
4059 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4060 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4061 uint32_t TempVal = static_cast<uint32_t>(Val);
4062 bool Res = ParseUInt32(TempVal);
4063 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4064 return Res;
4065 }
4066
4067 if (Lex.getKind() != lltok::DISPFlag)
4068 return TokError("expected debug info flag");
4069
4070 Val = DISubprogram::getFlag(Lex.getStrVal());
4071 if (!Val)
4072 return TokError(Twine("invalid subprogram debug info flag '") +
4073 Lex.getStrVal() + "'");
4074 Lex.Lex();
4075 return false;
4076 };
4077
4078 // Parse the flags and combine them together.
4079 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4080 do {
4081 DISubprogram::DISPFlags Val;
4082 if (parseFlag(Val))
4083 return true;
4084 Combined |= Val;
4085 } while (EatIfPresent(lltok::bar));
4086
4087 Result.assign(Combined);
4088 return false;
4089}
4090
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004091template <>
4092bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004093 MDSignedField &Result) {
4094 if (Lex.getKind() != lltok::APSInt)
4095 return TokError("expected signed integer");
4096
4097 auto &S = Lex.getAPSIntVal();
4098 if (S < Result.Min)
4099 return TokError("value for '" + Name + "' too small, limit is " +
4100 Twine(Result.Min));
4101 if (S > Result.Max)
4102 return TokError("value for '" + Name + "' too large, limit is " +
4103 Twine(Result.Max));
4104 Result.assign(S.getExtValue());
4105 assert(Result.Val >= Result.Min && "Expected value in range");
4106 assert(Result.Val <= Result.Max && "Expected value in range");
4107 Lex.Lex();
4108 return false;
4109}
4110
4111template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004112bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4113 switch (Lex.getKind()) {
4114 default:
4115 return TokError("expected 'true' or 'false'");
4116 case lltok::kw_true:
4117 Result.assign(true);
4118 break;
4119 case lltok::kw_false:
4120 Result.assign(false);
4121 break;
4122 }
4123 Lex.Lex();
4124 return false;
4125}
4126
4127template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004128bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004129 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004130 if (!Result.AllowNull)
4131 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004132 Lex.Lex();
4133 Result.assign(nullptr);
4134 return false;
4135 }
4136
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004137 Metadata *MD;
4138 if (ParseMetadata(MD, nullptr))
4139 return true;
4140
4141 Result.assign(MD);
4142 return false;
4143}
4144
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004145template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00004146bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4147 MDSignedOrMDField &Result) {
4148 // Try to parse a signed int.
4149 if (Lex.getKind() == lltok::APSInt) {
4150 MDSignedField Res = Result.A;
4151 if (!ParseMDField(Loc, Name, Res)) {
4152 Result.assign(Res);
4153 return false;
4154 }
4155 return true;
4156 }
4157
4158 // Otherwise, try to parse as an MDField.
4159 MDField Res = Result.B;
4160 if (!ParseMDField(Loc, Name, Res)) {
4161 Result.assign(Res);
4162 return false;
4163 }
4164
4165 return true;
4166}
4167
4168template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004169bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4170 MDSignedOrUnsignedField &Result) {
4171 if (Lex.getKind() != lltok::APSInt)
4172 return false;
4173
4174 if (Lex.getAPSIntVal().isSigned()) {
4175 MDSignedField Res = Result.A;
4176 if (ParseMDField(Loc, Name, Res))
4177 return true;
4178 Result.assign(Res);
4179 return false;
4180 }
4181
4182 MDUnsignedField Res = Result.B;
4183 if (ParseMDField(Loc, Name, Res))
4184 return true;
4185 Result.assign(Res);
4186 return false;
4187}
4188
4189template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004190bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004191 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004192 std::string S;
4193 if (ParseStringConstant(S))
4194 return true;
4195
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004196 if (!Result.AllowEmpty && S.empty())
4197 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4198
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004199 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004200 return false;
4201}
4202
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004203template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004204bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4205 SmallVector<Metadata *, 4> MDs;
4206 if (ParseMDNodeVector(MDs))
4207 return true;
4208
4209 Result.assign(std::move(MDs));
4210 return false;
4211}
4212
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004213template <>
4214bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4215 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004216 Optional<DIFile::ChecksumKind> CSKind =
4217 DIFile::getChecksumKind(Lex.getStrVal());
4218
4219 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004220 return TokError(
4221 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4222
Scott Linder71603842018-02-12 19:45:54 +00004223 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004224 Lex.Lex();
4225 return false;
4226}
4227
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004228} // end namespace llvm
4229
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004230template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004231bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004232 do {
4233 if (Lex.getKind() != lltok::LabelStr)
4234 return TokError("expected field label here");
4235
4236 if (parseField())
4237 return true;
4238 } while (EatIfPresent(lltok::comma));
4239
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004240 return false;
4241}
4242
4243template <class ParserTy>
4244bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4245 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4246 Lex.Lex();
4247
4248 if (ParseToken(lltok::lparen, "expected '(' here"))
4249 return true;
4250 if (Lex.getKind() != lltok::rparen)
4251 if (ParseMDFieldsImplBody(parseField))
4252 return true;
4253
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004254 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004255 return ParseToken(lltok::rparen, "expected ')' here");
4256}
4257
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004258template <class FieldTy>
4259bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4260 if (Result.Seen)
4261 return TokError("field '" + Name + "' cannot be specified more than once");
4262
4263 LocTy Loc = Lex.getLoc();
4264 Lex.Lex();
4265 return ParseMDField(Loc, Name, Result);
4266}
4267
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004268bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4269 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004270
4271#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004272 if (Lex.getStrVal() == #CLASS) \
4273 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004274#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004275
4276 return TokError("expected metadata type");
4277}
4278
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004279#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4280#define NOP_FIELD(NAME, TYPE, INIT)
4281#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4282 if (!NAME.Seen) \
4283 return Error(ClosingLoc, "missing required field '" #NAME "'");
4284#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004285 if (Lex.getStrVal() == #NAME) \
4286 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004287#define PARSE_MD_FIELDS() \
4288 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4289 do { \
4290 LocTy ClosingLoc; \
4291 if (ParseMDFieldsImpl([&]() -> bool { \
4292 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4293 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4294 }, ClosingLoc)) \
4295 return true; \
4296 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4297 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004298#define GET_OR_DISTINCT(CLASS, ARGS) \
4299 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004300
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004301/// ParseDILocationFields:
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004302/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4303/// isImplicitCode: true)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004304bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004305#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004306 OPTIONAL(line, LineField, ); \
4307 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004308 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004309 OPTIONAL(inlinedAt, MDField, ); \
4310 OPTIONAL(isImplicitCode, MDBoolField, (false));
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004311 PARSE_MD_FIELDS();
4312#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004313
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004314 Result =
4315 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4316 inlinedAt.Val, isImplicitCode.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004317 return false;
4318}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004319
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004320/// ParseGenericDINode:
4321/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4322bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004323#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004324 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004325 OPTIONAL(header, MDStringField, ); \
4326 OPTIONAL(operands, MDFieldList, );
4327 PARSE_MD_FIELDS();
4328#undef VISIT_MD_FIELDS
4329
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004330 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004331 (Context, tag.Val, header.Val, operands.Val));
4332 return false;
4333}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004334
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004335/// ParseDISubrange:
4336/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004337/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004338bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004339#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004340 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004341 OPTIONAL(lowerBound, MDSignedField, );
4342 PARSE_MD_FIELDS();
4343#undef VISIT_MD_FIELDS
4344
Sander de Smalenfdf40912018-01-24 09:56:07 +00004345 if (count.isMDSignedField())
4346 Result = GET_OR_DISTINCT(
4347 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4348 else if (count.isMDField())
4349 Result = GET_OR_DISTINCT(
4350 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4351 else
4352 return true;
4353
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004354 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004355}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004356
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004357/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004358/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004359bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004360#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004361 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004362 REQUIRED(value, MDSignedOrUnsignedField, ); \
4363 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004364 PARSE_MD_FIELDS();
4365#undef VISIT_MD_FIELDS
4366
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004367 if (isUnsigned.Val && value.isMDSignedField())
4368 return TokError("unsigned enumerator with negative value");
4369
4370 int64_t Value = value.isMDSignedField()
4371 ? value.getMDSignedValue()
4372 : static_cast<int64_t>(value.getMDUnsignedValue());
4373 Result =
4374 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4375
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004376 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004377}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004378
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004379/// ParseDIBasicType:
Adrian Prantl55f42622018-08-14 19:35:34 +00004380/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4381/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004382bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004383#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004384 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004385 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004386 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004387 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantl55f42622018-08-14 19:35:34 +00004388 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4389 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004390 PARSE_MD_FIELDS();
4391#undef VISIT_MD_FIELDS
4392
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004393 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantl55f42622018-08-14 19:35:34 +00004394 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004395 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004396}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004397
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004398/// ParseDIDerivedType:
4399/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004400/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004401/// align: 32, offset: 0, flags: 0, extraData: !3,
4402/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004403bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004404#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4405 REQUIRED(tag, DwarfTagField, ); \
4406 OPTIONAL(name, MDStringField, ); \
4407 OPTIONAL(file, MDField, ); \
4408 OPTIONAL(line, LineField, ); \
4409 OPTIONAL(scope, MDField, ); \
4410 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004411 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004412 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004413 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004414 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004415 OPTIONAL(extraData, MDField, ); \
4416 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004417 PARSE_MD_FIELDS();
4418#undef VISIT_MD_FIELDS
4419
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004420 Optional<unsigned> DWARFAddressSpace;
4421 if (dwarfAddressSpace.Val != UINT32_MAX)
4422 DWARFAddressSpace = dwarfAddressSpace.Val;
4423
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004424 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004425 (Context, tag.Val, name.Val, file.Val, line.Val,
4426 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004427 offset.Val, DWARFAddressSpace, flags.Val,
4428 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004429 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004430}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004431
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004432bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004433#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4434 REQUIRED(tag, DwarfTagField, ); \
4435 OPTIONAL(name, MDStringField, ); \
4436 OPTIONAL(file, MDField, ); \
4437 OPTIONAL(line, LineField, ); \
4438 OPTIONAL(scope, MDField, ); \
4439 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004440 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004441 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004442 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004443 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004444 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004445 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004446 OPTIONAL(vtableHolder, MDField, ); \
4447 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004448 OPTIONAL(identifier, MDStringField, ); \
4449 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004450 PARSE_MD_FIELDS();
4451#undef VISIT_MD_FIELDS
4452
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004453 // If this has an identifier try to build an ODR type.
4454 if (identifier.Val)
4455 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004456 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4457 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4458 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004459 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004460 Result = CT;
4461 return false;
4462 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004463
4464 // Create a new node, and save it in the context if it belongs in the type
4465 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004466 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004467 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004468 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4469 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004470 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4471 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004472 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004473}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004474
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004475bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004476#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004477 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004478 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004479 REQUIRED(types, MDField, );
4480 PARSE_MD_FIELDS();
4481#undef VISIT_MD_FIELDS
4482
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004483 Result = GET_OR_DISTINCT(DISubroutineType,
4484 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004485 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004486}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004487
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004488/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004489/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004490/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004491/// checksum: "000102030405060708090a0b0c0d0e0f",
4492/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004493bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004494 // The default constructed value for checksumkind is required, but will never
4495 // be used, as the parser checks if the field was actually Seen before using
4496 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004497#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4498 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004499 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004500 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004501 OPTIONAL(checksum, MDStringField, ); \
4502 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004503 PARSE_MD_FIELDS();
4504#undef VISIT_MD_FIELDS
4505
Scott Linder71603842018-02-12 19:45:54 +00004506 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4507 if (checksumkind.Seen && checksum.Seen)
4508 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4509 else if (checksumkind.Seen || checksum.Seen)
4510 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4511
Scott Linder16c7bda2018-02-23 23:01:06 +00004512 Optional<MDString *> OptSource;
4513 if (source.Seen)
4514 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004515 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004516 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004517 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004518}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004519
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004520/// ParseDICompileUnit:
4521/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004522/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004523/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004524/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004525/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004526bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004527 if (!IsDistinct)
4528 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4529
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004530#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4531 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004532 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004533 OPTIONAL(producer, MDStringField, ); \
4534 OPTIONAL(isOptimized, MDBoolField, ); \
4535 OPTIONAL(flags, MDStringField, ); \
4536 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4537 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004538 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004539 OPTIONAL(enums, MDField, ); \
4540 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004541 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004542 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004543 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004544 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004545 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004546 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikiebb279112018-11-13 20:08:10 +00004547 OPTIONAL(nameTableKind, NameTableKindField, ); \
4548 OPTIONAL(debugBaseAddress, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004549 PARSE_MD_FIELDS();
4550#undef VISIT_MD_FIELDS
4551
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004552 Result = DICompileUnit::getDistinct(
4553 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4554 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004555 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikiebb279112018-11-13 20:08:10 +00004556 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4557 debugBaseAddress.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004558 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004559}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004560
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004561/// ParseDISubprogram:
4562/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004563/// file: !1, line: 7, type: !2, isLocal: false,
4564/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004565/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004566/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004567/// spFlags: 10, isOptimized: false, templateParams: !4,
4568/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004569bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004570 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004571#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4572 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004573 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004574 OPTIONAL(linkageName, MDStringField, ); \
4575 OPTIONAL(file, MDField, ); \
4576 OPTIONAL(line, LineField, ); \
4577 OPTIONAL(type, MDField, ); \
4578 OPTIONAL(isLocal, MDBoolField, ); \
4579 OPTIONAL(isDefinition, MDBoolField, (true)); \
4580 OPTIONAL(scopeLine, LineField, ); \
4581 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004582 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004583 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004584 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004585 OPTIONAL(flags, DIFlagField, ); \
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004586 OPTIONAL(spFlags, DISPFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004587 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004588 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004589 OPTIONAL(templateParams, MDField, ); \
4590 OPTIONAL(declaration, MDField, ); \
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004591 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004592 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004593 PARSE_MD_FIELDS();
4594#undef VISIT_MD_FIELDS
4595
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004596 // An explicit spFlags field takes precedence over individual fields in
4597 // older IR versions.
4598 DISubprogram::DISPFlags SPFlags =
4599 spFlags.Seen ? spFlags.Val
4600 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4601 isOptimized.Val, virtuality.Val);
4602 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004603 return Lex.Error(
4604 Loc,
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004605 "missing 'distinct', required for !DISubprogram that is a Definition");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004606 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004607 DISubprogram,
4608 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
Paul Robinsoncda54212018-11-19 18:29:28 +00004609 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4610 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004611 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004612 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004613}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004614
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004615/// ParseDILexicalBlock:
4616/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4617bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004618#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004619 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004620 OPTIONAL(file, MDField, ); \
4621 OPTIONAL(line, LineField, ); \
4622 OPTIONAL(column, ColumnField, );
4623 PARSE_MD_FIELDS();
4624#undef VISIT_MD_FIELDS
4625
4626 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004627 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004628 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004629}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004630
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004631/// ParseDILexicalBlockFile:
4632/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4633bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004634#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004635 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004636 OPTIONAL(file, MDField, ); \
4637 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4638 PARSE_MD_FIELDS();
4639#undef VISIT_MD_FIELDS
4640
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004641 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004642 (Context, scope.Val, file.Val, discriminator.Val));
4643 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004644}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004645
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004646/// ParseDINamespace:
4647/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4648bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004649#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4650 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004651 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004652 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004653 PARSE_MD_FIELDS();
4654#undef VISIT_MD_FIELDS
4655
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004656 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004657 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004658 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004659}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004660
Amjad Abouda9bcf162015-12-10 12:56:35 +00004661/// ParseDIMacro:
4662/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4663bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4664#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4665 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004666 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004667 REQUIRED(name, MDStringField, ); \
4668 OPTIONAL(value, MDStringField, );
4669 PARSE_MD_FIELDS();
4670#undef VISIT_MD_FIELDS
4671
4672 Result = GET_OR_DISTINCT(DIMacro,
4673 (Context, type.Val, line.Val, name.Val, value.Val));
4674 return false;
4675}
4676
4677/// ParseDIMacroFile:
4678/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4679bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4680#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4681 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004682 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004683 REQUIRED(file, MDField, ); \
4684 OPTIONAL(nodes, MDField, );
4685 PARSE_MD_FIELDS();
4686#undef VISIT_MD_FIELDS
4687
4688 Result = GET_OR_DISTINCT(DIMacroFile,
4689 (Context, type.Val, line.Val, file.Val, nodes.Val));
4690 return false;
4691}
4692
Adrian Prantlab1243f2015-06-29 23:03:47 +00004693/// ParseDIModule:
4694/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4695/// includePath: "/usr/include", isysroot: "/")
4696bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4698 REQUIRED(scope, MDField, ); \
4699 REQUIRED(name, MDStringField, ); \
4700 OPTIONAL(configMacros, MDStringField, ); \
4701 OPTIONAL(includePath, MDStringField, ); \
4702 OPTIONAL(isysroot, MDStringField, );
4703 PARSE_MD_FIELDS();
4704#undef VISIT_MD_FIELDS
4705
4706 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4707 configMacros.Val, includePath.Val, isysroot.Val));
4708 return false;
4709}
4710
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004711/// ParseDITemplateTypeParameter:
4712/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4713bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004714#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004715 OPTIONAL(name, MDStringField, ); \
4716 REQUIRED(type, MDField, );
4717 PARSE_MD_FIELDS();
4718#undef VISIT_MD_FIELDS
4719
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004720 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004721 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004722 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004723}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004724
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004725/// ParseDITemplateValueParameter:
4726/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004727/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004728bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004729#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004730 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004731 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004732 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004733 REQUIRED(value, MDField, );
4734 PARSE_MD_FIELDS();
4735#undef VISIT_MD_FIELDS
4736
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004737 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004738 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004739 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004740}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004741
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004742/// ParseDIGlobalVariable:
4743/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004744/// file: !1, line: 7, type: !2, isLocal: false,
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004745/// isDefinition: true, templateParams: !3,
4746/// declaration: !4, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004747bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004748#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004749 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004750 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004751 OPTIONAL(linkageName, MDStringField, ); \
4752 OPTIONAL(file, MDField, ); \
4753 OPTIONAL(line, LineField, ); \
4754 OPTIONAL(type, MDField, ); \
4755 OPTIONAL(isLocal, MDBoolField, ); \
4756 OPTIONAL(isDefinition, MDBoolField, (true)); \
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004757 OPTIONAL(templateParams, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004758 OPTIONAL(declaration, MDField, ); \
4759 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004760 PARSE_MD_FIELDS();
4761#undef VISIT_MD_FIELDS
4762
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004763 Result =
4764 GET_OR_DISTINCT(DIGlobalVariable,
4765 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4766 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4767 declaration.Val, templateParams.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004768 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004769}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004770
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004771/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004772/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004773/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4774/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004775/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004776/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4777/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004778bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004779#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004780 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004781 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004782 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004783 OPTIONAL(file, MDField, ); \
4784 OPTIONAL(line, LineField, ); \
4785 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004786 OPTIONAL(flags, DIFlagField, ); \
4787 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004788 PARSE_MD_FIELDS();
4789#undef VISIT_MD_FIELDS
4790
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004791 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004792 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004793 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004794 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004795}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004796
Shiva Chen2c864552018-05-09 02:40:45 +00004797/// ParseDILabel:
4798/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4799bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4800#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4801 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4802 REQUIRED(name, MDStringField, ); \
4803 REQUIRED(file, MDField, ); \
4804 REQUIRED(line, LineField, );
4805 PARSE_MD_FIELDS();
4806#undef VISIT_MD_FIELDS
4807
4808 Result = GET_OR_DISTINCT(DILabel,
4809 (Context, scope.Val, name.Val, file.Val, line.Val));
4810 return false;
4811}
4812
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004813/// ParseDIExpression:
4814/// ::= !DIExpression(0, 7, -1)
4815bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004816 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4817 Lex.Lex();
4818
4819 if (ParseToken(lltok::lparen, "expected '(' here"))
4820 return true;
4821
4822 SmallVector<uint64_t, 8> Elements;
4823 if (Lex.getKind() != lltok::rparen)
4824 do {
4825 if (Lex.getKind() == lltok::DwarfOp) {
4826 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4827 Lex.Lex();
4828 Elements.push_back(Op);
4829 continue;
4830 }
4831 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4832 }
4833
4834 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4835 return TokError("expected unsigned integer");
4836
4837 auto &U = Lex.getAPSIntVal();
4838 if (U.ugt(UINT64_MAX))
4839 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4840 Elements.push_back(U.getZExtValue());
4841 Lex.Lex();
4842 } while (EatIfPresent(lltok::comma));
4843
4844 if (ParseToken(lltok::rparen, "expected ')' here"))
4845 return true;
4846
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004847 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004848 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004849}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004850
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004851/// ParseDIGlobalVariableExpression:
4852/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4853bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4854 bool IsDistinct) {
4855#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4856 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004857 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004858 PARSE_MD_FIELDS();
4859#undef VISIT_MD_FIELDS
4860
4861 Result =
4862 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4863 return false;
4864}
4865
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004866/// ParseDIObjCProperty:
4867/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004868/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004869bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004870#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004871 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004872 OPTIONAL(file, MDField, ); \
4873 OPTIONAL(line, LineField, ); \
4874 OPTIONAL(setter, MDStringField, ); \
4875 OPTIONAL(getter, MDStringField, ); \
4876 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4877 OPTIONAL(type, MDField, );
4878 PARSE_MD_FIELDS();
4879#undef VISIT_MD_FIELDS
4880
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004881 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004882 (Context, name.Val, file.Val, line.Val, setter.Val,
4883 getter.Val, attributes.Val, type.Val));
4884 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004885}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004886
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004887/// ParseDIImportedEntity:
4888/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004889/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004890bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004891#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4892 REQUIRED(tag, DwarfTagField, ); \
4893 REQUIRED(scope, MDField, ); \
4894 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004895 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004896 OPTIONAL(line, LineField, ); \
4897 OPTIONAL(name, MDStringField, );
4898 PARSE_MD_FIELDS();
4899#undef VISIT_MD_FIELDS
4900
Adrian Prantld63bfd22017-07-19 00:09:54 +00004901 Result = GET_OR_DISTINCT(
4902 DIImportedEntity,
4903 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004904 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004905}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004906
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004907#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004908#undef NOP_FIELD
4909#undef REQUIRE_FIELD
4910#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004911
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004912/// ParseMetadataAsValue
4913/// ::= metadata i32 %local
4914/// ::= metadata i32 @global
4915/// ::= metadata i32 7
4916/// ::= metadata !0
4917/// ::= metadata !{...}
4918/// ::= metadata !"string"
4919bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4920 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004921 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004922 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004923 return true;
4924
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004925 V = MetadataAsValue::get(Context, MD);
4926 return false;
4927}
4928
4929/// ParseValueAsMetadata
4930/// ::= i32 %local
4931/// ::= i32 @global
4932/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004933bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4934 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004935 Type *Ty;
4936 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004937 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004938 return true;
4939 if (Ty->isMetadataTy())
4940 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4941
4942 Value *V;
4943 if (ParseValue(Ty, V, PFS))
4944 return true;
4945
4946 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004947 return false;
4948}
4949
4950/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004951/// ::= i32 %local
4952/// ::= i32 @global
4953/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004954/// ::= !42
4955/// ::= !{...}
4956/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004957/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004958bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004959 if (Lex.getKind() == lltok::MetadataVar) {
4960 MDNode *N;
4961 if (ParseSpecializedMDNode(N))
4962 return true;
4963 MD = N;
4964 return false;
4965 }
4966
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004967 // ValueAsMetadata:
4968 // <type> <value>
4969 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004970 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004971
4972 // '!'.
4973 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4974 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004975
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004976 // MDString:
4977 // ::= '!' STRINGCONSTANT
4978 if (Lex.getKind() == lltok::StringConstant) {
4979 MDString *S;
4980 if (ParseMDString(S))
4981 return true;
4982 MD = S;
4983 return false;
4984 }
4985
Dan Gohman8939ba332010-07-14 18:26:50 +00004986 // MDNode:
4987 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004988 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004989 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004990 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004991 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004992 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004993 return false;
4994}
4995
Victor Hernandez9d75c962010-01-11 22:31:58 +00004996//===----------------------------------------------------------------------===//
4997// Function Parsing.
4998//===----------------------------------------------------------------------===//
4999
Chris Lattner229907c2011-07-18 04:54:35 +00005000bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005001 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00005002 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005004
Chris Lattnerac161bf2009-01-02 07:01:27 +00005005 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00005007 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005008 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005009 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005010 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00005011 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005012 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005013 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00005014 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00005015 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00005016 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00005017 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5018 (ID.UIntVal >> 1) & 1,
5019 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00005020 return false;
5021 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005022 case ValID::t_GlobalName:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005023 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005024 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005025 case ValID::t_GlobalID:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005026 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005027 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00005029 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005030 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00005031 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00005032 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005033 return false;
5034 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00005035 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5037 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005038
Dan Gohman518cda42011-12-17 00:04:22 +00005039 // The lexer has no type info, so builds all half, float, and double FP
5040 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005041 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005042 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00005043 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005044 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00005045 &Ignored);
5046 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005047 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00005048 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005049 }
Owen Anderson69c464d2009-07-27 20:59:43 +00005050 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005051
Chris Lattner8f57d29e2009-01-05 18:24:23 +00005052 if (V->getType() != Ty)
5053 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005054 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005055
Chris Lattnerac161bf2009-01-02 07:01:27 +00005056 return false;
5057 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00005058 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005059 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005060 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 return false;
5062 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00005063 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005064 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00005065 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005066 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005067 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00005068 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00005069 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00005070 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005071 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00005072 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005073 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00005074 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00005075 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005076 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00005077 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005078 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00005079 case ValID::t_None:
5080 if (!Ty->isTokenTy())
5081 return Error(ID.Loc, "invalid type for none constant");
5082 V = Constant::getNullValue(Ty);
5083 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005084 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00005085 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00005087
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 V = ID.ConstantVal;
5089 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005090 case ValID::t_ConstantStruct:
5091 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00005092 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005093 if (ST->getNumElements() != ID.UIntVal)
5094 return Error(ID.Loc,
5095 "initializer with struct type has wrong # elements");
5096 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5097 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005098
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005099 // Verify that the elements are compatible with the structtype.
5100 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5101 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5102 return Error(ID.Loc, "element " + Twine(i) +
5103 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005104
David Blaikieadbda4b2015-08-03 20:08:41 +00005105 V = ConstantStruct::get(
5106 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005107 } else
5108 return Error(ID.Loc, "constant expression type mismatch");
5109 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005110 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00005111 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005113
Alex Lorenzd2255952015-07-17 22:07:03 +00005114bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5115 C = nullptr;
5116 ValID ID;
5117 auto Loc = Lex.getLoc();
5118 if (ParseValID(ID, /*PFS=*/nullptr))
5119 return true;
5120 switch (ID.Kind) {
5121 case ValID::t_APSInt:
5122 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00005123 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00005124 case ValID::t_Constant:
5125 case ValID::t_ConstantStruct:
5126 case ValID::t_PackedConstantStruct: {
5127 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005128 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00005129 return true;
5130 assert(isa<Constant>(V) && "Expected a constant value");
5131 C = cast<Constant>(V);
5132 return false;
5133 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00005134 case ValID::t_Null:
5135 C = Constant::getNullValue(Ty);
5136 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00005137 default:
5138 return Error(Loc, "expected a constant value");
5139 }
5140}
5141
David Majnemer8a1c45d2015-12-12 05:38:55 +00005142bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005143 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005145 return ParseValID(ID, PFS) ||
5146 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147}
5148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005149bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005150 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005151 return ParseType(Ty) ||
5152 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005153}
5154
Chris Lattner3ed871f2009-10-27 19:13:16 +00005155bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5156 PerFunctionState &PFS) {
5157 Value *V;
5158 Loc = Lex.getLoc();
5159 if (ParseTypeAndValue(V, PFS)) return true;
5160 if (!isa<BasicBlock>(V))
5161 return Error(Loc, "expected a basic block");
5162 BB = cast<BasicBlock>(V);
5163 return false;
5164}
5165
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00005167/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5168/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005169/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5170/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00005171bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5172 // Parse the linkage.
5173 LocTy LinkageLoc = Lex.getLoc();
5174 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005175 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005176 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005177 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005178 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005179 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005180 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005181 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005183 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5184 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005185 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005186 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187 return true;
5188
5189 // Verify that the linkage is ok.
5190 switch ((GlobalValue::LinkageTypes)Linkage) {
5191 case GlobalValue::ExternalLinkage:
5192 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005193 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 if (isDefine)
5195 return Error(LinkageLoc, "invalid linkage for function definition");
5196 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005197 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005198 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005199 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005200 case GlobalValue::LinkOnceAnyLinkage:
5201 case GlobalValue::LinkOnceODRLinkage:
5202 case GlobalValue::WeakAnyLinkage:
5203 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 if (!isDefine)
5205 return Error(LinkageLoc, "invalid linkage for function declaration");
5206 break;
5207 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005208 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 return Error(LinkageLoc, "invalid function linkage type");
5210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005211
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005212 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5213 return Error(LinkageLoc,
5214 "symbol with local linkage must have default visibility");
5215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005216 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005217 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005218
Chris Lattnerac161bf2009-01-02 07:01:27 +00005219 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005220
5221 std::string FunctionName;
5222 if (Lex.getKind() == lltok::GlobalVar) {
5223 FunctionName = Lex.getStrVal();
5224 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5225 unsigned NameID = Lex.getUIntVal();
5226
5227 if (NameID != NumberedVals.size())
5228 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005229 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005230 } else {
5231 return TokError("expected function name");
5232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005233
Chris Lattner3822f632009-01-02 08:05:26 +00005234 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005235
Chris Lattner3822f632009-01-02 08:05:26 +00005236 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005237 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005238
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005239 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005241 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005242 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005243 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005244 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005246 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005247 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005248 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005249 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005250 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005251 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005252 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005253
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005254 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005255 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005256 ParseOptionalProgramAddrSpace(AddrSpace) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005257 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005258 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005259 (EatIfPresent(lltok::kw_section) &&
5260 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005261 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005262 ParseOptionalAlignment(Alignment) ||
5263 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005264 ParseStringConstant(GC)) ||
5265 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005266 ParseGlobalTypeAndValue(Prefix)) ||
5267 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005268 ParseGlobalTypeAndValue(Prologue)) ||
5269 (EatIfPresent(lltok::kw_personality) &&
5270 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005271 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272
Michael Gottesman41748d72013-06-27 00:25:01 +00005273 if (FuncAttrs.contains(Attribute::Builtin))
5274 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005275
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005277 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005278 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005279 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005281
Chris Lattnerac161bf2009-01-02 07:01:27 +00005282 // Okay, if we got here, the function is syntactically valid. Convert types
5283 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005284 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005285 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005286
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005288 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005289 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 }
5291
Reid Kleckner7f720332017-04-13 00:58:09 +00005292 AttributeList PAL =
5293 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5294 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005295
Bill Wendling749a43d2012-12-30 13:50:49 +00005296 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005297 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5298
Chris Lattner229907c2011-07-18 04:54:35 +00005299 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005300 FunctionType::get(RetType, ParamTypeList, isVarArg);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005301 PointerType *PFT = PointerType::get(FT, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005302
Craig Topper2617dcc2014-04-15 06:32:26 +00005303 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005304 if (!FunctionName.empty()) {
5305 // If this was a definition of a forward reference, remove the definition
5306 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005307 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308 if (FRVI != ForwardRefVals.end()) {
5309 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005310 if (!Fn)
5311 return Error(FRVI->second.second, "invalid forward reference to "
5312 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005313 if (Fn->getType() != PFT)
5314 return Error(FRVI->second.second, "invalid forward reference to "
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005315 "function '" + FunctionName + "' with wrong type: "
5316 "expected '" + getTypeString(PFT) + "' but was '" +
5317 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005318 ForwardRefVals.erase(FRVI);
5319 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005320 // Reject redefinitions.
5321 return Error(NameLoc, "invalid redefinition of function '" +
5322 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005323 } else if (M->getNamedValue(FunctionName)) {
5324 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005325 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005326
Dan Gohman399d6ae2009-08-29 23:37:49 +00005327 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005328 // If this is a definition of a forward referenced function, make sure the
5329 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005330 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005331 if (I != ForwardRefValIDs.end()) {
5332 Fn = cast<Function>(I->second.first);
5333 if (Fn->getType() != PFT)
5334 return Error(NameLoc, "type of definition and forward reference of '@" +
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005335 Twine(NumberedVals.size()) + "' disagree: "
5336 "expected '" + getTypeString(PFT) + "' but was '" +
5337 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005338 ForwardRefValIDs.erase(I);
5339 }
5340 }
5341
Craig Topper2617dcc2014-04-15 06:32:26 +00005342 if (!Fn)
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005343 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5344 FunctionName, M);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005345 else // Move the forward-reference to the correct spot in the module.
5346 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5347
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005348 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5349
Chris Lattnerac161bf2009-01-02 07:01:27 +00005350 if (FunctionName.empty())
5351 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005352
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005354 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005356 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005357 Fn->setCallingConv(CC);
5358 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005359 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005360 Fn->setAlignment(Alignment);
5361 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005362 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005363 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005364 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005365 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005366 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005367 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005368
Chris Lattnerac161bf2009-01-02 07:01:27 +00005369 // Add all of the arguments we parsed to the function.
5370 Function::arg_iterator ArgIt = Fn->arg_begin();
5371 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5372 // If the argument has a name, insert it into the argument symbol table.
5373 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005374
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 // Set the name, if it conflicted, it will be auto-renamed.
5376 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005377
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005378 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005379 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5380 ArgList[i].Name + "'");
5381 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005382
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005383 if (isDefine)
5384 return false;
5385
Robin Morisset039781e2014-08-29 21:53:01 +00005386 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005387 ValID ID;
5388 if (FunctionName.empty()) {
5389 ID.Kind = ValID::t_GlobalID;
5390 ID.UIntVal = NumberedVals.size() - 1;
5391 } else {
5392 ID.Kind = ValID::t_GlobalName;
5393 ID.StrVal = FunctionName;
5394 }
5395 auto Blocks = ForwardRefBlockAddresses.find(ID);
5396 if (Blocks != ForwardRefBlockAddresses.end())
5397 return Error(Blocks->first.Loc,
5398 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005399 return false;
5400}
5401
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005402bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5403 ValID ID;
5404 if (FunctionNumber == -1) {
5405 ID.Kind = ValID::t_GlobalName;
5406 ID.StrVal = F.getName();
5407 } else {
5408 ID.Kind = ValID::t_GlobalID;
5409 ID.UIntVal = FunctionNumber;
5410 }
5411
5412 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5413 if (Blocks == P.ForwardRefBlockAddresses.end())
5414 return false;
5415
5416 for (const auto &I : Blocks->second) {
5417 const ValID &BBID = I.first;
5418 GlobalValue *GV = I.second;
5419
5420 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5421 "Expected local id or name");
5422 BasicBlock *BB;
5423 if (BBID.Kind == ValID::t_LocalName)
5424 BB = GetBB(BBID.StrVal, BBID.Loc);
5425 else
5426 BB = GetBB(BBID.UIntVal, BBID.Loc);
5427 if (!BB)
5428 return P.Error(BBID.Loc, "referenced value is not a basic block");
5429
5430 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5431 GV->eraseFromParent();
5432 }
5433
5434 P.ForwardRefBlockAddresses.erase(Blocks);
5435 return false;
5436}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005437
5438/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005439/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005440bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005441 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005442 return TokError("expected '{' in function body");
5443 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005444
Chris Lattner3432c622009-10-28 03:39:23 +00005445 int FunctionNumber = -1;
5446 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005447
Chris Lattner3432c622009-10-28 03:39:23 +00005448 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005449
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005450 // Resolve block addresses and allow basic blocks to be forward-declared
5451 // within this function.
5452 if (PFS.resolveForwardRefBlockAddresses())
5453 return true;
5454 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5455
Chris Lattnerbbddd962010-01-09 19:20:07 +00005456 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005457 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005458 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005459
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005460 while (Lex.getKind() != lltok::rbrace &&
5461 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005462 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005463
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005464 while (Lex.getKind() != lltok::rbrace)
5465 if (ParseUseListOrder(&PFS))
5466 return true;
5467
Chris Lattnerac161bf2009-01-02 07:01:27 +00005468 // Eat the }.
5469 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005470
Chris Lattnerac161bf2009-01-02 07:01:27 +00005471 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005472 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005473}
5474
5475/// ParseBasicBlock
5476/// ::= LabelStr? Instruction*
5477bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5478 // If this basic block starts out with a name, remember it.
5479 std::string Name;
5480 LocTy NameLoc = Lex.getLoc();
5481 if (Lex.getKind() == lltok::LabelStr) {
5482 Name = Lex.getStrVal();
5483 Lex.Lex();
5484 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005485
Chris Lattnerac161bf2009-01-02 07:01:27 +00005486 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005487 if (!BB)
5488 return Error(NameLoc,
5489 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005490
Chris Lattnerac161bf2009-01-02 07:01:27 +00005491 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005492
Chris Lattnerac161bf2009-01-02 07:01:27 +00005493 // Parse the instructions in this block until we get a terminator.
5494 Instruction *Inst;
5495 do {
5496 // This instruction may have three possibilities for a name: a) none
5497 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5498 LocTy NameLoc = Lex.getLoc();
5499 int NameID = -1;
5500 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005501
Chris Lattnerac161bf2009-01-02 07:01:27 +00005502 if (Lex.getKind() == lltok::LocalVarID) {
5503 NameID = Lex.getUIntVal();
5504 Lex.Lex();
5505 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5506 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005507 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005508 NameStr = Lex.getStrVal();
5509 Lex.Lex();
5510 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5511 return true;
5512 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005513
Chris Lattner77b89dc2009-12-30 05:23:43 +00005514 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005515 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005516 case InstError: return true;
5517 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005518 BB->getInstList().push_back(Inst);
5519
Chris Lattner77b89dc2009-12-30 05:23:43 +00005520 // With a normal result, we check to see if the instruction is followed by
5521 // a comma and metadata.
5522 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005523 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005524 return true;
5525 break;
5526 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005527 BB->getInstList().push_back(Inst);
5528
Chris Lattner77b89dc2009-12-30 05:23:43 +00005529 // If the instruction parser ate an extra comma at the end of it, it
5530 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005531 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005532 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005533 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005534 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005535
Chris Lattnerac161bf2009-01-02 07:01:27 +00005536 // Set the name on the instruction.
5537 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005538 } while (!Inst->isTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005539
Chris Lattnerac161bf2009-01-02 07:01:27 +00005540 return false;
5541}
5542
5543//===----------------------------------------------------------------------===//
5544// Instruction Parsing.
5545//===----------------------------------------------------------------------===//
5546
5547/// ParseInstruction - Parse one of the many different instructions.
5548///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005549int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5550 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005551 lltok::Kind Token = Lex.getKind();
5552 if (Token == lltok::Eof)
5553 return TokError("found end of file when expecting more instructions");
5554 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005555 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005556 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005557
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 switch (Token) {
5559 default: return Error(Loc, "expected instruction opcode");
5560 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005561 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5563 case lltok::kw_br: return ParseBr(Inst, PFS);
5564 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005565 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005566 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005567 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005568 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5569 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005570 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5571 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005572 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Cameron McInallycbde0d92018-11-13 18:15:47 +00005573 // Unary Operators.
5574 case lltok::kw_fneg: {
5575 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5576 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, 2);
5577 if (Res != 0)
5578 return Res;
5579 if (FMF.any())
5580 Inst->setFastMathFlags(FMF);
5581 return false;
5582 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005583 // Binary Operators.
5584 case lltok::kw_add:
5585 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005586 case lltok::kw_mul:
5587 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005588 bool NUW = EatIfPresent(lltok::kw_nuw);
5589 bool NSW = EatIfPresent(lltok::kw_nsw);
5590 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005591
Chris Lattnera676c0f2011-02-07 16:40:21 +00005592 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005593
Chris Lattnera676c0f2011-02-07 16:40:21 +00005594 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5595 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5596 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005597 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005598 case lltok::kw_fadd:
5599 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005600 case lltok::kw_fmul:
5601 case lltok::kw_fdiv:
5602 case lltok::kw_frem: {
5603 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5604 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5605 if (Res != 0)
5606 return Res;
5607 if (FMF.any())
5608 Inst->setFastMathFlags(FMF);
5609 return 0;
5610 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005611
Chris Lattner35315d02011-02-06 21:44:57 +00005612 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005613 case lltok::kw_udiv:
5614 case lltok::kw_lshr:
5615 case lltok::kw_ashr: {
5616 bool Exact = EatIfPresent(lltok::kw_exact);
5617
5618 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5619 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5620 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005621 }
5622
Chris Lattnerac161bf2009-01-02 07:01:27 +00005623 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005624 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005625 case lltok::kw_and:
5626 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005627 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005628 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5629 case lltok::kw_fcmp: {
5630 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5631 int Res = ParseCompare(Inst, PFS, KeywordVal);
5632 if (Res != 0)
5633 return Res;
5634 if (FMF.any())
5635 Inst->setFastMathFlags(FMF);
5636 return 0;
5637 }
5638
Chris Lattnerac161bf2009-01-02 07:01:27 +00005639 // Casts.
5640 case lltok::kw_trunc:
5641 case lltok::kw_zext:
5642 case lltok::kw_sext:
5643 case lltok::kw_fptrunc:
5644 case lltok::kw_fpext:
5645 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005646 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647 case lltok::kw_uitofp:
5648 case lltok::kw_sitofp:
5649 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005650 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005651 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005652 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005653 // Other.
5654 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005655 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005656 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5657 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5658 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5659 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005660 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005661 // Call.
5662 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5663 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5664 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005665 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005666 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005667 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005668 case lltok::kw_load: return ParseLoad(Inst, PFS);
5669 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005670 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5671 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005672 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005673 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5674 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5675 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5676 }
5677}
5678
5679/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5680bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005681 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005682 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005683 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5685 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5686 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5687 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5688 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5689 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5690 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5691 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5692 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5693 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5694 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5695 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5696 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5697 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5698 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5699 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5700 }
5701 } else {
5702 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005703 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005704 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5705 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5706 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5707 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5708 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5709 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5710 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5711 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5712 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5713 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5714 }
5715 }
5716 Lex.Lex();
5717 return false;
5718}
5719
5720//===----------------------------------------------------------------------===//
5721// Terminator Instructions.
5722//===----------------------------------------------------------------------===//
5723
5724/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005725/// ::= 'ret' void (',' !dbg, !1)*
5726/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005727bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005728 PerFunctionState &PFS) {
5729 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005730 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005731 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005732
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005733 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005734
Chris Lattnerfdd87902009-10-05 05:54:46 +00005735 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005736 if (!ResType->isVoidTy())
5737 return Error(TypeLoc, "value doesn't match function result type '" +
5738 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005739
Owen Anderson55f1c092009-08-13 21:58:54 +00005740 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 return false;
5742 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005743
Chris Lattnerac161bf2009-01-02 07:01:27 +00005744 Value *RV;
5745 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005746
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005747 if (ResType != RV->getType())
5748 return Error(TypeLoc, "value doesn't match function result type '" +
5749 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005750
Owen Anderson55f1c092009-08-13 21:58:54 +00005751 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005752 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753}
5754
Chris Lattnerac161bf2009-01-02 07:01:27 +00005755/// ParseBr
5756/// ::= 'br' TypeAndValue
5757/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5758bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5759 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005760 Value *Op0;
5761 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005762 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005763
Chris Lattnerac161bf2009-01-02 07:01:27 +00005764 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5765 Inst = BranchInst::Create(BB);
5766 return false;
5767 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005768
Owen Anderson55f1c092009-08-13 21:58:54 +00005769 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005770 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005771
Chris Lattnerac161bf2009-01-02 07:01:27 +00005772 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005773 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005774 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005775 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005776 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005777
Chris Lattner3ed871f2009-10-27 19:13:16 +00005778 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005779 return false;
5780}
5781
5782/// ParseSwitch
5783/// Instruction
5784/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5785/// JumpTable
5786/// ::= (TypeAndValue ',' TypeAndValue)*
5787bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5788 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005789 Value *Cond;
5790 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005791 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5792 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005793 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005794 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5795 return true;
5796
Duncan Sands19d0b472010-02-16 11:11:14 +00005797 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005798 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005799
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 // Parse the jump table pairs.
5801 SmallPtrSet<Value*, 32> SeenCases;
5802 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5803 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005804 Value *Constant;
5805 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005806
Chris Lattnerac161bf2009-01-02 07:01:27 +00005807 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5808 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005809 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005810 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005811
David Blaikie70573dc2014-11-19 07:49:26 +00005812 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 return Error(CondLoc, "duplicate case value in switch");
5814 if (!isa<ConstantInt>(Constant))
5815 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005816
Chris Lattner3ed871f2009-10-27 19:13:16 +00005817 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005818 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005819
Chris Lattnerac161bf2009-01-02 07:01:27 +00005820 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005821
Chris Lattner3ed871f2009-10-27 19:13:16 +00005822 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005823 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5824 SI->addCase(Table[i].first, Table[i].second);
5825 Inst = SI;
5826 return false;
5827}
5828
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005829/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005830/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005831/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5832bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005833 LocTy AddrLoc;
5834 Value *Address;
5835 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005836 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5837 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005838 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005839
Duncan Sands19d0b472010-02-16 11:11:14 +00005840 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005841 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005842
Chris Lattner3ed871f2009-10-27 19:13:16 +00005843 // Parse the destination list.
5844 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005845
Chris Lattner3ed871f2009-10-27 19:13:16 +00005846 if (Lex.getKind() != lltok::rsquare) {
5847 BasicBlock *DestBB;
5848 if (ParseTypeAndBasicBlock(DestBB, PFS))
5849 return true;
5850 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005851
Chris Lattner3ed871f2009-10-27 19:13:16 +00005852 while (EatIfPresent(lltok::comma)) {
5853 if (ParseTypeAndBasicBlock(DestBB, PFS))
5854 return true;
5855 DestList.push_back(DestBB);
5856 }
5857 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005858
Chris Lattner3ed871f2009-10-27 19:13:16 +00005859 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5860 return true;
5861
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005862 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005863 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5864 IBI->addDestination(DestList[i]);
5865 Inst = IBI;
5866 return false;
5867}
5868
Chris Lattnerac161bf2009-01-02 07:01:27 +00005869/// ParseInvoke
5870/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5871/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5872bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5873 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005874 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005875 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005876 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005877 unsigned CC;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005878 unsigned InvokeAddrSpace;
Craig Topper2617dcc2014-04-15 06:32:26 +00005879 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 LocTy RetTypeLoc;
5881 ValID CalleeID;
5882 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005883 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884
Chris Lattner3ed871f2009-10-27 19:13:16 +00005885 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005886 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005887 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005888 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005889 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005890 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5891 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005892 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005893 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005894 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005895 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005896 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005897 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005898
Chris Lattnerac161bf2009-01-02 07:01:27 +00005899 // If RetType is a non-function pointer type, then this is the short syntax
5900 // for the call, which means that RetType is just the return type. Infer the
5901 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005902 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5903 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005904 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005905 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005906 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5907 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005908
Chris Lattnerac161bf2009-01-02 07:01:27 +00005909 if (!FunctionType::isValidReturnType(RetType))
5910 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005911
Owen Anderson4056ca92009-07-29 22:17:13 +00005912 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005914
David Blaikie41ba2b42015-07-27 23:32:19 +00005915 CalleeID.FTy = Ty;
5916
Chris Lattnerac161bf2009-01-02 07:01:27 +00005917 // Look up the callee.
5918 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005919 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5920 Callee, &PFS, /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005921 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005922
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005923 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005924 SmallVector<Value *, 8> Args;
5925 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005926
Chris Lattnerac161bf2009-01-02 07:01:27 +00005927 // Loop through FunctionType's arguments and ensure they are specified
5928 // correctly. Also, gather any parameter attributes.
5929 FunctionType::param_iterator I = Ty->param_begin();
5930 FunctionType::param_iterator E = Ty->param_end();
5931 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005932 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005933 if (I != E) {
5934 ExpectedTy = *I++;
5935 } else if (!Ty->isVarArg()) {
5936 return Error(ArgList[i].Loc, "too many arguments specified");
5937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005938
Chris Lattnerac161bf2009-01-02 07:01:27 +00005939 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5940 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005941 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005942 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005943 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005945
Chris Lattnerac161bf2009-01-02 07:01:27 +00005946 if (I != E)
5947 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005948
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005949 if (FnAttrs.hasAlignmentAttr())
5950 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005951
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005952 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005953 AttributeList PAL =
5954 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5955 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005956
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005957 InvokeInst *II =
5958 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005959 II->setCallingConv(CC);
5960 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005961 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005962 Inst = II;
5963 return false;
5964}
5965
Bill Wendlingf891bf82011-07-31 06:30:59 +00005966/// ParseResume
5967/// ::= 'resume' TypeAndValue
5968bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5969 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005970 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5971 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005972
Bill Wendlingf891bf82011-07-31 06:30:59 +00005973 ResumeInst *RI = ResumeInst::Create(Exn);
5974 Inst = RI;
5975 return false;
5976}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977
David Majnemer654e1302015-07-31 17:58:14 +00005978bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5979 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005980 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005981 return true;
5982
5983 while (Lex.getKind() != lltok::rsquare) {
5984 // If this isn't the first argument, we need a comma.
5985 if (!Args.empty() &&
5986 ParseToken(lltok::comma, "expected ',' in argument list"))
5987 return true;
5988
5989 // Parse the argument.
5990 LocTy ArgLoc;
5991 Type *ArgTy = nullptr;
5992 if (ParseType(ArgTy, ArgLoc))
5993 return true;
5994
5995 Value *V;
5996 if (ArgTy->isMetadataTy()) {
5997 if (ParseMetadataAsValue(V, PFS))
5998 return true;
5999 } else {
6000 if (ParseValue(ArgTy, V, PFS))
6001 return true;
6002 }
6003 Args.push_back(V);
6004 }
6005
6006 Lex.Lex(); // Lex the ']'.
6007 return false;
6008}
6009
6010/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00006011/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00006012bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006013 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00006014
David Majnemer8a1c45d2015-12-12 05:38:55 +00006015 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6016 return true;
6017
6018 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006019 return true;
David Majnemer654e1302015-07-31 17:58:14 +00006020
6021 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6022 return true;
6023
6024 BasicBlock *UnwindBB = nullptr;
6025 if (Lex.getKind() == lltok::kw_to) {
6026 Lex.Lex();
6027 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6028 return true;
6029 } else {
6030 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6031 return true;
6032 }
6033 }
6034
David Majnemer8a1c45d2015-12-12 05:38:55 +00006035 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00006036 return false;
6037}
6038
6039/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00006040/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006041bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006042 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00006043
David Majnemer8a1c45d2015-12-12 05:38:55 +00006044 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6045 return true;
6046
6047 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00006048 return true;
6049
David Majnemer0bc0eef2015-08-15 02:46:08 +00006050 BasicBlock *BB;
6051 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6052 ParseTypeAndBasicBlock(BB, PFS))
6053 return true;
6054
David Majnemer8a1c45d2015-12-12 05:38:55 +00006055 Inst = CatchReturnInst::Create(CatchPad, BB);
6056 return false;
6057}
6058
6059/// ParseCatchSwitch
6060/// ::= 'catchswitch' within Parent
6061bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6062 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00006063
6064 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6065 return true;
6066
6067 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6068 Lex.getKind() != lltok::LocalVarID)
6069 return TokError("expected scope value for catchswitch");
6070
6071 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6072 return true;
6073
6074 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6075 return true;
6076
6077 SmallVector<BasicBlock *, 32> Table;
6078 do {
6079 BasicBlock *DestBB;
6080 if (ParseTypeAndBasicBlock(DestBB, PFS))
6081 return true;
6082 Table.push_back(DestBB);
6083 } while (EatIfPresent(lltok::comma));
6084
6085 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6086 return true;
6087
6088 if (ParseToken(lltok::kw_unwind,
6089 "expected 'unwind' after catchswitch scope"))
6090 return true;
6091
6092 BasicBlock *UnwindBB = nullptr;
6093 if (EatIfPresent(lltok::kw_to)) {
6094 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6095 return true;
6096 } else {
6097 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6098 return true;
6099 }
6100
6101 auto *CatchSwitch =
6102 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6103 for (BasicBlock *DestBB : Table)
6104 CatchSwitch->addHandler(DestBB);
6105 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00006106 return false;
6107}
6108
6109/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006110/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006111bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006112 Value *CatchSwitch = nullptr;
6113
6114 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6115 return true;
6116
6117 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6118 return TokError("expected scope value for catchpad");
6119
6120 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6121 return true;
6122
David Majnemer654e1302015-07-31 17:58:14 +00006123 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006124 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006125 return true;
6126
David Majnemer8a1c45d2015-12-12 05:38:55 +00006127 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00006128 return false;
6129}
6130
David Majnemer654e1302015-07-31 17:58:14 +00006131/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00006132/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00006133bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006134 Value *ParentPad = nullptr;
6135
6136 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6137 return true;
6138
6139 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6140 Lex.getKind() != lltok::LocalVarID)
6141 return TokError("expected scope value for cleanuppad");
6142
6143 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6144 return true;
6145
David Majnemer654e1302015-07-31 17:58:14 +00006146 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006147 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006148 return true;
6149
David Majnemer8a1c45d2015-12-12 05:38:55 +00006150 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00006151 return false;
6152}
6153
Chris Lattnerac161bf2009-01-02 07:01:27 +00006154//===----------------------------------------------------------------------===//
Cameron McInallycbde0d92018-11-13 18:15:47 +00006155// Unary Operators.
6156//===----------------------------------------------------------------------===//
6157
6158/// ParseUnaryOp
6159/// ::= UnaryOp TypeAndValue ',' Value
6160///
6161/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6162/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6163bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6164 unsigned Opc, unsigned OperandType) {
6165 LocTy Loc; Value *LHS;
6166 if (ParseTypeAndValue(LHS, Loc, PFS))
6167 return true;
6168
6169 bool Valid;
6170 switch (OperandType) {
6171 default: llvm_unreachable("Unknown operand type!");
6172 case 0: // int or FP.
6173 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6174 LHS->getType()->isFPOrFPVectorTy();
6175 break;
6176 case 1:
6177 Valid = LHS->getType()->isIntOrIntVectorTy();
6178 break;
6179 case 2:
6180 Valid = LHS->getType()->isFPOrFPVectorTy();
6181 break;
6182 }
6183
6184 if (!Valid)
6185 return Error(Loc, "invalid operand type for instruction");
6186
6187 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6188 return false;
6189}
6190
6191//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00006192// Binary Operators.
6193//===----------------------------------------------------------------------===//
6194
6195/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006196/// ::= ArithmeticOps TypeAndValue ',' Value
6197///
6198/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6199/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00006200bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006201 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006202 LocTy Loc; Value *LHS, *RHS;
6203 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6204 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6205 ParseValue(LHS->getType(), RHS, PFS))
6206 return true;
6207
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006208 bool Valid;
6209 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00006210 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006211 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00006212 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6213 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006214 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00006215 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6216 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006217 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006218
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006219 if (!Valid)
6220 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006221
Chris Lattnerac161bf2009-01-02 07:01:27 +00006222 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6223 return false;
6224}
6225
6226/// ParseLogical
6227/// ::= ArithmeticOps TypeAndValue ',' Value {
6228bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6229 unsigned Opc) {
6230 LocTy Loc; Value *LHS, *RHS;
6231 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6232 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6233 ParseValue(LHS->getType(), RHS, PFS))
6234 return true;
6235
Duncan Sands9dff9be2010-02-15 16:12:20 +00006236 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006237 return Error(Loc,"instruction requires integer or integer vector operands");
6238
6239 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6240 return false;
6241}
6242
Chris Lattnerac161bf2009-01-02 07:01:27 +00006243/// ParseCompare
6244/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6245/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006246bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6247 unsigned Opc) {
6248 // Parse the integer/fp comparison predicate.
6249 LocTy Loc;
6250 unsigned Pred;
6251 Value *LHS, *RHS;
6252 if (ParseCmpPredicate(Pred, Opc) ||
6253 ParseTypeAndValue(LHS, Loc, PFS) ||
6254 ParseToken(lltok::comma, "expected ',' after compare value") ||
6255 ParseValue(LHS->getType(), RHS, PFS))
6256 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006257
Chris Lattnerac161bf2009-01-02 07:01:27 +00006258 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006259 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006260 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006261 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006262 } else {
6263 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006264 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006265 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006266 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006267 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006268 }
6269 return false;
6270}
6271
6272//===----------------------------------------------------------------------===//
6273// Other Instructions.
6274//===----------------------------------------------------------------------===//
6275
6276
6277/// ParseCast
6278/// ::= CastOpc TypeAndValue 'to' Type
6279bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6280 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006281 LocTy Loc;
6282 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006283 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006284 if (ParseTypeAndValue(Op, Loc, PFS) ||
6285 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6286 ParseType(DestTy))
6287 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006288
Chris Lattner89d856e2009-03-01 00:53:13 +00006289 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6290 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006291 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006292 getTypeString(Op->getType()) + "' to '" +
6293 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006294 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006295 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6296 return false;
6297}
6298
6299/// ParseSelect
6300/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6301bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6302 LocTy Loc;
6303 Value *Op0, *Op1, *Op2;
6304 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6305 ParseToken(lltok::comma, "expected ',' after select condition") ||
6306 ParseTypeAndValue(Op1, PFS) ||
6307 ParseToken(lltok::comma, "expected ',' after select value") ||
6308 ParseTypeAndValue(Op2, PFS))
6309 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006310
Chris Lattnerac161bf2009-01-02 07:01:27 +00006311 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6312 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006313
Chris Lattnerac161bf2009-01-02 07:01:27 +00006314 Inst = SelectInst::Create(Op0, Op1, Op2);
6315 return false;
6316}
6317
Chris Lattnerb55ab542009-01-05 08:18:44 +00006318/// ParseVA_Arg
6319/// ::= 'va_arg' TypeAndValue ',' Type
6320bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006321 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006322 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006323 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006324 if (ParseTypeAndValue(Op, PFS) ||
6325 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006326 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006327 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006328
Chris Lattnerb55ab542009-01-05 08:18:44 +00006329 if (!EltTy->isFirstClassType())
6330 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006331
6332 Inst = new VAArgInst(Op, EltTy);
6333 return false;
6334}
6335
6336/// ParseExtractElement
6337/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6338bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6339 LocTy Loc;
6340 Value *Op0, *Op1;
6341 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6342 ParseToken(lltok::comma, "expected ',' after extract value") ||
6343 ParseTypeAndValue(Op1, PFS))
6344 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006345
Chris Lattnerac161bf2009-01-02 07:01:27 +00006346 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6347 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006348
Eric Christopherc9742252009-07-25 02:28:41 +00006349 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006350 return false;
6351}
6352
6353/// ParseInsertElement
6354/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6355bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6356 LocTy Loc;
6357 Value *Op0, *Op1, *Op2;
6358 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6359 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6360 ParseTypeAndValue(Op1, PFS) ||
6361 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6362 ParseTypeAndValue(Op2, PFS))
6363 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006364
Chris Lattnerac161bf2009-01-02 07:01:27 +00006365 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006366 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006367
Chris Lattnerac161bf2009-01-02 07:01:27 +00006368 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6369 return false;
6370}
6371
6372/// ParseShuffleVector
6373/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6374bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6375 LocTy Loc;
6376 Value *Op0, *Op1, *Op2;
6377 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6378 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6379 ParseTypeAndValue(Op1, PFS) ||
6380 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6381 ParseTypeAndValue(Op2, PFS))
6382 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006383
Chris Lattnerac161bf2009-01-02 07:01:27 +00006384 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006385 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006386
Chris Lattnerac161bf2009-01-02 07:01:27 +00006387 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6388 return false;
6389}
6390
6391/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006392/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006393int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006394 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006395 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006396
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006397 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006398 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6399 ParseValue(Ty, Op0, PFS) ||
6400 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006401 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6403 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006404
Chris Lattnerf4f03422009-12-30 05:27:33 +00006405 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006406 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006407
6408 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006409 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006410
Chris Lattner3822f632009-01-02 08:05:26 +00006411 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006412 break;
6413
Chris Lattnerf4f03422009-12-30 05:27:33 +00006414 if (Lex.getKind() == lltok::MetadataVar) {
6415 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006416 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006417 }
Devang Patel8f842d32009-10-16 18:45:49 +00006418
Chris Lattner3822f632009-01-02 08:05:26 +00006419 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006420 ParseValue(Ty, Op0, PFS) ||
6421 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006422 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006423 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6424 return true;
6425 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006426
Chris Lattnerac161bf2009-01-02 07:01:27 +00006427 if (!Ty->isFirstClassType())
6428 return Error(TypeLoc, "phi node must have first class type");
6429
Jay Foad52131342011-03-30 11:28:46 +00006430 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006431 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6432 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6433 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006434 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006435}
6436
Bill Wendlingfae14752011-08-12 20:24:12 +00006437/// ParseLandingPad
6438/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6439/// Clause
6440/// ::= 'catch' TypeAndValue
6441/// ::= 'filter'
6442/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6443bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006444 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006445
David Majnemer7fddecc2015-06-17 20:52:32 +00006446 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006447 return true;
6448
David Majnemer7fddecc2015-06-17 20:52:32 +00006449 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006450 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6451
6452 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6453 LandingPadInst::ClauseType CT;
6454 if (EatIfPresent(lltok::kw_catch))
6455 CT = LandingPadInst::Catch;
6456 else if (EatIfPresent(lltok::kw_filter))
6457 CT = LandingPadInst::Filter;
6458 else
6459 return TokError("expected 'catch' or 'filter' clause type");
6460
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006461 Value *V;
6462 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006463 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006464 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006465
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006466 // A 'catch' type expects a non-array constant. A filter clause expects an
6467 // array constant.
6468 if (CT == LandingPadInst::Catch) {
6469 if (isa<ArrayType>(V->getType()))
6470 Error(VLoc, "'catch' clause has an invalid type");
6471 } else {
6472 if (!isa<ArrayType>(V->getType()))
6473 Error(VLoc, "'filter' clause has an invalid type");
6474 }
6475
Owen Andersonf8f259d2015-03-09 07:13:42 +00006476 Constant *CV = dyn_cast<Constant>(V);
6477 if (!CV)
6478 return Error(VLoc, "clause argument must be a constant");
6479 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006480 }
6481
Owen Andersonf8f259d2015-03-09 07:13:42 +00006482 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006483 return false;
6484}
6485
Chris Lattnerac161bf2009-01-02 07:01:27 +00006486/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006487/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6488/// OptionalAttrs Type Value ParameterList OptionalAttrs
6489/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6490/// OptionalAttrs Type Value ParameterList OptionalAttrs
6491/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6492/// OptionalAttrs Type Value ParameterList OptionalAttrs
6493/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6494/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006495bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006496 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006497 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006498 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006499 LocTy BuiltinLoc;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006500 unsigned CallAddrSpace;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006501 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006502 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006503 LocTy RetTypeLoc;
6504 ValID CalleeID;
6505 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006506 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006507 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006508
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006509 if (TCK != CallInst::TCK_None &&
6510 ParseToken(lltok::kw_call,
6511 "expected 'tail call', 'musttail call', or 'notail call'"))
6512 return true;
6513
6514 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6515
6516 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006517 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006518 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006519 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006520 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6521 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006522 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6523 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006524 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006525
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006526 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6527 return Error(CallLoc, "fast-math-flags specified for call without "
6528 "floating-point scalar or vector return type");
6529
Chris Lattnerac161bf2009-01-02 07:01:27 +00006530 // If RetType is a non-function pointer type, then this is the short syntax
6531 // for the call, which means that RetType is just the return type. Infer the
6532 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006533 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6534 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006535 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006536 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006537 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6538 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006539
Chris Lattnerac161bf2009-01-02 07:01:27 +00006540 if (!FunctionType::isValidReturnType(RetType))
6541 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006542
Owen Anderson4056ca92009-07-29 22:17:13 +00006543 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006544 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006545
David Blaikie41ba2b42015-07-27 23:32:19 +00006546 CalleeID.FTy = Ty;
6547
Chris Lattnerac161bf2009-01-02 07:01:27 +00006548 // Look up the callee.
6549 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006550 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6551 &PFS, /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006552 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006553
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006554 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006555 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006556
Chris Lattnerac161bf2009-01-02 07:01:27 +00006557 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006558
Chris Lattnerac161bf2009-01-02 07:01:27 +00006559 // Loop through FunctionType's arguments and ensure they are specified
6560 // correctly. Also, gather any parameter attributes.
6561 FunctionType::param_iterator I = Ty->param_begin();
6562 FunctionType::param_iterator E = Ty->param_end();
6563 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006564 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006565 if (I != E) {
6566 ExpectedTy = *I++;
6567 } else if (!Ty->isVarArg()) {
6568 return Error(ArgList[i].Loc, "too many arguments specified");
6569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006570
Chris Lattnerac161bf2009-01-02 07:01:27 +00006571 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6572 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006573 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006574 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006575 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006576 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006577
Chris Lattnerac161bf2009-01-02 07:01:27 +00006578 if (I != E)
6579 return Error(CallLoc, "not enough parameters specified for call");
6580
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006581 if (FnAttrs.hasAlignmentAttr())
6582 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006583
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006584 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006585 AttributeList PAL =
6586 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6587 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006588
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006589 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006590 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006591 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006592 if (FMF.any())
6593 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006594 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006595 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006596 Inst = CI;
6597 return false;
6598}
6599
6600//===----------------------------------------------------------------------===//
6601// Memory Instructions.
6602//===----------------------------------------------------------------------===//
6603
6604/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006605/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006606/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006607int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006608 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006609 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006610 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006611 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006612 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006613
6614 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006615 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006616
David Majnemera3b0eb22015-02-16 08:38:03 +00006617 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006618
David Majnemera3b0eb22015-02-16 08:38:03 +00006619 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6620 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006621
Chris Lattnerb2f39502009-12-30 05:44:30 +00006622 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006623 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006624 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006625 if (ParseOptionalAlignment(Alignment))
6626 return true;
6627 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6628 return true;
6629 } else if (Lex.getKind() == lltok::kw_addrspace) {
6630 ASLoc = Lex.getLoc();
6631 if (ParseOptionalAddrSpace(AddrSpace))
6632 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006633 } else if (Lex.getKind() == lltok::MetadataVar) {
6634 AteExtraComma = true;
6635 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006636 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006637 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006638 if (EatIfPresent(lltok::comma)) {
6639 if (Lex.getKind() == lltok::kw_align) {
6640 if (ParseOptionalAlignment(Alignment))
6641 return true;
6642 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6643 return true;
6644 } else if (Lex.getKind() == lltok::kw_addrspace) {
6645 ASLoc = Lex.getLoc();
6646 if (ParseOptionalAddrSpace(AddrSpace))
6647 return true;
6648 } else if (Lex.getKind() == lltok::MetadataVar) {
6649 AteExtraComma = true;
6650 }
6651 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006652 }
6653 }
6654
Dan Gohman2140a742010-05-28 01:14:11 +00006655 if (Size && !Size->getType()->isIntegerTy())
6656 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006657
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006658 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006659 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006660 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006661 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006662 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006663}
6664
6665/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006666/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006667/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006668/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006669int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006670 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006671 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006672 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006673 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006674 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006675 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006676
6677 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006678 isAtomic = true;
6679 Lex.Lex();
6680 }
6681
Chris Lattnerbc639292011-11-27 06:56:53 +00006682 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006683 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006684 isVolatile = true;
6685 Lex.Lex();
6686 }
6687
David Blaikie15d9a4c2015-04-06 20:59:48 +00006688 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006689 LocTy ExplicitTypeLoc = Lex.getLoc();
6690 if (ParseType(Ty) ||
6691 ParseToken(lltok::comma, "expected comma after load's type") ||
6692 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006693 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006694 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6695 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006696
David Blaikie15d9a4c2015-04-06 20:59:48 +00006697 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006698 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006699 if (isAtomic && !Alignment)
6700 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006701 if (Ordering == AtomicOrdering::Release ||
6702 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006703 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006704
David Blaikiea79ac142015-02-27 21:17:42 +00006705 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6706 return Error(ExplicitTypeLoc,
6707 "explicit pointee type doesn't match operand's pointee type");
6708
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006709 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006710 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006711}
6712
6713/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006714
6715/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6716/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006717/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006718int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006719 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006720 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006721 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006722 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006723 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006724 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006725
6726 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006727 isAtomic = true;
6728 Lex.Lex();
6729 }
6730
Chris Lattnerbc639292011-11-27 06:56:53 +00006731 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006732 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006733 isVolatile = true;
6734 Lex.Lex();
6735 }
6736
Chris Lattnerac161bf2009-01-02 07:01:27 +00006737 if (ParseTypeAndValue(Val, Loc, PFS) ||
6738 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006739 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006740 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006741 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006742 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006743
Duncan Sands19d0b472010-02-16 11:11:14 +00006744 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006745 return Error(PtrLoc, "store operand must be a pointer");
6746 if (!Val->getType()->isFirstClassType())
6747 return Error(Loc, "store operand must be a first class value");
6748 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6749 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006750 if (isAtomic && !Alignment)
6751 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006752 if (Ordering == AtomicOrdering::Acquire ||
6753 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006754 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006755
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006756 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006757 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006758}
6759
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006760/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006761/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6762/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006763int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006764 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6765 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006766 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6767 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006768 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006769 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006770 bool isWeak = false;
6771
6772 if (EatIfPresent(lltok::kw_weak))
6773 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006774
6775 if (EatIfPresent(lltok::kw_volatile))
6776 isVolatile = true;
6777
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006778 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6779 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6780 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6781 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6782 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006783 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006784 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006785 return true;
6786
JF Bastien800f87a2016-04-06 21:19:33 +00006787 if (SuccessOrdering == AtomicOrdering::Unordered ||
6788 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006789 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006790 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6791 return TokError("cmpxchg failure argument shall be no stronger than the "
6792 "success argument");
6793 if (FailureOrdering == AtomicOrdering::Release ||
6794 FailureOrdering == AtomicOrdering::AcquireRelease)
6795 return TokError(
6796 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006797 if (!Ptr->getType()->isPointerTy())
6798 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6799 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6800 return Error(CmpLoc, "compare value and pointer type do not match");
6801 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6802 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006803 if (!New->getType()->isFirstClassType())
6804 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006805 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006806 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006807 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006808 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006809 Inst = CXI;
6810 return AteExtraComma ? InstExtraComma : InstNormal;
6811}
6812
6813/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006814/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6815/// 'singlethread'? AtomicOrdering
6816int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006817 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6818 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006819 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006820 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006821 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006822 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006823
6824 if (EatIfPresent(lltok::kw_volatile))
6825 isVolatile = true;
6826
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006827 switch (Lex.getKind()) {
6828 default: return TokError("expected binary operation in atomicrmw");
6829 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6830 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6831 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6832 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6833 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6834 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6835 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6836 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6837 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6838 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6839 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6840 }
6841 Lex.Lex(); // Eat the operation.
6842
6843 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6844 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6845 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006846 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006847 return true;
6848
JF Bastien800f87a2016-04-06 21:19:33 +00006849 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006850 return TokError("atomicrmw cannot be unordered");
6851 if (!Ptr->getType()->isPointerTy())
6852 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6853 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6854 return Error(ValLoc, "atomicrmw value and pointer type do not match");
Matt Arsenault0f83d662018-10-03 02:37:15 +00006855
Matt Arsenault0cb08e42019-01-17 10:49:01 +00006856 if (Operation != AtomicRMWInst::Xchg && !Val->getType()->isIntegerTy()) {
Matt Arsenault0f83d662018-10-03 02:37:15 +00006857 return Error(ValLoc, "atomicrmw " +
6858 AtomicRMWInst::getOperationName(Operation) +
6859 " operand must be an integer");
6860 }
6861
Matt Arsenault0cb08e42019-01-17 10:49:01 +00006862 if (Operation == AtomicRMWInst::Xchg &&
6863 !Val->getType()->isIntegerTy() &&
6864 !Val->getType()->isFloatingPointTy()) {
6865 return Error(ValLoc, "atomicrmw " +
6866 AtomicRMWInst::getOperationName(Operation) +
6867 " operand must be an integer or floating point type");
6868 }
6869
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006870 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6871 if (Size < 8 || (Size & (Size - 1)))
6872 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6873 " integer");
6874
6875 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006876 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006877 RMWI->setVolatile(isVolatile);
6878 Inst = RMWI;
6879 return AteExtraComma ? InstExtraComma : InstNormal;
6880}
6881
Eli Friedmanfee02c62011-07-25 23:16:38 +00006882/// ParseFence
6883/// ::= 'fence' 'singlethread'? AtomicOrdering
6884int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006885 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006886 SyncScope::ID SSID = SyncScope::System;
6887 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006888 return true;
6889
JF Bastien800f87a2016-04-06 21:19:33 +00006890 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006891 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006892 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006893 return TokError("fence cannot be monotonic");
6894
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006895 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006896 return InstNormal;
6897}
6898
Chris Lattnerac161bf2009-01-02 07:01:27 +00006899/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006900/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006901int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006902 Value *Ptr = nullptr;
6903 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006904 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006905
Dan Gohman16cbbe42009-07-29 15:58:36 +00006906 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006907
David Blaikie79e6c742015-02-27 19:29:02 +00006908 Type *Ty = nullptr;
6909 LocTy ExplicitTypeLoc = Lex.getLoc();
6910 if (ParseType(Ty) ||
6911 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6912 ParseTypeAndValue(Ptr, Loc, PFS))
6913 return true;
6914
Eli Benderskyd9806682013-04-22 17:03:42 +00006915 Type *BaseType = Ptr->getType();
6916 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6917 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006918 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006919
David Blaikie8d757942015-03-09 23:08:44 +00006920 if (Ty != BasePointerType->getElementType())
6921 return Error(ExplicitTypeLoc,
6922 "explicit pointee type doesn't match operand's pointee type");
6923
Chris Lattnerac161bf2009-01-02 07:01:27 +00006924 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006925 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006926 // GEP returns a vector of pointers if at least one of parameters is a vector.
6927 // All vector parameters should have the same vector width.
6928 unsigned GEPWidth = BaseType->isVectorTy() ?
6929 BaseType->getVectorNumElements() : 0;
6930
Chris Lattner3822f632009-01-02 08:05:26 +00006931 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006932 if (Lex.getKind() == lltok::MetadataVar) {
6933 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006934 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006935 }
Chris Lattner3822f632009-01-02 08:05:26 +00006936 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006937 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006938 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006939
Nadav Rotem3924cb02011-12-05 06:29:09 +00006940 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006941 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6942 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006943 return Error(EltLoc,
6944 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006945 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006946 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006947 Indices.push_back(Val);
6948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006949
Craig Toppere3dcce92015-08-01 22:20:21 +00006950 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006951 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006952 return Error(Loc, "base element of getelementptr must be sized");
6953
David Blaikied33bad32015-04-17 22:32:13 +00006954 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006955 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006956 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006957 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006958 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006959 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006960}
6961
6962/// ParseExtractValue
6963/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006964int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006965 Value *Val; LocTy Loc;
6966 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006967 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006968 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006969 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006970 return true;
6971
Chris Lattner392be582010-02-12 20:49:41 +00006972 if (!Val->getType()->isAggregateType())
6973 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006974
Jay Foad57aa6362011-07-13 10:26:04 +00006975 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006976 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006977 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006978 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006979}
6980
6981/// ParseInsertValue
6982/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006983int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006984 Value *Val0, *Val1; LocTy Loc0, Loc1;
6985 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006986 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006987 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6988 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6989 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006990 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006991 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006992
Chris Lattner392be582010-02-12 20:49:41 +00006993 if (!Val0->getType()->isAggregateType())
6994 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006995
David Majnemer30074532015-02-11 07:43:58 +00006996 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6997 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006998 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006999 if (IndexedType != Val1->getType())
7000 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
7001 getTypeString(Val1->getType()) + "' instead of '" +
7002 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00007003 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00007004 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007005}
Nick Lewycky49f89192009-04-04 07:22:01 +00007006
7007//===----------------------------------------------------------------------===//
7008// Embedded metadata.
7009//===----------------------------------------------------------------------===//
7010
7011/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007012/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00007013/// Element
7014/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007015bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00007016 if (ParseToken(lltok::lbrace, "expected '{' here"))
7017 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007018
Dan Gohman1e0213a2010-07-13 19:33:27 +00007019 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007020 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00007021 return false;
7022
Nick Lewycky49f89192009-04-04 07:22:01 +00007023 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00007024 // Null is a special case since it is typeless.
7025 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00007026 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00007027 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00007028 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00007029
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007030 Metadata *MD;
7031 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007032 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007033 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00007034 } while (EatIfPresent(lltok::comma));
7035
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007036 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00007037}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007038
7039//===----------------------------------------------------------------------===//
7040// Use-list order directives.
7041//===----------------------------------------------------------------------===//
7042bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7043 SMLoc Loc) {
7044 if (V->use_empty())
7045 return Error(Loc, "value has no uses");
7046
7047 unsigned NumUses = 0;
7048 SmallDenseMap<const Use *, unsigned, 16> Order;
7049 for (const Use &U : V->uses()) {
7050 if (++NumUses > Indexes.size())
7051 break;
7052 Order[&U] = Indexes[NumUses - 1];
7053 }
7054 if (NumUses < 2)
7055 return Error(Loc, "value only has one use");
7056 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00007057 return Error(Loc,
7058 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007059
7060 V->sortUseList([&](const Use &L, const Use &R) {
7061 return Order.lookup(&L) < Order.lookup(&R);
7062 });
7063 return false;
7064}
7065
7066/// ParseUseListOrderIndexes
7067/// ::= '{' uint32 (',' uint32)+ '}'
7068bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7069 SMLoc Loc = Lex.getLoc();
7070 if (ParseToken(lltok::lbrace, "expected '{' here"))
7071 return true;
7072 if (Lex.getKind() == lltok::rbrace)
7073 return Lex.Error("expected non-empty list of uselistorder indexes");
7074
7075 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7076 // indexes should be distinct numbers in the range [0, size-1], and should
7077 // not be in order.
7078 unsigned Offset = 0;
7079 unsigned Max = 0;
7080 bool IsOrdered = true;
7081 assert(Indexes.empty() && "Expected empty order vector");
7082 do {
7083 unsigned Index;
7084 if (ParseUInt32(Index))
7085 return true;
7086
7087 // Update consistency checks.
7088 Offset += Index - Indexes.size();
7089 Max = std::max(Max, Index);
7090 IsOrdered &= Index == Indexes.size();
7091
7092 Indexes.push_back(Index);
7093 } while (EatIfPresent(lltok::comma));
7094
7095 if (ParseToken(lltok::rbrace, "expected '}' here"))
7096 return true;
7097
7098 if (Indexes.size() < 2)
7099 return Error(Loc, "expected >= 2 uselistorder indexes");
7100 if (Offset != 0 || Max >= Indexes.size())
7101 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7102 if (IsOrdered)
7103 return Error(Loc, "expected uselistorder indexes to change the order");
7104
7105 return false;
7106}
7107
7108/// ParseUseListOrder
7109/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7110bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7111 SMLoc Loc = Lex.getLoc();
7112 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7113 return true;
7114
7115 Value *V;
7116 SmallVector<unsigned, 16> Indexes;
7117 if (ParseTypeAndValue(V, PFS) ||
7118 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7119 ParseUseListOrderIndexes(Indexes))
7120 return true;
7121
7122 return sortUseListOrder(V, Indexes, Loc);
7123}
7124
7125/// ParseUseListOrderBB
7126/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7127bool LLParser::ParseUseListOrderBB() {
7128 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7129 SMLoc Loc = Lex.getLoc();
7130 Lex.Lex();
7131
7132 ValID Fn, Label;
7133 SmallVector<unsigned, 16> Indexes;
7134 if (ParseValID(Fn) ||
7135 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7136 ParseValID(Label) ||
7137 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7138 ParseUseListOrderIndexes(Indexes))
7139 return true;
7140
7141 // Check the function.
7142 GlobalValue *GV;
7143 if (Fn.Kind == ValID::t_GlobalName)
7144 GV = M->getNamedValue(Fn.StrVal);
7145 else if (Fn.Kind == ValID::t_GlobalID)
7146 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7147 else
7148 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7149 if (!GV)
7150 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7151 auto *F = dyn_cast<Function>(GV);
7152 if (!F)
7153 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7154 if (F->isDeclaration())
7155 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7156
7157 // Check the basic block.
7158 if (Label.Kind == ValID::t_LocalID)
7159 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7160 if (Label.Kind != ValID::t_LocalName)
7161 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00007162 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007163 if (!V)
7164 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7165 if (!isa<BasicBlock>(V))
7166 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7167
7168 return sortUseListOrder(V, Indexes, Loc);
7169}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007170
7171/// ModuleEntry
7172/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7173/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7174bool LLParser::ParseModuleEntry(unsigned ID) {
7175 assert(Lex.getKind() == lltok::kw_module);
7176 Lex.Lex();
7177
7178 std::string Path;
7179 if (ParseToken(lltok::colon, "expected ':' here") ||
7180 ParseToken(lltok::lparen, "expected '(' here") ||
7181 ParseToken(lltok::kw_path, "expected 'path' here") ||
7182 ParseToken(lltok::colon, "expected ':' here") ||
7183 ParseStringConstant(Path) ||
7184 ParseToken(lltok::comma, "expected ',' here") ||
7185 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7186 ParseToken(lltok::colon, "expected ':' here") ||
7187 ParseToken(lltok::lparen, "expected '(' here"))
7188 return true;
7189
7190 ModuleHash Hash;
7191 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7192 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7193 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7194 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7195 ParseUInt32(Hash[4]))
7196 return true;
7197
7198 if (ParseToken(lltok::rparen, "expected ')' here") ||
7199 ParseToken(lltok::rparen, "expected ')' here"))
7200 return true;
7201
7202 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7203 ModuleIdMap[ID] = ModuleEntry->first();
7204
7205 return false;
7206}
7207
7208/// TypeIdEntry
7209/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7210bool LLParser::ParseTypeIdEntry(unsigned ID) {
7211 assert(Lex.getKind() == lltok::kw_typeid);
7212 Lex.Lex();
7213
7214 std::string Name;
7215 if (ParseToken(lltok::colon, "expected ':' here") ||
7216 ParseToken(lltok::lparen, "expected '(' here") ||
7217 ParseToken(lltok::kw_name, "expected 'name' here") ||
7218 ParseToken(lltok::colon, "expected ':' here") ||
7219 ParseStringConstant(Name))
7220 return true;
7221
7222 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7223 if (ParseToken(lltok::comma, "expected ',' here") ||
7224 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7225 return true;
7226
7227 // Check if this ID was forward referenced, and if so, update the
7228 // corresponding GUIDs.
7229 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7230 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7231 for (auto TIDRef : FwdRefTIDs->second) {
7232 assert(!*TIDRef.first &&
7233 "Forward referenced type id GUID expected to be 0");
7234 *TIDRef.first = GlobalValue::getGUID(Name);
7235 }
7236 ForwardRefTypeIds.erase(FwdRefTIDs);
7237 }
7238
7239 return false;
7240}
7241
7242/// TypeIdSummary
7243/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7244bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7245 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7246 ParseToken(lltok::colon, "expected ':' here") ||
7247 ParseToken(lltok::lparen, "expected '(' here") ||
7248 ParseTypeTestResolution(TIS.TTRes))
7249 return true;
7250
7251 if (EatIfPresent(lltok::comma)) {
7252 // Expect optional wpdResolutions field
7253 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7254 return true;
7255 }
7256
7257 if (ParseToken(lltok::rparen, "expected ')' here"))
7258 return true;
7259
7260 return false;
7261}
7262
Teresa Johnson4fcf3b12019-01-17 15:49:03 +00007263static ValueInfo EmptyVI =
7264 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7265
7266/// TypeIdMetadataEntry
7267/// ::= 'typeidMetadata' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdGVInfo
7268/// ')'
7269bool LLParser::ParseTypeIdMetadataEntry(unsigned ID) {
7270 assert(Lex.getKind() == lltok::kw_typeidMetadata);
7271 Lex.Lex();
7272
7273 std::string Name;
7274 if (ParseToken(lltok::colon, "expected ':' here") ||
7275 ParseToken(lltok::lparen, "expected '(' here") ||
7276 ParseToken(lltok::kw_name, "expected 'name' here") ||
7277 ParseToken(lltok::colon, "expected ':' here") ||
7278 ParseStringConstant(Name))
7279 return true;
7280
7281 TypeIdGVInfo &TI = Index->getOrInsertTypeIdMetadataSummary(Name);
7282 if (ParseToken(lltok::comma, "expected ',' here") ||
7283 ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7284 ParseToken(lltok::colon, "expected ':' here") ||
7285 ParseToken(lltok::lparen, "expected '(' here"))
7286 return true;
7287
7288 IdToIndexMapType IdToIndexMap;
7289 // Parse each call edge
7290 do {
7291 uint64_t Offset;
7292 if (ParseToken(lltok::lparen, "expected '(' here") ||
7293 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7294 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7295 ParseToken(lltok::comma, "expected ',' here"))
7296 return true;
7297
7298 LocTy Loc = Lex.getLoc();
7299 unsigned GVId;
7300 ValueInfo VI;
7301 if (ParseGVReference(VI, GVId))
7302 return true;
7303
7304 // Keep track of the TypeIdGVInfo array index needing a forward reference.
7305 // We will save the location of the ValueInfo needing an update, but
7306 // can only do so once the std::vector is finalized.
7307 if (VI == EmptyVI)
7308 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7309 TI.push_back({Offset, VI});
7310
7311 if (ParseToken(lltok::rparen, "expected ')' in call"))
7312 return true;
7313 } while (EatIfPresent(lltok::comma));
7314
7315 // Now that the TI vector is finalized, it is safe to save the locations
7316 // of any forward GV references that need updating later.
7317 for (auto I : IdToIndexMap) {
7318 for (auto P : I.second) {
7319 assert(TI[P.first].second == EmptyVI &&
7320 "Forward referenced ValueInfo expected to be empty");
7321 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7322 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7323 FwdRef.first->second.push_back(
7324 std::make_pair(&TI[P.first].second, P.second));
7325 }
7326 }
7327
7328 if (ParseToken(lltok::rparen, "expected ')' here") ||
7329 ParseToken(lltok::rparen, "expected ')' here"))
7330 return true;
7331
7332 // Check if this ID was forward referenced, and if so, update the
7333 // corresponding GUIDs.
7334 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7335 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7336 for (auto TIDRef : FwdRefTIDs->second) {
7337 assert(!*TIDRef.first &&
7338 "Forward referenced type id GUID expected to be 0");
7339 *TIDRef.first = GlobalValue::getGUID(Name);
7340 }
7341 ForwardRefTypeIds.erase(FwdRefTIDs);
7342 }
7343
7344 return false;
7345}
7346
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007347/// TypeTestResolution
7348/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7349/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7350/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7351/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7352/// [',' 'inlinesBits' ':' UInt64]? ')'
7353bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7354 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7355 ParseToken(lltok::colon, "expected ':' here") ||
7356 ParseToken(lltok::lparen, "expected '(' here") ||
7357 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7358 ParseToken(lltok::colon, "expected ':' here"))
7359 return true;
7360
7361 switch (Lex.getKind()) {
7362 case lltok::kw_unsat:
7363 TTRes.TheKind = TypeTestResolution::Unsat;
7364 break;
7365 case lltok::kw_byteArray:
7366 TTRes.TheKind = TypeTestResolution::ByteArray;
7367 break;
7368 case lltok::kw_inline:
7369 TTRes.TheKind = TypeTestResolution::Inline;
7370 break;
7371 case lltok::kw_single:
7372 TTRes.TheKind = TypeTestResolution::Single;
7373 break;
7374 case lltok::kw_allOnes:
7375 TTRes.TheKind = TypeTestResolution::AllOnes;
7376 break;
7377 default:
7378 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7379 }
7380 Lex.Lex();
7381
7382 if (ParseToken(lltok::comma, "expected ',' here") ||
7383 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7384 ParseToken(lltok::colon, "expected ':' here") ||
7385 ParseUInt32(TTRes.SizeM1BitWidth))
7386 return true;
7387
7388 // Parse optional fields
7389 while (EatIfPresent(lltok::comma)) {
7390 switch (Lex.getKind()) {
7391 case lltok::kw_alignLog2:
7392 Lex.Lex();
7393 if (ParseToken(lltok::colon, "expected ':'") ||
7394 ParseUInt64(TTRes.AlignLog2))
7395 return true;
7396 break;
7397 case lltok::kw_sizeM1:
7398 Lex.Lex();
7399 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7400 return true;
7401 break;
7402 case lltok::kw_bitMask: {
7403 unsigned Val;
7404 Lex.Lex();
7405 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7406 return true;
7407 assert(Val <= 0xff);
7408 TTRes.BitMask = (uint8_t)Val;
7409 break;
7410 }
7411 case lltok::kw_inlineBits:
7412 Lex.Lex();
7413 if (ParseToken(lltok::colon, "expected ':'") ||
7414 ParseUInt64(TTRes.InlineBits))
7415 return true;
7416 break;
7417 default:
7418 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7419 }
7420 }
7421
7422 if (ParseToken(lltok::rparen, "expected ')' here"))
7423 return true;
7424
7425 return false;
7426}
7427
7428/// OptionalWpdResolutions
7429/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7430/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7431bool LLParser::ParseOptionalWpdResolutions(
7432 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7433 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7434 ParseToken(lltok::colon, "expected ':' here") ||
7435 ParseToken(lltok::lparen, "expected '(' here"))
7436 return true;
7437
7438 do {
7439 uint64_t Offset;
7440 WholeProgramDevirtResolution WPDRes;
7441 if (ParseToken(lltok::lparen, "expected '(' here") ||
7442 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7443 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7444 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7445 ParseToken(lltok::rparen, "expected ')' here"))
7446 return true;
7447 WPDResMap[Offset] = WPDRes;
7448 } while (EatIfPresent(lltok::comma));
7449
7450 if (ParseToken(lltok::rparen, "expected ')' here"))
7451 return true;
7452
7453 return false;
7454}
7455
7456/// WpdRes
7457/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7458/// [',' OptionalResByArg]? ')'
7459/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7460/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7461/// [',' OptionalResByArg]? ')'
7462/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7463/// [',' OptionalResByArg]? ')'
7464bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7465 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7466 ParseToken(lltok::colon, "expected ':' here") ||
7467 ParseToken(lltok::lparen, "expected '(' here") ||
7468 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7469 ParseToken(lltok::colon, "expected ':' here"))
7470 return true;
7471
7472 switch (Lex.getKind()) {
7473 case lltok::kw_indir:
7474 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7475 break;
7476 case lltok::kw_singleImpl:
7477 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7478 break;
7479 case lltok::kw_branchFunnel:
7480 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7481 break;
7482 default:
7483 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7484 }
7485 Lex.Lex();
7486
7487 // Parse optional fields
7488 while (EatIfPresent(lltok::comma)) {
7489 switch (Lex.getKind()) {
7490 case lltok::kw_singleImplName:
7491 Lex.Lex();
7492 if (ParseToken(lltok::colon, "expected ':' here") ||
7493 ParseStringConstant(WPDRes.SingleImplName))
7494 return true;
7495 break;
7496 case lltok::kw_resByArg:
7497 if (ParseOptionalResByArg(WPDRes.ResByArg))
7498 return true;
7499 break;
7500 default:
7501 return Error(Lex.getLoc(),
7502 "expected optional WholeProgramDevirtResolution field");
7503 }
7504 }
7505
7506 if (ParseToken(lltok::rparen, "expected ')' here"))
7507 return true;
7508
7509 return false;
7510}
7511
7512/// OptionalResByArg
7513/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7514/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7515/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7516/// 'virtualConstProp' )
7517/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7518/// [',' 'bit' ':' UInt32]? ')'
7519bool LLParser::ParseOptionalResByArg(
7520 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7521 &ResByArg) {
7522 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7523 ParseToken(lltok::colon, "expected ':' here") ||
7524 ParseToken(lltok::lparen, "expected '(' here"))
7525 return true;
7526
7527 do {
7528 std::vector<uint64_t> Args;
7529 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7530 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7531 ParseToken(lltok::colon, "expected ':' here") ||
7532 ParseToken(lltok::lparen, "expected '(' here") ||
7533 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7534 ParseToken(lltok::colon, "expected ':' here"))
7535 return true;
7536
7537 WholeProgramDevirtResolution::ByArg ByArg;
7538 switch (Lex.getKind()) {
7539 case lltok::kw_indir:
7540 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7541 break;
7542 case lltok::kw_uniformRetVal:
7543 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7544 break;
7545 case lltok::kw_uniqueRetVal:
7546 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7547 break;
7548 case lltok::kw_virtualConstProp:
7549 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7550 break;
7551 default:
7552 return Error(Lex.getLoc(),
7553 "unexpected WholeProgramDevirtResolution::ByArg kind");
7554 }
7555 Lex.Lex();
7556
7557 // Parse optional fields
7558 while (EatIfPresent(lltok::comma)) {
7559 switch (Lex.getKind()) {
7560 case lltok::kw_info:
7561 Lex.Lex();
7562 if (ParseToken(lltok::colon, "expected ':' here") ||
7563 ParseUInt64(ByArg.Info))
7564 return true;
7565 break;
7566 case lltok::kw_byte:
7567 Lex.Lex();
7568 if (ParseToken(lltok::colon, "expected ':' here") ||
7569 ParseUInt32(ByArg.Byte))
7570 return true;
7571 break;
7572 case lltok::kw_bit:
7573 Lex.Lex();
7574 if (ParseToken(lltok::colon, "expected ':' here") ||
7575 ParseUInt32(ByArg.Bit))
7576 return true;
7577 break;
7578 default:
7579 return Error(Lex.getLoc(),
7580 "expected optional whole program devirt field");
7581 }
7582 }
7583
7584 if (ParseToken(lltok::rparen, "expected ')' here"))
7585 return true;
7586
7587 ResByArg[Args] = ByArg;
7588 } while (EatIfPresent(lltok::comma));
7589
7590 if (ParseToken(lltok::rparen, "expected ')' here"))
7591 return true;
7592
7593 return false;
7594}
7595
7596/// OptionalResByArg
7597/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7598bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7599 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7600 ParseToken(lltok::colon, "expected ':' here") ||
7601 ParseToken(lltok::lparen, "expected '(' here"))
7602 return true;
7603
7604 do {
7605 uint64_t Val;
7606 if (ParseUInt64(Val))
7607 return true;
7608 Args.push_back(Val);
7609 } while (EatIfPresent(lltok::comma));
7610
7611 if (ParseToken(lltok::rparen, "expected ')' here"))
7612 return true;
7613
7614 return false;
7615}
7616
Benjamin Kramerb17d2132019-01-12 18:36:22 +00007617static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
Eugene Leviant009d8332018-11-23 10:54:51 +00007618
7619static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7620 bool ReadOnly = Fwd->isReadOnly();
7621 *Fwd = Resolved;
7622 if (ReadOnly)
7623 Fwd->setReadOnly();
7624}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007625
7626/// Stores the given Name/GUID and associated summary into the Index.
7627/// Also updates any forward references to the associated entry ID.
7628void LLParser::AddGlobalValueToIndex(
7629 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7630 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7631 // First create the ValueInfo utilizing the Name or GUID.
7632 ValueInfo VI;
7633 if (GUID != 0) {
7634 assert(Name.empty());
7635 VI = Index->getOrInsertValueInfo(GUID);
7636 } else {
7637 assert(!Name.empty());
7638 if (M) {
7639 auto *GV = M->getNamedValue(Name);
7640 assert(GV);
7641 VI = Index->getOrInsertValueInfo(GV);
7642 } else {
7643 assert(
7644 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7645 "Need a source_filename to compute GUID for local");
7646 GUID = GlobalValue::getGUID(
7647 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7648 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7649 }
7650 }
7651
7652 // Add the summary if one was provided.
7653 if (Summary)
7654 Index->addGlobalValueSummary(VI, std::move(Summary));
7655
7656 // Resolve forward references from calls/refs
7657 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7658 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7659 for (auto VIRef : FwdRefVIs->second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00007660 assert(VIRef.first->getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007661 "Forward referenced ValueInfo expected to be empty");
Eugene Leviant009d8332018-11-23 10:54:51 +00007662 resolveFwdRef(VIRef.first, VI);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007663 }
7664 ForwardRefValueInfos.erase(FwdRefVIs);
7665 }
7666
7667 // Resolve forward references from aliases
7668 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7669 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7670 for (auto AliaseeRef : FwdRefAliasees->second) {
7671 assert(!AliaseeRef.first->hasAliasee() &&
7672 "Forward referencing alias already has aliasee");
7673 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7674 }
7675 ForwardRefAliasees.erase(FwdRefAliasees);
7676 }
7677
7678 // Save the associated ValueInfo for use in later references by ID.
7679 if (ID == NumberedValueInfos.size())
7680 NumberedValueInfos.push_back(VI);
7681 else {
7682 // Handle non-continuous numbers (to make test simplification easier).
7683 if (ID > NumberedValueInfos.size())
7684 NumberedValueInfos.resize(ID + 1);
7685 NumberedValueInfos[ID] = VI;
7686 }
7687}
7688
7689/// ParseGVEntry
7690/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7691/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7692/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7693bool LLParser::ParseGVEntry(unsigned ID) {
7694 assert(Lex.getKind() == lltok::kw_gv);
7695 Lex.Lex();
7696
7697 if (ParseToken(lltok::colon, "expected ':' here") ||
7698 ParseToken(lltok::lparen, "expected '(' here"))
7699 return true;
7700
7701 std::string Name;
7702 GlobalValue::GUID GUID = 0;
7703 switch (Lex.getKind()) {
7704 case lltok::kw_name:
7705 Lex.Lex();
7706 if (ParseToken(lltok::colon, "expected ':' here") ||
7707 ParseStringConstant(Name))
7708 return true;
7709 // Can't create GUID/ValueInfo until we have the linkage.
7710 break;
7711 case lltok::kw_guid:
7712 Lex.Lex();
7713 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7714 return true;
7715 break;
7716 default:
7717 return Error(Lex.getLoc(), "expected name or guid tag");
7718 }
7719
7720 if (!EatIfPresent(lltok::comma)) {
7721 // No summaries. Wrap up.
7722 if (ParseToken(lltok::rparen, "expected ')' here"))
7723 return true;
7724 // This was created for a call to an external or indirect target.
7725 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7726 // created for indirect calls with VP. A Name with no GUID came from
7727 // an external definition. We pass ExternalLinkage since that is only
7728 // used when the GUID must be computed from Name, and in that case
7729 // the symbol must have external linkage.
7730 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7731 nullptr);
7732 return false;
7733 }
7734
7735 // Have a list of summaries
7736 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7737 ParseToken(lltok::colon, "expected ':' here"))
7738 return true;
7739
7740 do {
7741 if (ParseToken(lltok::lparen, "expected '(' here"))
7742 return true;
7743 switch (Lex.getKind()) {
7744 case lltok::kw_function:
7745 if (ParseFunctionSummary(Name, GUID, ID))
7746 return true;
7747 break;
7748 case lltok::kw_variable:
7749 if (ParseVariableSummary(Name, GUID, ID))
7750 return true;
7751 break;
7752 case lltok::kw_alias:
7753 if (ParseAliasSummary(Name, GUID, ID))
7754 return true;
7755 break;
7756 default:
7757 return Error(Lex.getLoc(), "expected summary type");
7758 }
7759 if (ParseToken(lltok::rparen, "expected ')' here"))
7760 return true;
7761 } while (EatIfPresent(lltok::comma));
7762
7763 if (ParseToken(lltok::rparen, "expected ')' here"))
7764 return true;
7765
7766 return false;
7767}
7768
7769/// FunctionSummary
7770/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7771/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7772/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7773bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7774 unsigned ID) {
7775 assert(Lex.getKind() == lltok::kw_function);
7776 Lex.Lex();
7777
7778 StringRef ModulePath;
7779 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7780 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7781 /*Live=*/false, /*IsLocal=*/false);
7782 unsigned InstCount;
7783 std::vector<FunctionSummary::EdgeTy> Calls;
7784 FunctionSummary::TypeIdInfo TypeIdInfo;
7785 std::vector<ValueInfo> Refs;
7786 // Default is all-zeros (conservative values).
7787 FunctionSummary::FFlags FFlags = {};
7788 if (ParseToken(lltok::colon, "expected ':' here") ||
7789 ParseToken(lltok::lparen, "expected '(' here") ||
7790 ParseModuleReference(ModulePath) ||
7791 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7792 ParseToken(lltok::comma, "expected ',' here") ||
7793 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7794 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7795 return true;
7796
7797 // Parse optional fields
7798 while (EatIfPresent(lltok::comma)) {
7799 switch (Lex.getKind()) {
7800 case lltok::kw_funcFlags:
7801 if (ParseOptionalFFlags(FFlags))
7802 return true;
7803 break;
7804 case lltok::kw_calls:
7805 if (ParseOptionalCalls(Calls))
7806 return true;
7807 break;
7808 case lltok::kw_typeIdInfo:
7809 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7810 return true;
7811 break;
7812 case lltok::kw_refs:
7813 if (ParseOptionalRefs(Refs))
7814 return true;
7815 break;
7816 default:
7817 return Error(Lex.getLoc(), "expected optional function summary field");
7818 }
7819 }
7820
7821 if (ParseToken(lltok::rparen, "expected ')' here"))
7822 return true;
7823
7824 auto FS = llvm::make_unique<FunctionSummary>(
Easwaran Raman5a7056f2018-12-13 19:54:27 +00007825 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
7826 std::move(Calls), std::move(TypeIdInfo.TypeTests),
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007827 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7828 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7829 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7830 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7831
7832 FS->setModulePath(ModulePath);
7833
7834 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7835 ID, std::move(FS));
7836
7837 return false;
7838}
7839
7840/// VariableSummary
7841/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7842/// [',' OptionalRefs]? ')'
7843bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7844 unsigned ID) {
7845 assert(Lex.getKind() == lltok::kw_variable);
7846 Lex.Lex();
7847
7848 StringRef ModulePath;
7849 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7850 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7851 /*Live=*/false, /*IsLocal=*/false);
Eugene Leviant009d8332018-11-23 10:54:51 +00007852 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007853 std::vector<ValueInfo> Refs;
Teresa Johnson4fcf3b12019-01-17 15:49:03 +00007854 VTableFuncList VTableFuncs;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007855 if (ParseToken(lltok::colon, "expected ':' here") ||
7856 ParseToken(lltok::lparen, "expected '(' here") ||
7857 ParseModuleReference(ModulePath) ||
Eugene Leviant009d8332018-11-23 10:54:51 +00007858 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7859 ParseToken(lltok::comma, "expected ',' here") ||
7860 ParseGVarFlags(GVarFlags))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007861 return true;
7862
Teresa Johnson4fcf3b12019-01-17 15:49:03 +00007863 // Parse optional fields
7864 while (EatIfPresent(lltok::comma)) {
7865 switch (Lex.getKind()) {
7866 case lltok::kw_vTableFuncs:
7867 if (ParseOptionalVTableFuncs(VTableFuncs))
7868 return true;
7869 break;
7870 case lltok::kw_refs:
7871 if (ParseOptionalRefs(Refs))
7872 return true;
7873 break;
7874 default:
7875 return Error(Lex.getLoc(), "expected optional variable summary field");
7876 }
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007877 }
7878
7879 if (ParseToken(lltok::rparen, "expected ')' here"))
7880 return true;
7881
Eugene Leviant009d8332018-11-23 10:54:51 +00007882 auto GS =
7883 llvm::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007884
7885 GS->setModulePath(ModulePath);
Teresa Johnson4fcf3b12019-01-17 15:49:03 +00007886 GS->setVTableFuncs(std::move(VTableFuncs));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007887
7888 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7889 ID, std::move(GS));
7890
7891 return false;
7892}
7893
7894/// AliasSummary
7895/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7896/// 'aliasee' ':' GVReference ')'
7897bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7898 unsigned ID) {
7899 assert(Lex.getKind() == lltok::kw_alias);
7900 LocTy Loc = Lex.getLoc();
7901 Lex.Lex();
7902
7903 StringRef ModulePath;
7904 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7905 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7906 /*Live=*/false, /*IsLocal=*/false);
7907 if (ParseToken(lltok::colon, "expected ':' here") ||
7908 ParseToken(lltok::lparen, "expected '(' here") ||
7909 ParseModuleReference(ModulePath) ||
7910 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7911 ParseToken(lltok::comma, "expected ',' here") ||
7912 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7913 ParseToken(lltok::colon, "expected ':' here"))
7914 return true;
7915
7916 ValueInfo AliaseeVI;
7917 unsigned GVId;
7918 if (ParseGVReference(AliaseeVI, GVId))
7919 return true;
7920
7921 if (ParseToken(lltok::rparen, "expected ')' here"))
7922 return true;
7923
7924 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7925
7926 AS->setModulePath(ModulePath);
7927
7928 // Record forward reference if the aliasee is not parsed yet.
Eugene Leviant009d8332018-11-23 10:54:51 +00007929 if (AliaseeVI.getRef() == FwdVIRef) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007930 auto FwdRef = ForwardRefAliasees.insert(
7931 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7932 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7933 } else
7934 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7935
7936 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7937 ID, std::move(AS));
7938
7939 return false;
7940}
7941
7942/// Flag
7943/// ::= [0|1]
7944bool LLParser::ParseFlag(unsigned &Val) {
7945 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7946 return TokError("expected integer");
7947 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7948 Lex.Lex();
7949 return false;
7950}
7951
7952/// OptionalFFlags
7953/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7954/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7955/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
Teresa Johnsoncb397462018-11-06 19:41:35 +00007956/// [',' 'noInline' ':' Flag]? ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007957bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7958 assert(Lex.getKind() == lltok::kw_funcFlags);
7959 Lex.Lex();
7960
7961 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7962 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7963 return true;
7964
7965 do {
7966 unsigned Val;
7967 switch (Lex.getKind()) {
7968 case lltok::kw_readNone:
7969 Lex.Lex();
7970 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7971 return true;
7972 FFlags.ReadNone = Val;
7973 break;
7974 case lltok::kw_readOnly:
7975 Lex.Lex();
7976 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7977 return true;
7978 FFlags.ReadOnly = Val;
7979 break;
7980 case lltok::kw_noRecurse:
7981 Lex.Lex();
7982 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7983 return true;
7984 FFlags.NoRecurse = Val;
7985 break;
7986 case lltok::kw_returnDoesNotAlias:
7987 Lex.Lex();
7988 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7989 return true;
7990 FFlags.ReturnDoesNotAlias = Val;
7991 break;
Teresa Johnsoncb397462018-11-06 19:41:35 +00007992 case lltok::kw_noInline:
7993 Lex.Lex();
7994 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7995 return true;
7996 FFlags.NoInline = Val;
7997 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007998 default:
7999 return Error(Lex.getLoc(), "expected function flag type");
8000 }
8001 } while (EatIfPresent(lltok::comma));
8002
8003 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
8004 return true;
8005
8006 return false;
8007}
8008
8009/// OptionalCalls
8010/// := 'calls' ':' '(' Call [',' Call]* ')'
8011/// Call ::= '(' 'callee' ':' GVReference
8012/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8013bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8014 assert(Lex.getKind() == lltok::kw_calls);
8015 Lex.Lex();
8016
8017 if (ParseToken(lltok::colon, "expected ':' in calls") |
8018 ParseToken(lltok::lparen, "expected '(' in calls"))
8019 return true;
8020
8021 IdToIndexMapType IdToIndexMap;
8022 // Parse each call edge
8023 do {
8024 ValueInfo VI;
8025 if (ParseToken(lltok::lparen, "expected '(' in call") ||
8026 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
8027 ParseToken(lltok::colon, "expected ':'"))
8028 return true;
8029
8030 LocTy Loc = Lex.getLoc();
8031 unsigned GVId;
8032 if (ParseGVReference(VI, GVId))
8033 return true;
8034
8035 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8036 unsigned RelBF = 0;
8037 if (EatIfPresent(lltok::comma)) {
8038 // Expect either hotness or relbf
8039 if (EatIfPresent(lltok::kw_hotness)) {
8040 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
8041 return true;
8042 } else {
8043 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
8044 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
8045 return true;
8046 }
8047 }
8048 // Keep track of the Call array index needing a forward reference.
8049 // We will save the location of the ValueInfo needing an update, but
8050 // can only do so once the std::vector is finalized.
Eugene Leviant009d8332018-11-23 10:54:51 +00008051 if (VI.getRef() == FwdVIRef)
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008052 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8053 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8054
8055 if (ParseToken(lltok::rparen, "expected ')' in call"))
8056 return true;
8057 } while (EatIfPresent(lltok::comma));
8058
8059 // Now that the Calls vector is finalized, it is safe to save the locations
8060 // of any forward GV references that need updating later.
8061 for (auto I : IdToIndexMap) {
8062 for (auto P : I.second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008063 assert(Calls[P.first].first.getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008064 "Forward referenced ValueInfo expected to be empty");
8065 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8066 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8067 FwdRef.first->second.push_back(
8068 std::make_pair(&Calls[P.first].first, P.second));
8069 }
8070 }
8071
8072 if (ParseToken(lltok::rparen, "expected ')' in calls"))
8073 return true;
8074
8075 return false;
8076}
8077
8078/// Hotness
8079/// := ('unknown'|'cold'|'none'|'hot'|'critical')
8080bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
8081 switch (Lex.getKind()) {
8082 case lltok::kw_unknown:
8083 Hotness = CalleeInfo::HotnessType::Unknown;
8084 break;
8085 case lltok::kw_cold:
8086 Hotness = CalleeInfo::HotnessType::Cold;
8087 break;
8088 case lltok::kw_none:
8089 Hotness = CalleeInfo::HotnessType::None;
8090 break;
8091 case lltok::kw_hot:
8092 Hotness = CalleeInfo::HotnessType::Hot;
8093 break;
8094 case lltok::kw_critical:
8095 Hotness = CalleeInfo::HotnessType::Critical;
8096 break;
8097 default:
8098 return Error(Lex.getLoc(), "invalid call edge hotness");
8099 }
8100 Lex.Lex();
8101 return false;
8102}
8103
Teresa Johnson4fcf3b12019-01-17 15:49:03 +00008104/// OptionalVTableFuncs
8105/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8106/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8107bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8108 assert(Lex.getKind() == lltok::kw_vTableFuncs);
8109 Lex.Lex();
8110
8111 if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") |
8112 ParseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8113 return true;
8114
8115 IdToIndexMapType IdToIndexMap;
8116 // Parse each virtual function pair
8117 do {
8118 ValueInfo VI;
8119 if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8120 ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8121 ParseToken(lltok::colon, "expected ':'"))
8122 return true;
8123
8124 LocTy Loc = Lex.getLoc();
8125 unsigned GVId;
8126 if (ParseGVReference(VI, GVId))
8127 return true;
8128
8129 uint64_t Offset;
8130 if (ParseToken(lltok::comma, "expected comma") ||
8131 ParseToken(lltok::kw_offset, "expected offset") ||
8132 ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset))
8133 return true;
8134
8135 // Keep track of the VTableFuncs array index needing a forward reference.
8136 // We will save the location of the ValueInfo needing an update, but
8137 // can only do so once the std::vector is finalized.
8138 if (VI == EmptyVI)
8139 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8140 VTableFuncs.push_back(std::make_pair(VI, Offset));
8141
8142 if (ParseToken(lltok::rparen, "expected ')' in vTableFunc"))
8143 return true;
8144 } while (EatIfPresent(lltok::comma));
8145
8146 // Now that the VTableFuncs vector is finalized, it is safe to save the
8147 // locations of any forward GV references that need updating later.
8148 for (auto I : IdToIndexMap) {
8149 for (auto P : I.second) {
8150 assert(VTableFuncs[P.first].first == EmptyVI &&
8151 "Forward referenced ValueInfo expected to be empty");
8152 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8153 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8154 FwdRef.first->second.push_back(
8155 std::make_pair(&VTableFuncs[P.first].first, P.second));
8156 }
8157 }
8158
8159 if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8160 return true;
8161
8162 return false;
8163}
8164
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008165/// OptionalRefs
8166/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8167bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8168 assert(Lex.getKind() == lltok::kw_refs);
8169 Lex.Lex();
8170
8171 if (ParseToken(lltok::colon, "expected ':' in refs") |
8172 ParseToken(lltok::lparen, "expected '(' in refs"))
8173 return true;
8174
Eugene Leviant009d8332018-11-23 10:54:51 +00008175 struct ValueContext {
8176 ValueInfo VI;
8177 unsigned GVId;
8178 LocTy Loc;
8179 };
8180 std::vector<ValueContext> VContexts;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008181 // Parse each ref edge
8182 do {
Eugene Leviant009d8332018-11-23 10:54:51 +00008183 ValueContext VC;
8184 VC.Loc = Lex.getLoc();
8185 if (ParseGVReference(VC.VI, VC.GVId))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008186 return true;
Eugene Leviant009d8332018-11-23 10:54:51 +00008187 VContexts.push_back(VC);
8188 } while (EatIfPresent(lltok::comma));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008189
Eugene Leviant009d8332018-11-23 10:54:51 +00008190 // Sort value contexts so that ones with readonly ValueInfo are at the end
8191 // of VContexts vector. This is needed to match immutableRefCount() behavior.
Eugene Leviant972e3482018-11-23 11:28:58 +00008192 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008193 return VC1.VI.isReadOnly() < VC2.VI.isReadOnly();
8194 });
8195
8196 IdToIndexMapType IdToIndexMap;
8197 for (auto &VC : VContexts) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008198 // Keep track of the Refs array index needing a forward reference.
8199 // We will save the location of the ValueInfo needing an update, but
8200 // can only do so once the std::vector is finalized.
Eugene Leviant009d8332018-11-23 10:54:51 +00008201 if (VC.VI.getRef() == FwdVIRef)
8202 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8203 Refs.push_back(VC.VI);
8204 }
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008205
8206 // Now that the Refs vector is finalized, it is safe to save the locations
8207 // of any forward GV references that need updating later.
8208 for (auto I : IdToIndexMap) {
8209 for (auto P : I.second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008210 assert(Refs[P.first].getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008211 "Forward referenced ValueInfo expected to be empty");
8212 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8213 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8214 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8215 }
8216 }
8217
8218 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8219 return true;
8220
8221 return false;
8222}
8223
8224/// OptionalTypeIdInfo
8225/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8226/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8227/// [',' TypeCheckedLoadConstVCalls]? ')'
8228bool LLParser::ParseOptionalTypeIdInfo(
8229 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8230 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8231 Lex.Lex();
8232
8233 if (ParseToken(lltok::colon, "expected ':' here") ||
8234 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8235 return true;
8236
8237 do {
8238 switch (Lex.getKind()) {
8239 case lltok::kw_typeTests:
8240 if (ParseTypeTests(TypeIdInfo.TypeTests))
8241 return true;
8242 break;
8243 case lltok::kw_typeTestAssumeVCalls:
8244 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8245 TypeIdInfo.TypeTestAssumeVCalls))
8246 return true;
8247 break;
8248 case lltok::kw_typeCheckedLoadVCalls:
8249 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8250 TypeIdInfo.TypeCheckedLoadVCalls))
8251 return true;
8252 break;
8253 case lltok::kw_typeTestAssumeConstVCalls:
8254 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8255 TypeIdInfo.TypeTestAssumeConstVCalls))
8256 return true;
8257 break;
8258 case lltok::kw_typeCheckedLoadConstVCalls:
8259 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8260 TypeIdInfo.TypeCheckedLoadConstVCalls))
8261 return true;
8262 break;
8263 default:
8264 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8265 }
8266 } while (EatIfPresent(lltok::comma));
8267
8268 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8269 return true;
8270
8271 return false;
8272}
8273
8274/// TypeTests
8275/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8276/// [',' (SummaryID | UInt64)]* ')'
8277bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8278 assert(Lex.getKind() == lltok::kw_typeTests);
8279 Lex.Lex();
8280
8281 if (ParseToken(lltok::colon, "expected ':' here") ||
8282 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8283 return true;
8284
8285 IdToIndexMapType IdToIndexMap;
8286 do {
8287 GlobalValue::GUID GUID = 0;
8288 if (Lex.getKind() == lltok::SummaryID) {
8289 unsigned ID = Lex.getUIntVal();
8290 LocTy Loc = Lex.getLoc();
8291 // Keep track of the TypeTests array index needing a forward reference.
8292 // We will save the location of the GUID needing an update, but
8293 // can only do so once the std::vector is finalized.
8294 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8295 Lex.Lex();
8296 } else if (ParseUInt64(GUID))
8297 return true;
8298 TypeTests.push_back(GUID);
8299 } while (EatIfPresent(lltok::comma));
8300
8301 // Now that the TypeTests vector is finalized, it is safe to save the
8302 // locations of any forward GV references that need updating later.
8303 for (auto I : IdToIndexMap) {
8304 for (auto P : I.second) {
8305 assert(TypeTests[P.first] == 0 &&
8306 "Forward referenced type id GUID expected to be 0");
8307 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8308 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8309 FwdRef.first->second.push_back(
8310 std::make_pair(&TypeTests[P.first], P.second));
8311 }
8312 }
8313
8314 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8315 return true;
8316
8317 return false;
8318}
8319
8320/// VFuncIdList
8321/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8322bool LLParser::ParseVFuncIdList(
8323 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8324 assert(Lex.getKind() == Kind);
8325 Lex.Lex();
8326
8327 if (ParseToken(lltok::colon, "expected ':' here") ||
8328 ParseToken(lltok::lparen, "expected '(' here"))
8329 return true;
8330
8331 IdToIndexMapType IdToIndexMap;
8332 do {
8333 FunctionSummary::VFuncId VFuncId;
8334 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8335 return true;
8336 VFuncIdList.push_back(VFuncId);
8337 } while (EatIfPresent(lltok::comma));
8338
8339 if (ParseToken(lltok::rparen, "expected ')' here"))
8340 return true;
8341
8342 // Now that the VFuncIdList vector is finalized, it is safe to save the
8343 // locations of any forward GV references that need updating later.
8344 for (auto I : IdToIndexMap) {
8345 for (auto P : I.second) {
8346 assert(VFuncIdList[P.first].GUID == 0 &&
8347 "Forward referenced type id GUID expected to be 0");
8348 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8349 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8350 FwdRef.first->second.push_back(
8351 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8352 }
8353 }
8354
8355 return false;
8356}
8357
8358/// ConstVCallList
8359/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8360bool LLParser::ParseConstVCallList(
8361 lltok::Kind Kind,
8362 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8363 assert(Lex.getKind() == Kind);
8364 Lex.Lex();
8365
8366 if (ParseToken(lltok::colon, "expected ':' here") ||
8367 ParseToken(lltok::lparen, "expected '(' here"))
8368 return true;
8369
8370 IdToIndexMapType IdToIndexMap;
8371 do {
8372 FunctionSummary::ConstVCall ConstVCall;
8373 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8374 return true;
8375 ConstVCallList.push_back(ConstVCall);
8376 } while (EatIfPresent(lltok::comma));
8377
8378 if (ParseToken(lltok::rparen, "expected ')' here"))
8379 return true;
8380
8381 // Now that the ConstVCallList vector is finalized, it is safe to save the
8382 // locations of any forward GV references that need updating later.
8383 for (auto I : IdToIndexMap) {
8384 for (auto P : I.second) {
8385 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8386 "Forward referenced type id GUID expected to be 0");
8387 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8388 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8389 FwdRef.first->second.push_back(
8390 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8391 }
8392 }
8393
8394 return false;
8395}
8396
8397/// ConstVCall
Teresa Johnsonc7816802018-08-14 01:49:33 +00008398/// ::= '(' VFuncId ',' Args ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008399bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8400 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsonc7816802018-08-14 01:49:33 +00008401 if (ParseToken(lltok::lparen, "expected '(' here") ||
8402 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8403 return true;
8404
8405 if (EatIfPresent(lltok::comma))
8406 if (ParseArgs(ConstVCall.Args))
8407 return true;
8408
8409 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008410 return true;
8411
8412 return false;
8413}
8414
8415/// VFuncId
8416/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8417/// 'offset' ':' UInt64 ')'
8418bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8419 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8420 assert(Lex.getKind() == lltok::kw_vFuncId);
8421 Lex.Lex();
8422
8423 if (ParseToken(lltok::colon, "expected ':' here") ||
8424 ParseToken(lltok::lparen, "expected '(' here"))
8425 return true;
8426
8427 if (Lex.getKind() == lltok::SummaryID) {
8428 VFuncId.GUID = 0;
8429 unsigned ID = Lex.getUIntVal();
8430 LocTy Loc = Lex.getLoc();
8431 // Keep track of the array index needing a forward reference.
8432 // We will save the location of the GUID needing an update, but
8433 // can only do so once the caller's std::vector is finalized.
8434 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8435 Lex.Lex();
8436 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8437 ParseToken(lltok::colon, "expected ':' here") ||
8438 ParseUInt64(VFuncId.GUID))
8439 return true;
8440
8441 if (ParseToken(lltok::comma, "expected ',' here") ||
8442 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8443 ParseToken(lltok::colon, "expected ':' here") ||
8444 ParseUInt64(VFuncId.Offset) ||
8445 ParseToken(lltok::rparen, "expected ')' here"))
8446 return true;
8447
8448 return false;
8449}
8450
8451/// GVFlags
8452/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8453/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8454/// 'dsoLocal' ':' Flag ')'
8455bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8456 assert(Lex.getKind() == lltok::kw_flags);
8457 Lex.Lex();
8458
8459 bool HasLinkage;
8460 if (ParseToken(lltok::colon, "expected ':' here") ||
8461 ParseToken(lltok::lparen, "expected '(' here") ||
8462 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8463 ParseToken(lltok::colon, "expected ':' here"))
8464 return true;
8465
8466 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8467 assert(HasLinkage && "Linkage not optional in summary entry");
8468 Lex.Lex();
8469
8470 unsigned Flag;
8471 if (ParseToken(lltok::comma, "expected ',' here") ||
8472 ParseToken(lltok::kw_notEligibleToImport,
8473 "expected 'notEligibleToImport' here") ||
8474 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8475 return true;
8476 GVFlags.NotEligibleToImport = Flag;
8477
8478 if (ParseToken(lltok::comma, "expected ',' here") ||
8479 ParseToken(lltok::kw_live, "expected 'live' here") ||
8480 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8481 return true;
8482 GVFlags.Live = Flag;
8483
8484 if (ParseToken(lltok::comma, "expected ',' here") ||
8485 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8486 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8487 return true;
8488 GVFlags.DSOLocal = Flag;
8489
8490 if (ParseToken(lltok::rparen, "expected ')' here"))
8491 return true;
8492
8493 return false;
8494}
8495
Eugene Leviant009d8332018-11-23 10:54:51 +00008496/// GVarFlags
8497/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8498bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8499 assert(Lex.getKind() == lltok::kw_varFlags);
8500 Lex.Lex();
8501
8502 unsigned Flag;
8503 if (ParseToken(lltok::colon, "expected ':' here") ||
8504 ParseToken(lltok::lparen, "expected '(' here") ||
8505 ParseToken(lltok::kw_readonly, "expected 'readonly' here") ||
8506 ParseToken(lltok::colon, "expected ':' here"))
8507 return true;
8508
8509 ParseFlag(Flag);
8510 GVarFlags.ReadOnly = Flag;
8511
8512 if (ParseToken(lltok::rparen, "expected ')' here"))
8513 return true;
8514 return false;
8515}
8516
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008517/// ModuleReference
8518/// ::= 'module' ':' UInt
8519bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8520 // Parse module id.
8521 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8522 ParseToken(lltok::colon, "expected ':' here") ||
8523 ParseToken(lltok::SummaryID, "expected module ID"))
8524 return true;
8525
8526 unsigned ModuleID = Lex.getUIntVal();
8527 auto I = ModuleIdMap.find(ModuleID);
8528 // We should have already parsed all module IDs
8529 assert(I != ModuleIdMap.end());
8530 ModulePath = I->second;
8531 return false;
8532}
8533
8534/// GVReference
8535/// ::= SummaryID
8536bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008537 bool ReadOnly = EatIfPresent(lltok::kw_readonly);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008538 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8539 return true;
8540
8541 GVId = Lex.getUIntVal();
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008542 // Check if we already have a VI for this GV
8543 if (GVId < NumberedValueInfos.size()) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008544 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008545 VI = NumberedValueInfos[GVId];
8546 } else
8547 // We will create a forward reference to the stored location.
Eugene Leviant009d8332018-11-23 10:54:51 +00008548 VI = ValueInfo(false, FwdVIRef);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008549
Eugene Leviant009d8332018-11-23 10:54:51 +00008550 if (ReadOnly)
8551 VI.setReadOnly();
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008552 return false;
8553}