blob: 0f28864534e78b9668992c96999e2071182f526c [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
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
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() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000127 AttrBuilder B;
128
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000131
132 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000133 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136
137 FnAttrs.merge(B);
138
139 // If the alignment was parsed as an attribute, move to the alignment
140 // field.
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
144 }
145
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000150 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000153 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000158 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000161 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000164 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
167 Attrs.merge(B);
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000169 } else {
170 llvm_unreachable("invalid object with forward attribute group reference");
171 }
172 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000173
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000179
David Majnemer19b51052015-02-11 07:43:56 +0000180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
195
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
199 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000204 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Devang Pateld2541152009-07-08 19:23:54 +0000206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
215 }
Devang Pateld2541152009-07-08 19:23:54 +0000216
Mehdi Aminie4709272016-09-14 22:29:59 +0000217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000224
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000228
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
237 }
238 }
239
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000240 if (UpgradeDebugInfo)
241 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000242
Manman Renb5d7ff42016-05-25 23:14:48 +0000243 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000244 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000245
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000246 if (!Slots)
247 return false;
248 // Initialize the slot mapping.
249 // Because by this point we've parsed and validated everything, we can "steal"
250 // the mapping from LLParser as it doesn't need it anymore.
251 Slots->GlobalValues = std::move(NumberedVals);
252 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000253 for (const auto &I : NamedTypes)
254 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
255 for (const auto &I : NumberedTypes)
256 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000257
Chris Lattnerac161bf2009-01-02 07:01:27 +0000258 return false;
259}
260
261//===----------------------------------------------------------------------===//
262// Top-Level Entities
263//===----------------------------------------------------------------------===//
264
265bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000266 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000267 switch (Lex.getKind()) {
268 default: return TokError("expected top-level entity");
269 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000270 case lltok::kw_declare: if (ParseDeclare()) return true; break;
271 case lltok::kw_define: if (ParseDefine()) return true; break;
272 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
273 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000274 case lltok::kw_source_filename:
275 if (ParseSourceFileName())
276 return true;
277 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000278 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000279 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000281 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000282 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000283 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000284 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000285 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000287 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
288 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000289 if (ParseUseListOrderBB())
290 return true;
291 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 }
293 }
294}
295
Chris Lattnerac161bf2009-01-02 07:01:27 +0000296/// toplevelentity
297/// ::= 'module' 'asm' STRINGCONSTANT
298bool LLParser::ParseModuleAsm() {
299 assert(Lex.getKind() == lltok::kw_module);
300 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000301
302 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000303 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
304 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000305
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000306 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000307 return false;
308}
309
310/// toplevelentity
311/// ::= 'target' 'triple' '=' STRINGCONSTANT
312/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
313bool LLParser::ParseTargetDefinition() {
314 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000315 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000316 switch (Lex.Lex()) {
317 default: return TokError("unknown target property");
318 case lltok::kw_triple:
319 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000320 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
321 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000323 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324 return false;
325 case lltok::kw_datalayout:
326 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000327 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
328 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000330 if (DataLayoutStr.empty())
331 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 return false;
333 }
334}
335
Bill Wendling706d3d62012-11-28 08:41:48 +0000336/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000337/// ::= 'source_filename' '=' STRINGCONSTANT
338bool LLParser::ParseSourceFileName() {
339 assert(Lex.getKind() == lltok::kw_source_filename);
340 std::string Str;
341 Lex.Lex();
342 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
343 ParseStringConstant(Str))
344 return true;
345 M->setSourceFileName(Str);
346 return false;
347}
348
349/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000350/// ::= 'deplibs' '=' '[' ']'
351/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
352/// FIXME: Remove in 4.0. Currently parse, but ignore.
353bool LLParser::ParseDepLibs() {
354 assert(Lex.getKind() == lltok::kw_deplibs);
355 Lex.Lex();
356 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
357 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
358 return true;
359
360 if (EatIfPresent(lltok::rsquare))
361 return false;
362
363 do {
364 std::string Str;
365 if (ParseStringConstant(Str)) return true;
366 } while (EatIfPresent(lltok::comma));
367
368 return ParseToken(lltok::rsquare, "expected ']' at end of list");
369}
370
Dan Gohman466876b2009-08-12 23:32:33 +0000371/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000372/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000373bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000374 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000375 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000376 Lex.Lex(); // eat LocalVarID;
377
378 if (ParseToken(lltok::equal, "expected '=' after name") ||
379 ParseToken(lltok::kw_type, "expected 'type' after '='"))
380 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381
Craig Topper2617dcc2014-04-15 06:32:26 +0000382 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383 if (ParseStructDefinition(TypeLoc, "",
384 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000385
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000386 if (!isa<StructType>(Result)) {
387 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
388 if (Entry.first)
389 return Error(TypeLoc, "non-struct types may not be recursive");
390 Entry.first = Result;
391 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000392 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000393
Chris Lattnerac161bf2009-01-02 07:01:27 +0000394 return false;
395}
396
397/// toplevelentity
398/// ::= LocalVar '=' 'type' type
399bool LLParser::ParseNamedType() {
400 std::string Name = Lex.getStrVal();
401 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000402 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000403
Chris Lattner3822f632009-01-02 08:05:26 +0000404 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000405 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000406 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000407
Craig Topper2617dcc2014-04-15 06:32:26 +0000408 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 if (ParseStructDefinition(NameLoc, Name,
410 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000411
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000412 if (!isa<StructType>(Result)) {
413 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
414 if (Entry.first)
415 return Error(NameLoc, "non-struct types may not be recursive");
416 Entry.first = Result;
417 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000418 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000420 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000421}
422
Chris Lattnerac161bf2009-01-02 07:01:27 +0000423/// toplevelentity
424/// ::= 'declare' FunctionHeader
425bool LLParser::ParseDeclare() {
426 assert(Lex.getKind() == lltok::kw_declare);
427 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000428
Peter Collingbourne21521892016-06-21 23:42:48 +0000429 std::vector<std::pair<unsigned, MDNode *>> MDs;
430 while (Lex.getKind() == lltok::MetadataVar) {
431 unsigned MDK;
432 MDNode *N;
433 if (ParseMetadataAttachment(MDK, N))
434 return true;
435 MDs.push_back({MDK, N});
436 }
437
Chris Lattnerac161bf2009-01-02 07:01:27 +0000438 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000439 if (ParseFunctionHeader(F, false))
440 return true;
441 for (auto &MD : MDs)
442 F->addMetadata(MD.first, *MD.second);
443 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444}
445
446/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000447/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448bool LLParser::ParseDefine() {
449 assert(Lex.getKind() == lltok::kw_define);
450 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000453 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000454 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000455 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000456}
457
Chris Lattner3822f632009-01-02 08:05:26 +0000458/// ParseGlobalType
459/// ::= 'constant'
460/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000461bool LLParser::ParseGlobalType(bool &IsConstant) {
462 if (Lex.getKind() == lltok::kw_constant)
463 IsConstant = true;
464 else if (Lex.getKind() == lltok::kw_global)
465 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000466 else {
467 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000468 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000469 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470 Lex.Lex();
471 return false;
472}
473
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000474bool LLParser::ParseOptionalUnnamedAddr(
475 GlobalVariable::UnnamedAddr &UnnamedAddr) {
476 if (EatIfPresent(lltok::kw_unnamed_addr))
477 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
478 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
479 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
480 else
481 UnnamedAddr = GlobalValue::UnnamedAddr::None;
482 return false;
483}
484
Dan Gohman466876b2009-08-12 23:32:33 +0000485/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000486/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000487/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
488/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000489/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000490/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000491/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
492/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000493/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000494bool LLParser::ParseUnnamedGlobal() {
495 unsigned VarID = NumberedVals.size();
496 std::string Name;
497 LocTy NameLoc = Lex.getLoc();
498
499 // Handle the GlobalID form.
500 if (Lex.getKind() == lltok::GlobalID) {
501 if (Lex.getUIntVal() != VarID)
502 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000503 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000504 Lex.Lex(); // eat GlobalID;
505
506 if (ParseToken(lltok::equal, "expected '=' after name"))
507 return true;
508 }
509
510 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000511 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000512 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000513 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000514 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000515 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
516 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000517 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000518 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000519
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000520 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000521 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000522 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000523
524 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000525 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000526}
527
Chris Lattnerac161bf2009-01-02 07:01:27 +0000528/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000529/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000530/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
531/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000532/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000533bool LLParser::ParseNamedGlobal() {
534 assert(Lex.getKind() == lltok::GlobalVar);
535 LocTy NameLoc = Lex.getLoc();
536 std::string Name = Lex.getStrVal();
537 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000538
Chris Lattnerac161bf2009-01-02 07:01:27 +0000539 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000540 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000541 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000542 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000543 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000544 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000545 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
546 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000547 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000548 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000549
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000550 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000551 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000552 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000553
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000554 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000555 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000556}
557
David Majnemerdad0a642014-06-27 18:19:56 +0000558bool LLParser::parseComdat() {
559 assert(Lex.getKind() == lltok::ComdatVar);
560 std::string Name = Lex.getStrVal();
561 LocTy NameLoc = Lex.getLoc();
562 Lex.Lex();
563
564 if (ParseToken(lltok::equal, "expected '=' here"))
565 return true;
566
567 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
568 return TokError("expected comdat type");
569
570 Comdat::SelectionKind SK;
571 switch (Lex.getKind()) {
572 default:
573 return TokError("unknown selection kind");
574 case lltok::kw_any:
575 SK = Comdat::Any;
576 break;
577 case lltok::kw_exactmatch:
578 SK = Comdat::ExactMatch;
579 break;
580 case lltok::kw_largest:
581 SK = Comdat::Largest;
582 break;
583 case lltok::kw_noduplicates:
584 SK = Comdat::NoDuplicates;
585 break;
586 case lltok::kw_samesize:
587 SK = Comdat::SameSize;
588 break;
589 }
590 Lex.Lex();
591
592 // See if the comdat was forward referenced, if so, use the comdat.
593 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
594 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
595 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
596 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
597
598 Comdat *C;
599 if (I != ComdatSymTab.end())
600 C = &I->second;
601 else
602 C = M->getOrInsertComdat(Name);
603 C->setSelectionKind(SK);
604
605 return false;
606}
607
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000608// MDString:
609// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000610bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000611 std::string Str;
612 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000613 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000614 return false;
615}
616
617// MDNode:
618// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000619bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000620 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000621 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000622 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000623 if (ParseUInt32(MID))
624 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000625
Chris Lattner8eff0152010-04-01 05:14:45 +0000626 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000627 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000628 Result = NumberedMetadata[MID];
629 return false;
630 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000631
Chris Lattner8eff0152010-04-01 05:14:45 +0000632 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000633 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000634 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000635
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000636 Result = FwdRef.first.get();
637 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000638 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000639}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000640
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000641/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000642/// !foo = !{ !1, !2 }
643bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000644 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000645 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000646 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000647
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000648 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000649 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000650 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000651 return true;
652
Dan Gohman2637cc12010-07-21 23:38:33 +0000653 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000654 if (Lex.getKind() != lltok::rbrace)
655 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000656 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000657 // Parse DIExpressions inline as a special case. They are still MDNodes,
658 // so they can still appear in named metadata. Remove this logic if they
659 // become plain Metadata.
660 if (Lex.getKind() == lltok::MetadataVar &&
661 Lex.getStrVal() == "DIExpression") {
662 if (ParseDIExpression(N, /*IsDistinct=*/false))
663 return true;
664 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
665 ParseMDNodeID(N)) {
666 return true;
667 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000668 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000669 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000670
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000671 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000672}
673
Devang Patel39e64d42009-07-01 19:21:12 +0000674/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000675/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000676bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000677 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000678 Lex.Lex();
679 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000680
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000681 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000682 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000683 ParseToken(lltok::equal, "expected '=' here"))
684 return true;
685
686 // Detect common error, from old metadata syntax.
687 if (Lex.getKind() == lltok::Type)
688 return TokError("unexpected type in metadata definition");
689
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000690 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000691 if (Lex.getKind() == lltok::MetadataVar) {
692 if (ParseSpecializedMDNode(Init, IsDistinct))
693 return true;
694 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
695 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000696 return true;
697
Chris Lattnerfc58af22009-12-30 04:51:58 +0000698 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000699 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000700 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000701 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000702 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000703
Chris Lattnerfc58af22009-12-30 04:51:58 +0000704 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
705 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000706 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000707 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000708 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000709 }
710
Devang Patel39e64d42009-07-01 19:21:12 +0000711 return false;
712}
713
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000714static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
715 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
716 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
717}
718
Rafael Espindolae4b02312018-01-11 22:15:05 +0000719// If there was an explicit dso_local, update GV. In the absence of an explicit
720// dso_local we keep the default value.
721static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
722 if (DSOLocal)
723 GV.setDSOLocal(true);
724}
725
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000726/// parseIndirectSymbol:
Sean Fertilec70d28b2017-10-26 15:00:26 +0000727/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
728/// OptionalVisibility OptionalDLLStorageClass
729/// OptionalThreadLocal OptionalUnnamedAddr
730// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000731///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000732/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000733/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000734///
Eric Christopher536f0a92015-05-28 23:07:39 +0000735/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000736///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000737bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
738 unsigned L, unsigned Visibility,
739 unsigned DLLStorageClass, bool DSOLocal,
740 GlobalVariable::ThreadLocalMode TLM,
741 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000742 bool IsAlias;
743 if (Lex.getKind() == lltok::kw_alias)
744 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000745 else if (Lex.getKind() == lltok::kw_ifunc)
746 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000747 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000748 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000749 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750
Rafael Espindola78527052013-10-06 15:10:43 +0000751 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
752
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000753 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000754 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000756 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000757 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000758 "symbol with local linkage must have default visibility");
759
David Blaikie2f408302015-09-11 03:22:04 +0000760 Type *Ty;
761 LocTy ExplicitTypeLoc = Lex.getLoc();
762 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000763 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000764 return true;
765
Rafael Espindola64c1e182014-06-03 02:41:57 +0000766 Constant *Aliasee;
767 LocTy AliaseeLoc = Lex.getLoc();
768 if (Lex.getKind() != lltok::kw_bitcast &&
769 Lex.getKind() != lltok::kw_getelementptr &&
770 Lex.getKind() != lltok::kw_addrspacecast &&
771 Lex.getKind() != lltok::kw_inttoptr) {
772 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000773 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000774 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000775 // The bitcast dest type is not present, it is implied by the dest type.
776 ValID ID;
777 if (ParseValID(ID))
778 return true;
779 if (ID.Kind != ValID::t_Constant)
780 return Error(AliaseeLoc, "invalid aliasee");
781 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
Rafael Espindola64c1e182014-06-03 02:41:57 +0000784 Type *AliaseeType = Aliasee->getType();
785 auto *PTy = dyn_cast<PointerType>(AliaseeType);
786 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000787 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000788 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000790 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000791 return Error(
792 ExplicitTypeLoc,
793 "explicit pointee type doesn't match operand's pointee type");
794
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000795 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
796 return Error(
797 ExplicitTypeLoc,
798 "explicit pointee type should be a function type");
799
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000800 GlobalValue *GVal = nullptr;
801
802 // See if the alias was forward referenced, if so, prepare to replace the
803 // forward reference.
804 if (!Name.empty()) {
805 GVal = M->getNamedValue(Name);
806 if (GVal) {
807 if (!ForwardRefVals.erase(Name))
808 return Error(NameLoc, "redefinition of global '@" + Name + "'");
809 }
810 } else {
811 auto I = ForwardRefValIDs.find(NumberedVals.size());
812 if (I != ForwardRefValIDs.end()) {
813 GVal = I->second.first;
814 ForwardRefValIDs.erase(I);
815 }
816 }
817
Chris Lattnerac161bf2009-01-02 07:01:27 +0000818 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000819 std::unique_ptr<GlobalIndirectSymbol> GA;
820 if (IsAlias)
821 GA.reset(GlobalAlias::create(Ty, AddrSpace,
822 (GlobalValue::LinkageTypes)Linkage, Name,
823 Aliasee, /*Parent*/ nullptr));
824 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000825 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
826 (GlobalValue::LinkageTypes)Linkage, Name,
827 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000828 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000829 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000830 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000831 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000832 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000833
Rafael Espindola54fc2982015-06-17 17:53:31 +0000834 if (Name.empty())
835 NumberedVals.push_back(GA.get());
836
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000837 if (GVal) {
838 // Verify that types agree.
839 if (GVal->getType() != GA->getType())
840 return Error(
841 ExplicitTypeLoc,
842 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000843
Chris Lattnerac161bf2009-01-02 07:01:27 +0000844 // If they agree, just RAUW the old value with the alias and remove the
845 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000846 GVal->replaceAllUsesWith(GA.get());
847 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000849
Chris Lattnerac161bf2009-01-02 07:01:27 +0000850 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000851 if (IsAlias)
852 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
853 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000854 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000855 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000856
Rafael Espindolaaa273822014-05-09 21:49:17 +0000857 // The module owns this now
858 GA.release();
859
Chris Lattnerac161bf2009-01-02 07:01:27 +0000860 return false;
861}
862
863/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000864/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
865/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000866/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000867/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000868/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
869/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
870/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
871/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872///
Eric Christopher536f0a92015-05-28 23:07:39 +0000873/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000874/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000875///
876bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
877 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000878 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000879 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000880 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000881 if (!isValidVisibilityForLinkage(Visibility, Linkage))
882 return Error(NameLoc,
883 "symbol with local linkage must have default visibility");
884
Chris Lattnerac161bf2009-01-02 07:01:27 +0000885 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000886 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000887 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000888 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000889
Craig Topper2617dcc2014-04-15 06:32:26 +0000890 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000891 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000892 ParseOptionalToken(lltok::kw_externally_initialized,
893 IsExternallyInitialized,
894 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000895 ParseGlobalType(IsConstant) ||
896 ParseType(Ty, TyLoc))
897 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000898
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 // If the linkage is specified and is external, then no initializer is
900 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000901 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000902 if (!HasLinkage ||
903 !GlobalValue::isValidDeclarationLinkage(
904 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 if (ParseGlobalValue(Ty, Init))
906 return true;
907 }
908
David Majnemer49b3d9b2015-02-16 08:41:08 +0000909 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000910 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000911
David Majnemer598bd052014-12-09 05:56:09 +0000912 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000913
914 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000915 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000916 GVal = M->getNamedValue(Name);
917 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000918 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000919 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000920 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000922 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000923 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000924 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000925 ForwardRefValIDs.erase(I);
926 }
927 }
928
David Majnemer598bd052014-12-09 05:56:09 +0000929 GlobalVariable *GV;
930 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000931 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
932 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000933 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000934 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000935 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000936 return Error(TyLoc,
937 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
David Majnemer598bd052014-12-09 05:56:09 +0000939 GV = cast<GlobalVariable>(GVal);
940
Chris Lattnerac161bf2009-01-02 07:01:27 +0000941 // Move the forward-reference to the correct spot in the module.
942 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
943 }
944
945 if (Name.empty())
946 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000947
Chris Lattnerac161bf2009-01-02 07:01:27 +0000948 // Set the parsed properties on the global.
949 if (Init)
950 GV->setInitializer(Init);
951 GV->setConstant(IsConstant);
952 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000953 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000954 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000955 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000956 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000957 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000958 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000959
Chris Lattnerac161bf2009-01-02 07:01:27 +0000960 // Parse attributes on the global.
961 while (Lex.getKind() == lltok::comma) {
962 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000963
Chris Lattnerac161bf2009-01-02 07:01:27 +0000964 if (Lex.getKind() == lltok::kw_section) {
965 Lex.Lex();
966 GV->setSection(Lex.getStrVal());
967 if (ParseToken(lltok::StringConstant, "expected global section string"))
968 return true;
969 } else if (Lex.getKind() == lltok::kw_align) {
970 unsigned Alignment;
971 if (ParseOptionalAlignment(Alignment)) return true;
972 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000973 } else if (Lex.getKind() == lltok::MetadataVar) {
974 if (ParseGlobalObjectMetadataAttachment(*GV))
975 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000976 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000977 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000978 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000979 return true;
980 if (C)
981 GV->setComdat(C);
982 else
983 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000984 }
985 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000986
Javed Absarf3d79042017-05-11 12:28:08 +0000987 AttrBuilder Attrs;
988 LocTy BuiltinLoc;
989 std::vector<unsigned> FwdRefAttrGrps;
990 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
991 return true;
992 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
993 GV->setAttributes(AttributeSet::get(Context, Attrs));
994 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
995 }
996
Chris Lattnerac161bf2009-01-02 07:01:27 +0000997 return false;
998}
999
Bill Wendling63b88192013-02-06 06:52:58 +00001000/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001001/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001002bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001003 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001004 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001005 Lex.Lex();
1006
David Majnemerb39e22b2014-12-09 18:33:57 +00001007 if (Lex.getKind() != lltok::AttrGrpID)
1008 return TokError("expected attribute group id");
1009
Bill Wendling63b88192013-02-06 06:52:58 +00001010 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001011 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001012 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001013 Lex.Lex();
1014
1015 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001016 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001017 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001018 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001019 ParseToken(lltok::rbrace, "expected end of attribute group"))
1020 return true;
1021
Bill Wendlingb32b0412013-02-08 06:32:06 +00001022 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001023 return Error(AttrGrpLoc, "attribute group has no attributes");
1024
1025 return false;
1026}
1027
Bill Wendling8b0321d2013-02-08 00:52:31 +00001028/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001029/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001030bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1031 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001032 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001033 bool HaveError = false;
1034
1035 B.clear();
1036
Bill Wendling63b88192013-02-06 06:52:58 +00001037 while (true) {
1038 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001039 if (Token == lltok::kw_builtin)
1040 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001041 switch (Token) {
1042 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001043 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001044 return Error(Lex.getLoc(), "unterminated attribute group");
1045 case lltok::rbrace:
1046 // Finished.
1047 return false;
1048
Bill Wendlingb32b0412013-02-08 06:32:06 +00001049 case lltok::AttrGrpID: {
1050 // Allow a function to reference an attribute group:
1051 //
1052 // define void @foo() #1 { ... }
1053 if (inAttrGrp)
1054 HaveError |=
1055 Error(Lex.getLoc(),
1056 "cannot have an attribute group reference in an attribute group");
1057
1058 unsigned AttrGrpNum = Lex.getUIntVal();
1059 if (inAttrGrp) break;
1060
1061 // Save the reference to the attribute group. We'll fill it in later.
1062 FwdRefAttrGrps.push_back(AttrGrpNum);
1063 break;
1064 }
Bill Wendling63b88192013-02-06 06:52:58 +00001065 // Target-dependent attributes:
1066 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001067 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001068 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001069 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001070 }
1071
1072 // Target-independent attributes:
1073 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001074 // As a hack, we allow function alignment to be initially parsed as an
1075 // attribute on a function declaration/definition or added to an attribute
1076 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001077 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001078 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001079 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001080 if (ParseToken(lltok::equal, "expected '=' here") ||
1081 ParseUInt32(Alignment))
1082 return true;
1083 } else {
1084 if (ParseOptionalAlignment(Alignment))
1085 return true;
1086 }
Bill Wendling63b88192013-02-06 06:52:58 +00001087 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001088 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001089 }
1090 case lltok::kw_alignstack: {
1091 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001092 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001093 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001094 if (ParseToken(lltok::equal, "expected '=' here") ||
1095 ParseUInt32(Alignment))
1096 return true;
1097 } else {
1098 if (ParseOptionalStackAlignment(Alignment))
1099 return true;
1100 }
Bill Wendling63b88192013-02-06 06:52:58 +00001101 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001102 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001103 }
George Burgess IV278199f2016-04-12 01:05:35 +00001104 case lltok::kw_allocsize: {
1105 unsigned ElemSizeArg;
1106 Optional<unsigned> NumElemsArg;
1107 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1108 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1109 return true;
1110 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1111 continue;
1112 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001113 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1114 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1115 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1116 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1117 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001118 case lltok::kw_inaccessiblememonly:
1119 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1120 case lltok::kw_inaccessiblemem_or_argmemonly:
1121 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001122 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1123 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1124 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1125 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1126 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1127 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1128 case lltok::kw_noimplicitfloat:
1129 B.addAttribute(Attribute::NoImplicitFloat); break;
1130 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1131 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1132 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1133 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001134 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001135 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001136 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001137 case lltok::kw_optforfuzzing:
1138 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001139 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1140 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1141 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1142 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1143 case lltok::kw_returns_twice:
1144 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001145 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001146 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1147 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1148 case lltok::kw_sspstrong:
1149 B.addAttribute(Attribute::StackProtectStrong); break;
1150 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001151 case lltok::kw_shadowcallstack:
1152 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001153 case lltok::kw_sanitize_address:
1154 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001155 case lltok::kw_sanitize_hwaddress:
1156 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001157 case lltok::kw_sanitize_thread:
1158 B.addAttribute(Attribute::SanitizeThread); break;
1159 case lltok::kw_sanitize_memory:
1160 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001161 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001162 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001163 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001164
1165 // Error handling.
1166 case lltok::kw_inreg:
1167 case lltok::kw_signext:
1168 case lltok::kw_zeroext:
1169 HaveError |=
1170 Error(Lex.getLoc(),
1171 "invalid use of attribute on a function");
1172 break;
1173 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001174 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001175 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001176 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001177 case lltok::kw_nest:
1178 case lltok::kw_noalias:
1179 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001180 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001181 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001182 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001183 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001184 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001185 HaveError |=
1186 Error(Lex.getLoc(),
1187 "invalid use of parameter-only attribute on a function");
1188 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001189 }
1190
1191 Lex.Lex();
1192 }
1193}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194
1195//===----------------------------------------------------------------------===//
1196// GlobalValue Reference/Resolution Routines.
1197//===----------------------------------------------------------------------===//
1198
Karl Schimpf77729782015-09-03 18:06:44 +00001199static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1200 const std::string &Name) {
1201 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1202 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1203 else
1204 return new GlobalVariable(*M, PTy->getElementType(), false,
1205 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1206 nullptr, GlobalVariable::NotThreadLocal,
1207 PTy->getAddressSpace());
1208}
1209
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210/// GetGlobalVal - Get a value with the specified name or ID, creating a
1211/// forward reference record if needed. This can return null if the value
1212/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001213GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001215 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001216 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001218 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001220
Chris Lattnerac161bf2009-01-02 07:01:27 +00001221 // Look this name up in the normal function symbol table.
1222 GlobalValue *Val =
1223 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001224
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 // If this is a forward reference for the value, see if we already created a
1226 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001227 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001228 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001229 if (I != ForwardRefVals.end())
1230 Val = I->second.first;
1231 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001232
Chris Lattnerac161bf2009-01-02 07:01:27 +00001233 // If we have the value in the symbol table or fwd-ref table, return it.
1234 if (Val) {
1235 if (Val->getType() == Ty) return Val;
1236 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001237 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001238 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001239 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001240
Chris Lattnerac161bf2009-01-02 07:01:27 +00001241 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001242 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001243 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1244 return FwdVal;
1245}
1246
Chris Lattner229907c2011-07-18 04:54:35 +00001247GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1248 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001249 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001250 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001251 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001253
Craig Topper2617dcc2014-04-15 06:32:26 +00001254 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001255
Chris Lattnerac161bf2009-01-02 07:01:27 +00001256 // If this is a forward reference for the value, see if we already created a
1257 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001258 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001259 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001260 if (I != ForwardRefValIDs.end())
1261 Val = I->second.first;
1262 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001263
Chris Lattnerac161bf2009-01-02 07:01:27 +00001264 // If we have the value in the symbol table or fwd-ref table, return it.
1265 if (Val) {
1266 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001267 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001268 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001269 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001270 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001271
Chris Lattnerac161bf2009-01-02 07:01:27 +00001272 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001273 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1275 return FwdVal;
1276}
1277
Chris Lattnerac161bf2009-01-02 07:01:27 +00001278//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001279// Comdat Reference/Resolution Routines.
1280//===----------------------------------------------------------------------===//
1281
1282Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1283 // Look this name up in the comdat symbol table.
1284 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1285 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1286 if (I != ComdatSymTab.end())
1287 return &I->second;
1288
1289 // Otherwise, create a new forward reference for this value and remember it.
1290 Comdat *C = M->getOrInsertComdat(Name);
1291 ForwardRefComdats[Name] = Loc;
1292 return C;
1293}
1294
David Majnemerdad0a642014-06-27 18:19:56 +00001295//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001296// Helper Routines.
1297//===----------------------------------------------------------------------===//
1298
1299/// ParseToken - If the current token has the specified kind, eat it and return
1300/// success. Otherwise, emit the specified error and return failure.
1301bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1302 if (Lex.getKind() != T)
1303 return TokError(ErrMsg);
1304 Lex.Lex();
1305 return false;
1306}
1307
Chris Lattner3822f632009-01-02 08:05:26 +00001308/// ParseStringConstant
1309/// ::= StringConstant
1310bool LLParser::ParseStringConstant(std::string &Result) {
1311 if (Lex.getKind() != lltok::StringConstant)
1312 return TokError("expected string constant");
1313 Result = Lex.getStrVal();
1314 Lex.Lex();
1315 return false;
1316}
1317
1318/// ParseUInt32
1319/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001320bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001321 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1322 return TokError("expected integer");
1323 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1324 if (Val64 != unsigned(Val64))
1325 return TokError("expected 32-bit integer (too large)");
1326 Val = Val64;
1327 Lex.Lex();
1328 return false;
1329}
1330
Hal Finkelb0407ba2014-07-18 15:51:28 +00001331/// ParseUInt64
1332/// ::= uint64
1333bool LLParser::ParseUInt64(uint64_t &Val) {
1334 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1335 return TokError("expected integer");
1336 Val = Lex.getAPSIntVal().getLimitedValue();
1337 Lex.Lex();
1338 return false;
1339}
1340
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001341/// ParseTLSModel
1342/// := 'localdynamic'
1343/// := 'initialexec'
1344/// := 'localexec'
1345bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1346 switch (Lex.getKind()) {
1347 default:
1348 return TokError("expected localdynamic, initialexec or localexec");
1349 case lltok::kw_localdynamic:
1350 TLM = GlobalVariable::LocalDynamicTLSModel;
1351 break;
1352 case lltok::kw_initialexec:
1353 TLM = GlobalVariable::InitialExecTLSModel;
1354 break;
1355 case lltok::kw_localexec:
1356 TLM = GlobalVariable::LocalExecTLSModel;
1357 break;
1358 }
1359
1360 Lex.Lex();
1361 return false;
1362}
1363
1364/// ParseOptionalThreadLocal
1365/// := /*empty*/
1366/// := 'thread_local'
1367/// := 'thread_local' '(' tlsmodel ')'
1368bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1369 TLM = GlobalVariable::NotThreadLocal;
1370 if (!EatIfPresent(lltok::kw_thread_local))
1371 return false;
1372
1373 TLM = GlobalVariable::GeneralDynamicTLSModel;
1374 if (Lex.getKind() == lltok::lparen) {
1375 Lex.Lex();
1376 return ParseTLSModel(TLM) ||
1377 ParseToken(lltok::rparen, "expected ')' after thread local model");
1378 }
1379 return false;
1380}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381
1382/// ParseOptionalAddrSpace
1383/// := /*empty*/
1384/// := 'addrspace' '(' uint32 ')'
1385bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1386 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001387 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001388 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001389 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001390 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001392}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001393
Artur Pilipenko17376c42015-08-03 14:31:49 +00001394/// ParseStringAttribute
1395/// := StringConstant
1396/// := StringConstant '=' StringConstant
1397bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1398 std::string Attr = Lex.getStrVal();
1399 Lex.Lex();
1400 std::string Val;
1401 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1402 return true;
1403 B.addAttribute(Attr, Val);
1404 return false;
1405}
1406
Bill Wendling34c2eb22012-12-04 23:40:58 +00001407/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1408bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1409 bool HaveError = false;
1410
1411 B.clear();
1412
Eugene Zelenko1804a772016-08-25 00:45:04 +00001413 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001414 lltok::Kind Token = Lex.getKind();
1415 switch (Token) {
1416 default: // End of attributes.
1417 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001418 case lltok::StringConstant: {
1419 if (ParseStringAttribute(B))
1420 return true;
1421 continue;
1422 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001423 case lltok::kw_align: {
1424 unsigned Alignment;
1425 if (ParseOptionalAlignment(Alignment))
1426 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001427 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001428 continue;
1429 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001430 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001431 case lltok::kw_dereferenceable: {
1432 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001433 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001434 return true;
1435 B.addDereferenceableAttr(Bytes);
1436 continue;
1437 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001438 case lltok::kw_dereferenceable_or_null: {
1439 uint64_t Bytes;
1440 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1441 return true;
1442 B.addDereferenceableOrNullAttr(Bytes);
1443 continue;
1444 }
Reid Klecknera534a382013-12-19 02:14:12 +00001445 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001446 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1447 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1448 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1449 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001450 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001451 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1452 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001453 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001454 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1455 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001456 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001457 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001458 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001459 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001460
Stephen Lin7577ed52013-04-20 13:16:13 +00001461 case lltok::kw_alignstack:
1462 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001463 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001464 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001465 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001466 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001467 case lltok::kw_minsize:
1468 case lltok::kw_naked:
1469 case lltok::kw_nobuiltin:
1470 case lltok::kw_noduplicate:
1471 case lltok::kw_noimplicitfloat:
1472 case lltok::kw_noinline:
1473 case lltok::kw_nonlazybind:
1474 case lltok::kw_noredzone:
1475 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001476 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001477 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001478 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001479 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001480 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001481 case lltok::kw_returns_twice:
1482 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001483 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001484 case lltok::kw_sanitize_memory:
1485 case lltok::kw_sanitize_thread:
1486 case lltok::kw_ssp:
1487 case lltok::kw_sspreq:
1488 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001489 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001490 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001491 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001492 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001493 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1494 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001495 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001496
Bill Wendling34c2eb22012-12-04 23:40:58 +00001497 Lex.Lex();
1498 }
1499}
1500
1501/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1502bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1503 bool HaveError = false;
1504
1505 B.clear();
1506
Eugene Zelenko1804a772016-08-25 00:45:04 +00001507 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001508 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001509 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001510 default: // End of attributes.
1511 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001512 case lltok::StringConstant: {
1513 if (ParseStringAttribute(B))
1514 return true;
1515 continue;
1516 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001517 case lltok::kw_dereferenceable: {
1518 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001519 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001520 return true;
1521 B.addDereferenceableAttr(Bytes);
1522 continue;
1523 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001524 case lltok::kw_dereferenceable_or_null: {
1525 uint64_t Bytes;
1526 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1527 return true;
1528 B.addDereferenceableOrNullAttr(Bytes);
1529 continue;
1530 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001531 case lltok::kw_align: {
1532 unsigned Alignment;
1533 if (ParseOptionalAlignment(Alignment))
1534 return true;
1535 B.addAlignmentAttr(Alignment);
1536 continue;
1537 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001538 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1539 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001540 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001541 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1542 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001543
Bill Wendling34c2eb22012-12-04 23:40:58 +00001544 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001545 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001546 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001547 case lltok::kw_nest:
1548 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001549 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001550 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001551 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001552 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001553 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001554 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001555
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001556 case lltok::kw_alignstack:
1557 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001558 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001559 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001560 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001561 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001562 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001563 case lltok::kw_minsize:
1564 case lltok::kw_naked:
1565 case lltok::kw_nobuiltin:
1566 case lltok::kw_noduplicate:
1567 case lltok::kw_noimplicitfloat:
1568 case lltok::kw_noinline:
1569 case lltok::kw_nonlazybind:
1570 case lltok::kw_noredzone:
1571 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001572 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001573 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001574 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001575 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001576 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001577 case lltok::kw_returns_twice:
1578 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001579 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001580 case lltok::kw_sanitize_memory:
1581 case lltok::kw_sanitize_thread:
1582 case lltok::kw_ssp:
1583 case lltok::kw_sspreq:
1584 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001585 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001586 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001587 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001588 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001589 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001590 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001591
1592 case lltok::kw_readnone:
1593 case lltok::kw_readonly:
1594 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001595 }
1596
Chris Lattnerac161bf2009-01-02 07:01:27 +00001597 Lex.Lex();
1598 }
1599}
1600
Rafael Espindolac6269912016-05-10 17:16:45 +00001601static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1602 HasLinkage = true;
1603 switch (Kind) {
1604 default:
1605 HasLinkage = false;
1606 return GlobalValue::ExternalLinkage;
1607 case lltok::kw_private:
1608 return GlobalValue::PrivateLinkage;
1609 case lltok::kw_internal:
1610 return GlobalValue::InternalLinkage;
1611 case lltok::kw_weak:
1612 return GlobalValue::WeakAnyLinkage;
1613 case lltok::kw_weak_odr:
1614 return GlobalValue::WeakODRLinkage;
1615 case lltok::kw_linkonce:
1616 return GlobalValue::LinkOnceAnyLinkage;
1617 case lltok::kw_linkonce_odr:
1618 return GlobalValue::LinkOnceODRLinkage;
1619 case lltok::kw_available_externally:
1620 return GlobalValue::AvailableExternallyLinkage;
1621 case lltok::kw_appending:
1622 return GlobalValue::AppendingLinkage;
1623 case lltok::kw_common:
1624 return GlobalValue::CommonLinkage;
1625 case lltok::kw_extern_weak:
1626 return GlobalValue::ExternalWeakLinkage;
1627 case lltok::kw_external:
1628 return GlobalValue::ExternalLinkage;
1629 }
1630}
1631
Chris Lattnerac161bf2009-01-02 07:01:27 +00001632/// ParseOptionalLinkage
1633/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001634/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001635/// ::= 'internal'
1636/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001637/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001639/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001640/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001641/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001642/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643/// ::= 'extern_weak'
1644/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001645bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1646 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001647 unsigned &DLLStorageClass,
1648 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001649 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1650 if (HasLinkage)
1651 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001652 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001653 ParseOptionalVisibility(Visibility);
1654 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001655
1656 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1657 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1658 }
1659
Chris Lattnerac161bf2009-01-02 07:01:27 +00001660 return false;
1661}
1662
Sean Fertilec70d28b2017-10-26 15:00:26 +00001663void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1664 switch (Lex.getKind()) {
1665 default:
1666 DSOLocal = false;
1667 break;
1668 case lltok::kw_dso_local:
1669 DSOLocal = true;
1670 Lex.Lex();
1671 break;
1672 case lltok::kw_dso_preemptable:
1673 DSOLocal = false;
1674 Lex.Lex();
1675 break;
1676 }
1677}
1678
Chris Lattnerac161bf2009-01-02 07:01:27 +00001679/// ParseOptionalVisibility
1680/// ::= /*empty*/
1681/// ::= 'default'
1682/// ::= 'hidden'
1683/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001684///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001685void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001687 default:
1688 Res = GlobalValue::DefaultVisibility;
1689 return;
1690 case lltok::kw_default:
1691 Res = GlobalValue::DefaultVisibility;
1692 break;
1693 case lltok::kw_hidden:
1694 Res = GlobalValue::HiddenVisibility;
1695 break;
1696 case lltok::kw_protected:
1697 Res = GlobalValue::ProtectedVisibility;
1698 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001699 }
1700 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701}
1702
Nico Rieck7157bb72014-01-14 15:22:47 +00001703/// ParseOptionalDLLStorageClass
1704/// ::= /*empty*/
1705/// ::= 'dllimport'
1706/// ::= 'dllexport'
1707///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001708void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001709 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001710 default:
1711 Res = GlobalValue::DefaultStorageClass;
1712 return;
1713 case lltok::kw_dllimport:
1714 Res = GlobalValue::DLLImportStorageClass;
1715 break;
1716 case lltok::kw_dllexport:
1717 Res = GlobalValue::DLLExportStorageClass;
1718 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001719 }
1720 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001721}
1722
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723/// ParseOptionalCallingConv
1724/// ::= /*empty*/
1725/// ::= 'ccc'
1726/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001727/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001728/// ::= 'coldcc'
1729/// ::= 'x86_stdcallcc'
1730/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001731/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001732/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001733/// ::= 'arm_apcscc'
1734/// ::= 'arm_aapcscc'
1735/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001736/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001737/// ::= 'avr_intrcc'
1738/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001739/// ::= 'ptx_kernel'
1740/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001741/// ::= 'spir_func'
1742/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001743/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001744/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001745/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001746/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001747/// ::= 'preserve_mostcc'
1748/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001749/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001750/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001751/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001752/// ::= 'hhvmcc'
1753/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001754/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001755/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001756/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001757/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001758/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001759/// ::= 'amdgpu_gs'
1760/// ::= 'amdgpu_ps'
1761/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001762/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001763/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001764///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001765bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001766 switch (Lex.getKind()) {
1767 default: CC = CallingConv::C; return false;
1768 case lltok::kw_ccc: CC = CallingConv::C; break;
1769 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1770 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1771 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1772 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001773 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001774 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001775 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001776 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1777 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1778 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001779 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001780 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1781 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001782 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1783 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001784 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1785 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001786 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001787 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001788 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001789 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001790 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001791 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1792 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001793 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001794 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001795 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001796 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1797 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001798 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001799 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001800 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001801 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001802 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001803 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1804 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1805 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001806 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001807 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001808 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001809 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001810 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001812
Chris Lattnerac161bf2009-01-02 07:01:27 +00001813 Lex.Lex();
1814 return false;
1815}
1816
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001817/// ParseMetadataAttachment
1818/// ::= !dbg !42
1819bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1820 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1821
1822 std::string Name = Lex.getStrVal();
1823 Kind = M->getMDKindID(Name);
1824 Lex.Lex();
1825
1826 return ParseMDNode(MD);
1827}
1828
Chris Lattner5c427632009-12-30 05:31:19 +00001829/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001830/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001831bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001832 do {
1833 if (Lex.getKind() != lltok::MetadataVar)
1834 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001835
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001836 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001837 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001838 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001840
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001841 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001842 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001843 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001844
Chris Lattner596760d2009-12-29 21:25:40 +00001845 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001846 } while (EatIfPresent(lltok::comma));
1847 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001848}
1849
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001850/// ParseGlobalObjectMetadataAttachment
1851/// ::= !dbg !57
1852bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1853 unsigned MDK;
1854 MDNode *N;
1855 if (ParseMetadataAttachment(MDK, N))
1856 return true;
1857
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001858 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001859 return false;
1860}
1861
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001862/// ParseOptionalFunctionMetadata
1863/// ::= (!dbg !57)*
1864bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001865 while (Lex.getKind() == lltok::MetadataVar)
1866 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001867 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001868 return false;
1869}
1870
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871/// ParseOptionalAlignment
1872/// ::= /* empty */
1873/// ::= 'align' 4
1874bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1875 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001876 if (!EatIfPresent(lltok::kw_align))
1877 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001878 LocTy AlignLoc = Lex.getLoc();
1879 if (ParseUInt32(Alignment)) return true;
1880 if (!isPowerOf2_32(Alignment))
1881 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001882 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001883 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001884 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885}
1886
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001887/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001888/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001889/// ::= AttrKind '(' 4 ')'
1890///
1891/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1892bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1893 uint64_t &Bytes) {
1894 assert((AttrKind == lltok::kw_dereferenceable ||
1895 AttrKind == lltok::kw_dereferenceable_or_null) &&
1896 "contract!");
1897
Hal Finkelb0407ba2014-07-18 15:51:28 +00001898 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001899 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001900 return false;
1901 LocTy ParenLoc = Lex.getLoc();
1902 if (!EatIfPresent(lltok::lparen))
1903 return Error(ParenLoc, "expected '('");
1904 LocTy DerefLoc = Lex.getLoc();
1905 if (ParseUInt64(Bytes)) return true;
1906 ParenLoc = Lex.getLoc();
1907 if (!EatIfPresent(lltok::rparen))
1908 return Error(ParenLoc, "expected ')'");
1909 if (!Bytes)
1910 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1911 return false;
1912}
1913
Chris Lattnerb2f39502009-12-30 05:44:30 +00001914/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001915/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001916/// ::= ',' align 4
1917///
1918/// This returns with AteExtraComma set to true if it ate an excess comma at the
1919/// end.
1920bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1921 bool &AteExtraComma) {
1922 AteExtraComma = false;
1923 while (EatIfPresent(lltok::comma)) {
1924 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001925 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001926 AteExtraComma = true;
1927 return false;
1928 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001929
Chris Lattner95b0ff42010-04-23 00:50:50 +00001930 if (Lex.getKind() != lltok::kw_align)
1931 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001932
Chris Lattner95b0ff42010-04-23 00:50:50 +00001933 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001934 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001935
Devang Patelea8a4b92009-09-17 23:04:48 +00001936 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001937}
1938
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001939/// ParseOptionalCommaAddrSpace
1940/// ::=
1941/// ::= ',' addrspace(1)
1942///
1943/// This returns with AteExtraComma set to true if it ate an excess comma at the
1944/// end.
1945bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1946 LocTy &Loc,
1947 bool &AteExtraComma) {
1948 AteExtraComma = false;
1949 while (EatIfPresent(lltok::comma)) {
1950 // Metadata at the end is an early exit.
1951 if (Lex.getKind() == lltok::MetadataVar) {
1952 AteExtraComma = true;
1953 return false;
1954 }
1955
1956 Loc = Lex.getLoc();
1957 if (Lex.getKind() != lltok::kw_addrspace)
1958 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1959
1960 if (ParseOptionalAddrSpace(AddrSpace))
1961 return true;
1962 }
1963
1964 return false;
1965}
1966
George Burgess IV278199f2016-04-12 01:05:35 +00001967bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1968 Optional<unsigned> &HowManyArg) {
1969 Lex.Lex();
1970
1971 auto StartParen = Lex.getLoc();
1972 if (!EatIfPresent(lltok::lparen))
1973 return Error(StartParen, "expected '('");
1974
1975 if (ParseUInt32(BaseSizeArg))
1976 return true;
1977
1978 if (EatIfPresent(lltok::comma)) {
1979 auto HowManyAt = Lex.getLoc();
1980 unsigned HowMany;
1981 if (ParseUInt32(HowMany))
1982 return true;
1983 if (HowMany == BaseSizeArg)
1984 return Error(HowManyAt,
1985 "'allocsize' indices can't refer to the same parameter");
1986 HowManyArg = HowMany;
1987 } else
1988 HowManyArg = None;
1989
1990 auto EndParen = Lex.getLoc();
1991 if (!EatIfPresent(lltok::rparen))
1992 return Error(EndParen, "expected ')'");
1993 return false;
1994}
1995
Eli Friedmanfee02c62011-07-25 23:16:38 +00001996/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001997/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00001998/// else: ::=
1999///
2000/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002001bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002002 AtomicOrdering &Ordering) {
2003 if (!isAtomic)
2004 return false;
2005
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002006 return ParseScope(SSID) || ParseOrdering(Ordering);
2007}
Tim Northovere94a5182014-03-11 10:48:52 +00002008
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002009/// ParseScope
2010/// ::= syncscope("singlethread" | "<target scope>")?
2011///
2012/// This sets synchronization scope ID to the ID of the parsed value.
2013bool LLParser::ParseScope(SyncScope::ID &SSID) {
2014 SSID = SyncScope::System;
2015 if (EatIfPresent(lltok::kw_syncscope)) {
2016 auto StartParenAt = Lex.getLoc();
2017 if (!EatIfPresent(lltok::lparen))
2018 return Error(StartParenAt, "Expected '(' in syncscope");
2019
2020 std::string SSN;
2021 auto SSNAt = Lex.getLoc();
2022 if (ParseStringConstant(SSN))
2023 return Error(SSNAt, "Expected synchronization scope name");
2024
2025 auto EndParenAt = Lex.getLoc();
2026 if (!EatIfPresent(lltok::rparen))
2027 return Error(EndParenAt, "Expected ')' in syncscope");
2028
2029 SSID = Context.getOrInsertSyncScopeID(SSN);
2030 }
2031
2032 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002033}
2034
2035/// ParseOrdering
2036/// ::= AtomicOrdering
2037///
2038/// This sets Ordering to the parsed value.
2039bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002040 switch (Lex.getKind()) {
2041 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002042 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2043 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2044 // Not specified yet:
2045 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2046 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2047 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2048 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2049 case lltok::kw_seq_cst:
2050 Ordering = AtomicOrdering::SequentiallyConsistent;
2051 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002052 }
2053 Lex.Lex();
2054 return false;
2055}
2056
Charles Davisbe5557e2010-02-12 00:31:15 +00002057/// ParseOptionalStackAlignment
2058/// ::= /* empty */
2059/// ::= 'alignstack' '(' 4 ')'
2060bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2061 Alignment = 0;
2062 if (!EatIfPresent(lltok::kw_alignstack))
2063 return false;
2064 LocTy ParenLoc = Lex.getLoc();
2065 if (!EatIfPresent(lltok::lparen))
2066 return Error(ParenLoc, "expected '('");
2067 LocTy AlignLoc = Lex.getLoc();
2068 if (ParseUInt32(Alignment)) return true;
2069 ParenLoc = Lex.getLoc();
2070 if (!EatIfPresent(lltok::rparen))
2071 return Error(ParenLoc, "expected ')'");
2072 if (!isPowerOf2_32(Alignment))
2073 return Error(AlignLoc, "stack alignment is not a power of two");
2074 return false;
2075}
Devang Patelea8a4b92009-09-17 23:04:48 +00002076
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002077/// ParseIndexList - This parses the index list for an insert/extractvalue
2078/// instruction. This sets AteExtraComma in the case where we eat an extra
2079/// comma at the end of the line and find that it is followed by metadata.
2080/// Clients that don't allow metadata can call the version of this function that
2081/// only takes one argument.
2082///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083/// ParseIndexList
2084/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002085///
2086bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2087 bool &AteExtraComma) {
2088 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002089
Chris Lattnerac161bf2009-01-02 07:01:27 +00002090 if (Lex.getKind() != lltok::comma)
2091 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002092
Chris Lattner3822f632009-01-02 08:05:26 +00002093 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002094 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002095 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002096 AteExtraComma = true;
2097 return false;
2098 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002099 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002100 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 Indices.push_back(Idx);
2102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattnerac161bf2009-01-02 07:01:27 +00002104 return false;
2105}
2106
2107//===----------------------------------------------------------------------===//
2108// Type Parsing.
2109//===----------------------------------------------------------------------===//
2110
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002111/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002112bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 switch (Lex.getKind()) {
2115 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002116 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002118 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002123 // Type ::= StructType
2124 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 return true;
2126 break;
2127 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002128 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 Lex.Lex(); // eat the lsquare.
2130 if (ParseArrayVectorType(Result, false))
2131 return true;
2132 break;
2133 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002134 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002135 Lex.Lex();
2136 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002137 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002138 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 } else if (ParseArrayVectorType(Result, true))
2141 return true;
2142 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002143 case lltok::LocalVar: {
2144 // Type ::= %foo
2145 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002146
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002147 // If the type hasn't been defined yet, create a forward definition and
2148 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002149 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002150 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002151 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002153 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 Lex.Lex();
2155 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002157
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002158 case lltok::LocalVarID: {
2159 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002160 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002161
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002162 // If the type hasn't been defined yet, create a forward definition and
2163 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002164 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002165 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002166 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002168 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 Lex.Lex();
2170 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 }
2172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173
2174 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002175 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 switch (Lex.getKind()) {
2177 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002178 default:
2179 if (!AllowVoid && Result->isVoidTy())
2180 return Error(TypeLoc, "void type only allowed for function results");
2181 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002183 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002185 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002186 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002187 if (Result->isVoidTy())
2188 return TokError("pointers to void are invalid - use i8* instead");
2189 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002190 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002191 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 Lex.Lex();
2193 break;
2194
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002195 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002197 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002199 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002200 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002201 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002202 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002203 unsigned AddrSpace;
2204 if (ParseOptionalAddrSpace(AddrSpace) ||
2205 ParseToken(lltok::star, "expected '*' in address space"))
2206 return true;
2207
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002208 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 break;
2210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2213 case lltok::lparen:
2214 if (ParseFunctionType(Result))
2215 return true;
2216 break;
2217 }
2218 }
2219}
2220
2221/// ParseParameterList
2222/// ::= '(' ')'
2223/// ::= '(' Arg (',' Arg)* ')'
2224/// Arg
2225/// ::= Type OptionalAttributes Value OptionalAttributes
2226bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002227 PerFunctionState &PFS, bool IsMustTailCall,
2228 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 if (ParseToken(lltok::lparen, "expected '(' in call"))
2230 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002231
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 while (Lex.getKind() != lltok::rparen) {
2233 // If this isn't the first argument, we need a comma.
2234 if (!ArgList.empty() &&
2235 ParseToken(lltok::comma, "expected ',' in argument list"))
2236 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002237
Reid Kleckner83498642014-08-26 00:33:28 +00002238 // Parse an ellipsis if this is a musttail call in a variadic function.
2239 if (Lex.getKind() == lltok::dotdotdot) {
2240 const char *Msg = "unexpected ellipsis in argument list for ";
2241 if (!IsMustTailCall)
2242 return TokError(Twine(Msg) + "non-musttail call");
2243 if (!InVarArgsFunc)
2244 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2245 Lex.Lex(); // Lex the '...', it is purely for readability.
2246 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2247 }
2248
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 // Parse the argument.
2250 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002251 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002252 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002253 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002254 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002256
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002257 if (ArgTy->isMetadataTy()) {
2258 if (ParseMetadataAsValue(V, PFS))
2259 return true;
2260 } else {
2261 // Otherwise, handle normal operands.
2262 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2263 return true;
2264 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002265 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002266 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 }
2268
Reid Kleckner83498642014-08-26 00:33:28 +00002269 if (IsMustTailCall && InVarArgsFunc)
2270 return TokError("expected '...' at end of argument list for musttail call "
2271 "in varargs function");
2272
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 Lex.Lex(); // Lex the ')'.
2274 return false;
2275}
2276
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002277/// ParseOptionalOperandBundles
2278/// ::= /*empty*/
2279/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2280///
2281/// OperandBundle
2282/// ::= bundle-tag '(' ')'
2283/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2284///
2285/// bundle-tag ::= String Constant
2286bool LLParser::ParseOptionalOperandBundles(
2287 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2288 LocTy BeginLoc = Lex.getLoc();
2289 if (!EatIfPresent(lltok::lsquare))
2290 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002292 while (Lex.getKind() != lltok::rsquare) {
2293 // If this isn't the first operand bundle, we need a comma.
2294 if (!BundleList.empty() &&
2295 ParseToken(lltok::comma, "expected ',' in input list"))
2296 return true;
2297
2298 std::string Tag;
2299 if (ParseStringConstant(Tag))
2300 return true;
2301
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002302 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2303 return true;
2304
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002305 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002306 while (Lex.getKind() != lltok::rparen) {
2307 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002308 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002309 ParseToken(lltok::comma, "expected ',' in input list"))
2310 return true;
2311
2312 Type *Ty = nullptr;
2313 Value *Input = nullptr;
2314 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2315 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002316 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002317 }
2318
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002319 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2320
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002321 Lex.Lex(); // Lex the ')'.
2322 }
2323
2324 if (BundleList.empty())
2325 return Error(BeginLoc, "operand bundle set must not be empty");
2326
2327 Lex.Lex(); // Lex the ']'.
2328 return false;
2329}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002330
Chris Lattner2ed06b42009-01-05 18:34:07 +00002331/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002332/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333/// ::= '(' ArgTypeListI ')'
2334/// ArgTypeListI
2335/// ::= /*empty*/
2336/// ::= '...'
2337/// ::= ArgTypeList ',' '...'
2338/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002339///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002340bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2341 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 isVarArg = false;
2343 assert(Lex.getKind() == lltok::lparen);
2344 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 if (Lex.getKind() == lltok::rparen) {
2347 // empty
2348 } else if (Lex.getKind() == lltok::dotdotdot) {
2349 isVarArg = true;
2350 Lex.Lex();
2351 } else {
2352 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002353 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002354 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002355 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002356
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002358 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002359
Chris Lattnerfdd87902009-10-05 05:54:46 +00002360 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002361 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002362
Chris Lattnerdef19492011-06-17 06:36:20 +00002363 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 Name = Lex.getStrVal();
2365 Lex.Lex();
2366 }
Chris Lattner3822f632009-01-02 08:05:26 +00002367
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002368 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002369 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002371 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002372 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002373 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002374
Chris Lattner3822f632009-01-02 08:05:26 +00002375 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002377 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379 break;
2380 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 // Otherwise must be an argument type.
2383 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002384 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002385
Chris Lattnerfdd87902009-10-05 05:54:46 +00002386 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002387 return Error(TypeLoc, "argument can not have void type");
2388
Chris Lattnerdef19492011-06-17 06:36:20 +00002389 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002390 Name = Lex.getStrVal();
2391 Lex.Lex();
2392 } else {
2393 Name = "";
2394 }
Chris Lattner3822f632009-01-02 08:05:26 +00002395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002397 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002398
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002399 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002400 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002401 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 }
2403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002404
Chris Lattner3822f632009-01-02 08:05:26 +00002405 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002407
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408/// ParseFunctionType
2409/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002410bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411 assert(Lex.getKind() == lltok::lparen);
2412
Chris Lattnerce473c72009-01-05 08:04:33 +00002413 if (!FunctionType::isValidReturnType(Result))
2414 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002415
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002416 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002418 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002420
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421 // Reject names on the arguments lists.
2422 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2423 if (!ArgList[i].Name.empty())
2424 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002425 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002426 return Error(ArgList[i].Loc,
2427 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002429
Jay Foadb804a2b2011-07-12 14:06:48 +00002430 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002432 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002434 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002435 return false;
2436}
2437
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002438/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2439/// other structs.
2440bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2441 SmallVector<Type*, 8> Elts;
2442 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002443
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002444 Result = StructType::get(Context, Elts, Packed);
2445 return false;
2446}
2447
2448/// ParseStructDefinition - Parse a struct in a 'type' definition.
2449bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2450 std::pair<Type*, LocTy> &Entry,
2451 Type *&ResultTy) {
2452 // If the type was already defined, diagnose the redefinition.
2453 if (Entry.first && !Entry.second.isValid())
2454 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002455
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002456 // If we have opaque, just return without filling in the definition for the
2457 // struct. This counts as a definition as far as the .ll file goes.
2458 if (EatIfPresent(lltok::kw_opaque)) {
2459 // This type is being defined, so clear the location to indicate this.
2460 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002461
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002462 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002463 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002464 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002465 ResultTy = Entry.first;
2466 return false;
2467 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002469 // If the type starts with '<', then it is either a packed struct or a vector.
2470 bool isPacked = EatIfPresent(lltok::less);
2471
2472 // If we don't have a struct, then we have a random type alias, which we
2473 // accept for compatibility with old files. These types are not allowed to be
2474 // forward referenced and not allowed to be recursive.
2475 if (Lex.getKind() != lltok::lbrace) {
2476 if (Entry.first)
2477 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002478
Craig Topper2617dcc2014-04-15 06:32:26 +00002479 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002480 if (isPacked)
2481 return ParseArrayVectorType(ResultTy, true);
2482 return ParseType(ResultTy);
2483 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002484
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002485 // This type is being defined, so clear the location to indicate this.
2486 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002487
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002488 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002489 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002490 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002491
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002492 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002493
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002494 SmallVector<Type*, 8> Body;
2495 if (ParseStructBody(Body) ||
2496 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2497 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002498
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002499 STy->setBody(Body, isPacked);
2500 ResultTy = STy;
2501 return false;
2502}
2503
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002505/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002506/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002507/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002509/// ::= '<' '{' Type (',' Type)* '}' '>'
2510bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 assert(Lex.getKind() == lltok::lbrace);
2512 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002513
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002514 // Handle the empty struct.
2515 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517
Chris Lattnerf880ca22009-03-09 04:49:14 +00002518 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002519 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002520 if (ParseType(Ty)) return true;
2521 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002523 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002524 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002525
Chris Lattner3822f632009-01-02 08:05:26 +00002526 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002527 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002528 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002529
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002530 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002531 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002532
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002533 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002535
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002536 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537}
2538
2539/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2540/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002541/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002542/// ::= '[' APSINTVAL 'x' Types ']'
2543/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002544bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2546 Lex.getAPSIntVal().getBitWidth() > 64)
2547 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002548
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 LocTy SizeLoc = Lex.getLoc();
2550 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002551 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002552
Chris Lattner3822f632009-01-02 08:05:26 +00002553 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2554 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555
2556 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002557 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002558 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002559
Chris Lattner3822f632009-01-02 08:05:26 +00002560 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2561 "expected end of sequential type"))
2562 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002565 if (Size == 0)
2566 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 if ((unsigned)Size != Size)
2568 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002569 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002570 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002571 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002573 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002575 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 }
2577 return false;
2578}
2579
2580//===----------------------------------------------------------------------===//
2581// Function Semantic Analysis.
2582//===----------------------------------------------------------------------===//
2583
Chris Lattner3432c622009-10-28 03:39:23 +00002584LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2585 int functionNumber)
2586 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587
2588 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002589 for (Argument &A : F.args())
2590 if (!A.hasName())
2591 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592}
2593
2594LLParser::PerFunctionState::~PerFunctionState() {
2595 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002596
David Blaikie9ebdc692015-09-21 21:07:50 +00002597 for (const auto &P : ForwardRefVals) {
2598 if (isa<BasicBlock>(P.second.first))
2599 continue;
2600 P.second.first->replaceAllUsesWith(
2601 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002602 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002603 }
2604
2605 for (const auto &P : ForwardRefValIDs) {
2606 if (isa<BasicBlock>(P.second.first))
2607 continue;
2608 P.second.first->replaceAllUsesWith(
2609 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002610 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002611 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612}
2613
Chris Lattner3432c622009-10-28 03:39:23 +00002614bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002615 if (!ForwardRefVals.empty())
2616 return P.Error(ForwardRefVals.begin()->second.second,
2617 "use of undefined value '%" + ForwardRefVals.begin()->first +
2618 "'");
2619 if (!ForwardRefValIDs.empty())
2620 return P.Error(ForwardRefValIDs.begin()->second.second,
2621 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002622 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 return false;
2624}
2625
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002626static bool isValidVariableType(Module *M, Type *Ty, Value *Val, bool IsCall) {
2627 if (Val->getType() == Ty)
2628 return true;
2629 // For calls we also accept variables in the program address space
2630 if (IsCall && isa<PointerType>(Ty)) {
2631 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
2632 M->getDataLayout().getProgramAddressSpace());
2633 if (Val->getType() == TyInProgAS)
2634 return true;
2635 }
2636 return false;
2637}
2638
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639/// GetVal - Get a value with the specified name or ID, creating a
2640/// forward reference record if needed. This can return null if the value
2641/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002642Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002643 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002644 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002645 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 // If this is a forward reference for the value, see if we already created a
2648 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002649 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002650 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 if (I != ForwardRefVals.end())
2652 Val = I->second.first;
2653 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002654
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 // If we have the value in the symbol table or fwd-ref table, return it.
2656 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002657 if (isValidVariableType(P.M, Ty, Val, IsCall))
2658 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002659 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660 P.Error(Loc, "'%" + Name + "' is not a basic block");
2661 else
2662 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002663 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002664 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002668 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002670 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002672
Chris Lattnerac161bf2009-01-02 07:01:27 +00002673 // Otherwise, create a new forward reference for this value and remember it.
2674 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002675 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002676 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002677 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002678 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002679 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002680
Chris Lattnerac161bf2009-01-02 07:01:27 +00002681 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2682 return FwdVal;
2683}
2684
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002685Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2686 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002688 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002689
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 // If this is a forward reference for the value, see if we already created a
2691 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002692 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002693 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 if (I != ForwardRefValIDs.end())
2695 Val = I->second.first;
2696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002697
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 // If we have the value in the symbol table or fwd-ref table, return it.
2699 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002700 if (isValidVariableType(P.M, Ty, Val, IsCall))
2701 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002702 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002703 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002705 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002706 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002707 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002709
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002710 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002712 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 // Otherwise, create a new forward reference for this value and remember it.
2716 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002717 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002718 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002719 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002720 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002721 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002722
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2724 return FwdVal;
2725}
2726
2727/// SetInstName - After an instruction is parsed and inserted into its
2728/// basic block, this installs its name.
2729bool LLParser::PerFunctionState::SetInstName(int NameID,
2730 const std::string &NameStr,
2731 LocTy NameLoc, Instruction *Inst) {
2732 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002733 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 if (NameID != -1 || !NameStr.empty())
2735 return P.Error(NameLoc, "instructions returning void cannot have a name");
2736 return false;
2737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002738
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 // If this was a numbered instruction, verify that the instruction is the
2740 // expected value and resolve any forward references.
2741 if (NameStr.empty()) {
2742 // If neither a name nor an ID was specified, just use the next ID.
2743 if (NameID == -1)
2744 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002745
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746 if (unsigned(NameID) != NumberedVals.size())
2747 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002748 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002749
David Blaikie9ebdc692015-09-21 21:07:50 +00002750 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002751 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002752 Value *Sentinel = FI->second.first;
2753 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002754 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002755 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002756
2757 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002758 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002759 ForwardRefValIDs.erase(FI);
2760 }
2761
2762 NumberedVals.push_back(Inst);
2763 return false;
2764 }
2765
2766 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002767 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002769 Value *Sentinel = FI->second.first;
2770 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002771 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002772 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002773
2774 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002775 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 ForwardRefVals.erase(FI);
2777 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002778
Chris Lattnerac161bf2009-01-02 07:01:27 +00002779 // Set the name on the instruction.
2780 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002782 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002783 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 NameStr + "'");
2785 return false;
2786}
2787
2788/// GetBB - Get a basic block with the specified name or ID, creating a
2789/// forward reference record if needed.
2790BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2791 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002792 return dyn_cast_or_null<BasicBlock>(
2793 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794}
2795
2796BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002797 return dyn_cast_or_null<BasicBlock>(
2798 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799}
2800
2801/// DefineBB - Define the specified basic block, which is either named or
2802/// unnamed. If there is an error, this returns null otherwise it returns
2803/// the block being defined.
2804BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2805 LocTy Loc) {
2806 BasicBlock *BB;
2807 if (Name.empty())
2808 BB = GetBB(NumberedVals.size(), Loc);
2809 else
2810 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002811 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 // Move the block to the end of the function. Forward ref'd blocks are
2814 // inserted wherever they happen to be referenced.
2815 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002816
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 // Remove the block from forward ref sets.
2818 if (Name.empty()) {
2819 ForwardRefValIDs.erase(NumberedVals.size());
2820 NumberedVals.push_back(BB);
2821 } else {
2822 // BB forward references are already in the function symbol table.
2823 ForwardRefVals.erase(Name);
2824 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002825
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 return BB;
2827}
2828
2829//===----------------------------------------------------------------------===//
2830// Constants.
2831//===----------------------------------------------------------------------===//
2832
2833/// ParseValID - Parse an abstract value that doesn't necessarily have a
2834/// type implied. For example, if we parse "4" we don't know what integer type
2835/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002836/// sanity. PFS is used to convert function-local operands of metadata (since
2837/// metadata operands are not just parsed here but also converted to values).
2838/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002839bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 ID.Loc = Lex.getLoc();
2841 switch (Lex.getKind()) {
2842 default: return TokError("expected value token");
2843 case lltok::GlobalID: // @42
2844 ID.UIntVal = Lex.getUIntVal();
2845 ID.Kind = ValID::t_GlobalID;
2846 break;
2847 case lltok::GlobalVar: // @foo
2848 ID.StrVal = Lex.getStrVal();
2849 ID.Kind = ValID::t_GlobalName;
2850 break;
2851 case lltok::LocalVarID: // %42
2852 ID.UIntVal = Lex.getUIntVal();
2853 ID.Kind = ValID::t_LocalID;
2854 break;
2855 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 ID.StrVal = Lex.getStrVal();
2857 ID.Kind = ValID::t_LocalName;
2858 break;
2859 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002860 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002861 ID.Kind = ValID::t_APSInt;
2862 break;
2863 case lltok::APFloat:
2864 ID.APFloatVal = Lex.getAPFloatVal();
2865 ID.Kind = ValID::t_APFloat;
2866 break;
2867 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002868 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 ID.Kind = ValID::t_Constant;
2870 break;
2871 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002872 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 ID.Kind = ValID::t_Constant;
2874 break;
2875 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2876 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2877 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002878 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002879
Chris Lattnerac161bf2009-01-02 07:01:27 +00002880 case lltok::lbrace: {
2881 // ValID ::= '{' ConstVector '}'
2882 Lex.Lex();
2883 SmallVector<Constant*, 16> Elts;
2884 if (ParseGlobalValueVector(Elts) ||
2885 ParseToken(lltok::rbrace, "expected end of struct constant"))
2886 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
David Blaikieadbda4b2015-08-03 20:08:41 +00002888 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002889 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002890 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2891 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002892 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 return false;
2894 }
2895 case lltok::less: {
2896 // ValID ::= '<' ConstVector '>' --> Vector.
2897 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2898 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002899 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002900
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 SmallVector<Constant*, 16> Elts;
2902 LocTy FirstEltLoc = Lex.getLoc();
2903 if (ParseGlobalValueVector(Elts) ||
2904 (isPackedStruct &&
2905 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2906 ParseToken(lltok::greater, "expected end of constant"))
2907 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002908
Chris Lattnerac161bf2009-01-02 07:01:27 +00002909 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002910 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2911 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2912 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002913 ID.UIntVal = Elts.size();
2914 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002915 return false;
2916 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002917
Chris Lattnerac161bf2009-01-02 07:01:27 +00002918 if (Elts.empty())
2919 return Error(ID.Loc, "constant vector must not be empty");
2920
Duncan Sands9dff9be2010-02-15 16:12:20 +00002921 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002922 !Elts[0]->getType()->isFloatingPointTy() &&
2923 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002924 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002925 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002926
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927 // Verify that all the vector elements have the same type.
2928 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2929 if (Elts[i]->getType() != Elts[0]->getType())
2930 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002931 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002932 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002933
Chris Lattner69229312011-02-15 00:14:00 +00002934 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002935 ID.Kind = ValID::t_Constant;
2936 return false;
2937 }
2938 case lltok::lsquare: { // Array Constant
2939 Lex.Lex();
2940 SmallVector<Constant*, 16> Elts;
2941 LocTy FirstEltLoc = Lex.getLoc();
2942 if (ParseGlobalValueVector(Elts) ||
2943 ParseToken(lltok::rsquare, "expected end of array constant"))
2944 return true;
2945
2946 // Handle empty element.
2947 if (Elts.empty()) {
2948 // Use undef instead of an array because it's inconvenient to determine
2949 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002950 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002951 return false;
2952 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002953
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002955 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002956 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002957
Owen Anderson4056ca92009-07-29 22:17:13 +00002958 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002959
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002961 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 if (Elts[i]->getType() != Elts[0]->getType())
2963 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002964 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002965 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002967
Jay Foad83be3612011-06-22 09:24:39 +00002968 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 ID.Kind = ValID::t_Constant;
2970 return false;
2971 }
2972 case lltok::kw_c: // c "foo"
2973 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002974 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2975 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002976 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2977 ID.Kind = ValID::t_Constant;
2978 return false;
2979
2980 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002981 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2982 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002983 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002984 Lex.Lex();
2985 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002986 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002987 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002988 ParseStringConstant(ID.StrVal) ||
2989 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002990 ParseToken(lltok::StringConstant, "expected constraint string"))
2991 return true;
2992 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002993 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002994 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002995 ID.Kind = ValID::t_InlineAsm;
2996 return false;
2997 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002998
Chris Lattner3432c622009-10-28 03:39:23 +00002999 case lltok::kw_blockaddress: {
3000 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3001 Lex.Lex();
3002
3003 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003004
Chris Lattner3432c622009-10-28 03:39:23 +00003005 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3006 ParseValID(Fn) ||
3007 ParseToken(lltok::comma, "expected comma in block address expression")||
3008 ParseValID(Label) ||
3009 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3010 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003011
Chris Lattner3432c622009-10-28 03:39:23 +00003012 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3013 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003014 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003015 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003016
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003017 // Try to find the function (but skip it if it's forward-referenced).
3018 GlobalValue *GV = nullptr;
3019 if (Fn.Kind == ValID::t_GlobalID) {
3020 if (Fn.UIntVal < NumberedVals.size())
3021 GV = NumberedVals[Fn.UIntVal];
3022 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3023 GV = M->getNamedValue(Fn.StrVal);
3024 }
3025 Function *F = nullptr;
3026 if (GV) {
3027 // Confirm that it's actually a function with a definition.
3028 if (!isa<Function>(GV))
3029 return Error(Fn.Loc, "expected function name in blockaddress");
3030 F = cast<Function>(GV);
3031 if (F->isDeclaration())
3032 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3033 }
3034
3035 if (!F) {
3036 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003037 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003038 ForwardRefBlockAddresses.insert(std::make_pair(
3039 std::move(Fn),
3040 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003041 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3042 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003043 if (!FwdRef)
3044 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3045 GlobalValue::InternalLinkage, nullptr, "");
3046 ID.ConstantVal = FwdRef;
3047 ID.Kind = ValID::t_Constant;
3048 return false;
3049 }
3050
3051 // We found the function; now find the basic block. Don't use PFS, since we
3052 // might be inside a constant expression.
3053 BasicBlock *BB;
3054 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3055 if (Label.Kind == ValID::t_LocalID)
3056 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3057 else
3058 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3059 if (!BB)
3060 return Error(Label.Loc, "referenced value is not a basic block");
3061 } else {
3062 if (Label.Kind == ValID::t_LocalID)
3063 return Error(Label.Loc, "cannot take address of numeric label after "
3064 "the function is defined");
3065 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003066 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003067 if (!BB)
3068 return Error(Label.Loc, "referenced value is not a basic block");
3069 }
3070
3071 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003072 ID.Kind = ValID::t_Constant;
3073 return false;
3074 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003075
Chris Lattnerac161bf2009-01-02 07:01:27 +00003076 case lltok::kw_trunc:
3077 case lltok::kw_zext:
3078 case lltok::kw_sext:
3079 case lltok::kw_fptrunc:
3080 case lltok::kw_fpext:
3081 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003082 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 case lltok::kw_uitofp:
3084 case lltok::kw_sitofp:
3085 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003086 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003088 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003089 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003090 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003091 Constant *SrcVal;
3092 Lex.Lex();
3093 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3094 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003095 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003096 ParseType(DestTy) ||
3097 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3098 return true;
3099 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3100 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003101 getTypeString(SrcVal->getType()) + "' to '" +
3102 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003103 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003104 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003105 ID.Kind = ValID::t_Constant;
3106 return false;
3107 }
3108 case lltok::kw_extractvalue: {
3109 Lex.Lex();
3110 Constant *Val;
3111 SmallVector<unsigned, 4> Indices;
3112 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3113 ParseGlobalTypeAndValue(Val) ||
3114 ParseIndexList(Indices) ||
3115 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3116 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003117
Chris Lattner392be582010-02-12 20:49:41 +00003118 if (!Val->getType()->isAggregateType())
3119 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003120 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003121 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003122 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003123 ID.Kind = ValID::t_Constant;
3124 return false;
3125 }
3126 case lltok::kw_insertvalue: {
3127 Lex.Lex();
3128 Constant *Val0, *Val1;
3129 SmallVector<unsigned, 4> Indices;
3130 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3131 ParseGlobalTypeAndValue(Val0) ||
3132 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3133 ParseGlobalTypeAndValue(Val1) ||
3134 ParseIndexList(Indices) ||
3135 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3136 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003137 if (!Val0->getType()->isAggregateType())
3138 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003139 Type *IndexedType =
3140 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3141 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003143 if (IndexedType != Val1->getType())
3144 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3145 getTypeString(Val1->getType()) +
3146 "' instead of '" + getTypeString(IndexedType) +
3147 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003148 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003149 ID.Kind = ValID::t_Constant;
3150 return false;
3151 }
3152 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003153 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003154 unsigned PredVal, Opc = Lex.getUIntVal();
3155 Constant *Val0, *Val1;
3156 Lex.Lex();
3157 if (ParseCmpPredicate(PredVal, Opc) ||
3158 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3159 ParseGlobalTypeAndValue(Val0) ||
3160 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3161 ParseGlobalTypeAndValue(Val1) ||
3162 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3163 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003164
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 if (Val0->getType() != Val1->getType())
3166 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003167
Chris Lattnerac161bf2009-01-02 07:01:27 +00003168 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003169
Chris Lattnerac161bf2009-01-02 07:01:27 +00003170 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003171 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003173 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003174 } else {
3175 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003176 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003177 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003178 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003179 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003180 }
3181 ID.Kind = ValID::t_Constant;
3182 return false;
3183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003184
Chris Lattnerac161bf2009-01-02 07:01:27 +00003185 // Binary Operators.
3186 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003187 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003188 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003189 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003191 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003192 case lltok::kw_udiv:
3193 case lltok::kw_sdiv:
3194 case lltok::kw_fdiv:
3195 case lltok::kw_urem:
3196 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003197 case lltok::kw_frem:
3198 case lltok::kw_shl:
3199 case lltok::kw_lshr:
3200 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003201 bool NUW = false;
3202 bool NSW = false;
3203 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003204 unsigned Opc = Lex.getUIntVal();
3205 Constant *Val0, *Val1;
3206 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003207 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003208 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3209 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003210 if (EatIfPresent(lltok::kw_nuw))
3211 NUW = true;
3212 if (EatIfPresent(lltok::kw_nsw)) {
3213 NSW = true;
3214 if (EatIfPresent(lltok::kw_nuw))
3215 NUW = true;
3216 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003217 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3218 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003219 if (EatIfPresent(lltok::kw_exact))
3220 Exact = true;
3221 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003222 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3223 ParseGlobalTypeAndValue(Val0) ||
3224 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3225 ParseGlobalTypeAndValue(Val1) ||
3226 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3227 return true;
3228 if (Val0->getType() != Val1->getType())
3229 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003230 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003231 if (NUW)
3232 return Error(ModifierLoc, "nuw only applies to integer operations");
3233 if (NSW)
3234 return Error(ModifierLoc, "nsw only applies to integer operations");
3235 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003236 // Check that the type is valid for the operator.
3237 switch (Opc) {
3238 case Instruction::Add:
3239 case Instruction::Sub:
3240 case Instruction::Mul:
3241 case Instruction::UDiv:
3242 case Instruction::SDiv:
3243 case Instruction::URem:
3244 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003245 case Instruction::Shl:
3246 case Instruction::AShr:
3247 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003248 if (!Val0->getType()->isIntOrIntVectorTy())
3249 return Error(ID.Loc, "constexpr requires integer operands");
3250 break;
3251 case Instruction::FAdd:
3252 case Instruction::FSub:
3253 case Instruction::FMul:
3254 case Instruction::FDiv:
3255 case Instruction::FRem:
3256 if (!Val0->getType()->isFPOrFPVectorTy())
3257 return Error(ID.Loc, "constexpr requires fp operands");
3258 break;
3259 default: llvm_unreachable("Unknown binary operator!");
3260 }
Dan Gohman1b849082009-09-07 23:54:19 +00003261 unsigned Flags = 0;
3262 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3263 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003264 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003265 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003266 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 ID.Kind = ValID::t_Constant;
3268 return false;
3269 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003270
Chris Lattnerac161bf2009-01-02 07:01:27 +00003271 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003272 case lltok::kw_and:
3273 case lltok::kw_or:
3274 case lltok::kw_xor: {
3275 unsigned Opc = Lex.getUIntVal();
3276 Constant *Val0, *Val1;
3277 Lex.Lex();
3278 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3279 ParseGlobalTypeAndValue(Val0) ||
3280 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3281 ParseGlobalTypeAndValue(Val1) ||
3282 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3283 return true;
3284 if (Val0->getType() != Val1->getType())
3285 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003286 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003287 return Error(ID.Loc,
3288 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003289 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 ID.Kind = ValID::t_Constant;
3291 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003292 }
3293
Chris Lattnerac161bf2009-01-02 07:01:27 +00003294 case lltok::kw_getelementptr:
3295 case lltok::kw_shufflevector:
3296 case lltok::kw_insertelement:
3297 case lltok::kw_extractelement:
3298 case lltok::kw_select: {
3299 unsigned Opc = Lex.getUIntVal();
3300 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003301 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003302 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003303 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003304
Dan Gohman1639c392009-07-27 21:53:46 +00003305 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003306 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003307
3308 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3309 return true;
3310
3311 LocTy ExplicitTypeLoc = Lex.getLoc();
3312 if (Opc == Instruction::GetElementPtr) {
3313 if (ParseType(Ty) ||
3314 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3315 return true;
3316 }
3317
Peter Collingbourned93620b2016-11-10 22:34:55 +00003318 Optional<unsigned> InRangeOp;
3319 if (ParseGlobalValueVector(
3320 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003321 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3322 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003323
Chris Lattnerac161bf2009-01-02 07:01:27 +00003324 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003325 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003326 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003327 return Error(ID.Loc, "base of getelementptr must be a pointer");
3328
3329 Type *BaseType = Elts[0]->getType();
3330 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003331 if (Ty != BasePointerType->getElementType())
3332 return Error(
3333 ExplicitTypeLoc,
3334 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003335
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003336 unsigned GEPWidth =
3337 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3338
Jay Foaded8db7d2011-07-21 14:31:17 +00003339 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003340 for (Constant *Val : Indices) {
3341 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003342 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003343 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003344 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003345 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003346 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003347 return Error(
3348 ID.Loc,
3349 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003350 // GEPWidth may have been unknown because the base is a scalar,
3351 // but it is known now.
3352 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003353 }
3354 }
3355
Craig Toppere3dcce92015-08-01 22:20:21 +00003356 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003357 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003358 return Error(ID.Loc, "base element of getelementptr must be sized");
3359
David Blaikie4a2e73b2015-04-02 18:55:32 +00003360 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003361 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003362
3363 if (InRangeOp) {
3364 if (*InRangeOp == 0)
3365 return Error(ID.Loc,
3366 "inrange keyword may not appear on pointer operand");
3367 --*InRangeOp;
3368 }
3369
3370 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3371 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003372 } else if (Opc == Instruction::Select) {
3373 if (Elts.size() != 3)
3374 return Error(ID.Loc, "expected three operands to select");
3375 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3376 Elts[2]))
3377 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003378 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003379 } else if (Opc == Instruction::ShuffleVector) {
3380 if (Elts.size() != 3)
3381 return Error(ID.Loc, "expected three operands to shufflevector");
3382 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3383 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003384 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003385 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003386 } else if (Opc == Instruction::ExtractElement) {
3387 if (Elts.size() != 2)
3388 return Error(ID.Loc, "expected two operands to extractelement");
3389 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3390 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003391 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003392 } else {
3393 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3394 if (Elts.size() != 3)
3395 return Error(ID.Loc, "expected three operands to insertelement");
3396 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3397 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003398 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003399 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003400 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003401
Chris Lattnerac161bf2009-01-02 07:01:27 +00003402 ID.Kind = ValID::t_Constant;
3403 return false;
3404 }
3405 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003406
Chris Lattnerac161bf2009-01-02 07:01:27 +00003407 Lex.Lex();
3408 return false;
3409}
3410
3411/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003412bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003413 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003414 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003415 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003416 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003417 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003418 if (V && !(C = dyn_cast<Constant>(V)))
3419 return Error(ID.Loc, "global values must be constants");
3420 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003421}
3422
Victor Hernandez9d75c962010-01-11 22:31:58 +00003423bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003424 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003425 return ParseType(Ty) ||
3426 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003427}
3428
Rafael Espindola83a362c2015-01-06 22:55:16 +00003429bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003430 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003431
3432 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003433 if (!EatIfPresent(lltok::kw_comdat))
3434 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003435
3436 if (EatIfPresent(lltok::lparen)) {
3437 if (Lex.getKind() != lltok::ComdatVar)
3438 return TokError("expected comdat variable");
3439 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3440 Lex.Lex();
3441 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3442 return true;
3443 } else {
3444 if (GlobalName.empty())
3445 return TokError("comdat cannot be unnamed");
3446 C = getComdat(GlobalName, KwLoc);
3447 }
3448
David Majnemerdad0a642014-06-27 18:19:56 +00003449 return false;
3450}
3451
Victor Hernandez9d75c962010-01-11 22:31:58 +00003452/// ParseGlobalValueVector
3453/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003454/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3455bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3456 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003457 // Empty list.
3458 if (Lex.getKind() == lltok::rbrace ||
3459 Lex.getKind() == lltok::rsquare ||
3460 Lex.getKind() == lltok::greater ||
3461 Lex.getKind() == lltok::rparen)
3462 return false;
3463
Peter Collingbourned93620b2016-11-10 22:34:55 +00003464 do {
3465 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3466 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003467
Peter Collingbourned93620b2016-11-10 22:34:55 +00003468 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003469 if (ParseGlobalTypeAndValue(C)) return true;
3470 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003471 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003472
3473 return false;
3474}
3475
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003476bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003477 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003478 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003479 return true;
3480
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003481 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003482 return false;
3483}
3484
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003485/// MDNode:
3486/// ::= !{ ... }
3487/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003488/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003489bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003490 if (Lex.getKind() == lltok::MetadataVar)
3491 return ParseSpecializedMDNode(N);
3492
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003493 return ParseToken(lltok::exclaim, "expected '!' here") ||
3494 ParseMDNodeTail(N);
3495}
3496
3497bool LLParser::ParseMDNodeTail(MDNode *&N) {
3498 // !{ ... }
3499 if (Lex.getKind() == lltok::lbrace)
3500 return ParseMDTuple(N);
3501
3502 // !42
3503 return ParseMDNodeID(N);
3504}
3505
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003506namespace {
3507
3508/// Structure to represent an optional metadata field.
3509template <class FieldTy> struct MDFieldImpl {
3510 typedef MDFieldImpl ImplTy;
3511 FieldTy Val;
3512 bool Seen;
3513
3514 void assign(FieldTy Val) {
3515 Seen = true;
3516 this->Val = std::move(Val);
3517 }
3518
3519 explicit MDFieldImpl(FieldTy Default)
3520 : Val(std::move(Default)), Seen(false) {}
3521};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003522
Sander de Smalenfdf40912018-01-24 09:56:07 +00003523/// Structure to represent an optional metadata field that
3524/// can be of either type (A or B) and encapsulates the
3525/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3526/// to reimplement the specifics for representing each Field.
3527template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3528 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3529 FieldTypeA A;
3530 FieldTypeB B;
3531 bool Seen;
3532
3533 enum {
3534 IsInvalid = 0,
3535 IsTypeA = 1,
3536 IsTypeB = 2
3537 } WhatIs;
3538
3539 void assign(FieldTypeA A) {
3540 Seen = true;
3541 this->A = std::move(A);
3542 WhatIs = IsTypeA;
3543 }
3544
3545 void assign(FieldTypeB B) {
3546 Seen = true;
3547 this->B = std::move(B);
3548 WhatIs = IsTypeB;
3549 }
3550
3551 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3552 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3553 WhatIs(IsInvalid) {}
3554};
3555
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003556struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3557 uint64_t Max;
3558
3559 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3560 : ImplTy(Default), Max(Max) {}
3561};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003562
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003563struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003564 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003565};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003566
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003567struct ColumnField : public MDUnsignedField {
3568 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3569};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003570
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003571struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003572 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003573 DwarfTagField(dwarf::Tag DefaultTag)
3574 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003575};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003576
Amjad Abouda9bcf162015-12-10 12:56:35 +00003577struct DwarfMacinfoTypeField : public MDUnsignedField {
3578 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3579 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3580 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3581};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003582
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003583struct DwarfAttEncodingField : public MDUnsignedField {
3584 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3585};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003586
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003587struct DwarfVirtualityField : public MDUnsignedField {
3588 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3589};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003590
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003591struct DwarfLangField : public MDUnsignedField {
3592 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3593};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003594
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003595struct DwarfCCField : public MDUnsignedField {
3596 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3597};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003598
Adrian Prantlb939a252016-03-31 23:56:58 +00003599struct EmissionKindField : public MDUnsignedField {
3600 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3601};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003602
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003603struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3604 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003605};
3606
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003607struct MDSignedField : public MDFieldImpl<int64_t> {
3608 int64_t Min;
3609 int64_t Max;
3610
3611 MDSignedField(int64_t Default = 0)
3612 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3613 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3614 : ImplTy(Default), Min(Min), Max(Max) {}
3615};
3616
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003617struct MDBoolField : public MDFieldImpl<bool> {
3618 MDBoolField(bool Default = false) : ImplTy(Default) {}
3619};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003620
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003621struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003622 bool AllowNull;
3623
3624 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003625};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003626
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003627struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3628 MDConstant() : ImplTy(nullptr) {}
3629};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003630
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003631struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003632 bool AllowEmpty;
3633 MDStringField(bool AllowEmpty = true)
3634 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003635};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003636
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003637struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3638 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3639};
3640
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003641struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003642 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3643};
3644
Sander de Smalenfdf40912018-01-24 09:56:07 +00003645struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3646 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3647 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3648
3649 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3650 bool AllowNull = true)
3651 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3652
3653 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3654 bool isMDField() const { return WhatIs == IsTypeB; }
3655 int64_t getMDSignedValue() const {
3656 assert(isMDSignedField() && "Wrong field type");
3657 return A.Val;
3658 }
3659 Metadata *getMDFieldValue() const {
3660 assert(isMDField() && "Wrong field type");
3661 return B.Val;
3662 }
3663};
3664
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003665struct MDSignedOrUnsignedField
3666 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3667 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3668
3669 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3670 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3671 int64_t getMDSignedValue() const {
3672 assert(isMDSignedField() && "Wrong field type");
3673 return A.Val;
3674 }
3675 uint64_t getMDUnsignedValue() const {
3676 assert(isMDUnsignedField() && "Wrong field type");
3677 return B.Val;
3678 }
3679};
3680
Eugene Zelenko1804a772016-08-25 00:45:04 +00003681} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003682
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003683namespace llvm {
3684
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003685template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003686bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003687 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003688 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3689 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003690
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003691 auto &U = Lex.getAPSIntVal();
3692 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003693 return TokError("value for '" + Name + "' too large, limit is " +
3694 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003695 Result.assign(U.getZExtValue());
3696 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003697 Lex.Lex();
3698 return false;
3699}
3700
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003701template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003702bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3703 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3704}
3705template <>
3706bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3707 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3708}
3709
3710template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003711bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3712 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003713 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003714
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003715 if (Lex.getKind() != lltok::DwarfTag)
3716 return TokError("expected DWARF tag");
3717
3718 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3719 if (Tag == dwarf::DW_TAG_invalid)
3720 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003721 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003722
3723 Result.assign(Tag);
3724 Lex.Lex();
3725 return false;
3726}
3727
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003728template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003729bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003730 DwarfMacinfoTypeField &Result) {
3731 if (Lex.getKind() == lltok::APSInt)
3732 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3733
3734 if (Lex.getKind() != lltok::DwarfMacinfo)
3735 return TokError("expected DWARF macinfo type");
3736
3737 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3738 if (Macinfo == dwarf::DW_MACINFO_invalid)
3739 return TokError(
3740 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3741 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3742
3743 Result.assign(Macinfo);
3744 Lex.Lex();
3745 return false;
3746}
3747
3748template <>
3749bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003750 DwarfVirtualityField &Result) {
3751 if (Lex.getKind() == lltok::APSInt)
3752 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3753
3754 if (Lex.getKind() != lltok::DwarfVirtuality)
3755 return TokError("expected DWARF virtuality code");
3756
3757 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003758 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003759 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3760 Lex.getStrVal() + "'");
3761 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3762 Result.assign(Virtuality);
3763 Lex.Lex();
3764 return false;
3765}
3766
3767template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003768bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3769 if (Lex.getKind() == lltok::APSInt)
3770 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3771
3772 if (Lex.getKind() != lltok::DwarfLang)
3773 return TokError("expected DWARF language");
3774
3775 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3776 if (!Lang)
3777 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3778 "'");
3779 assert(Lang <= Result.Max && "Expected valid DWARF language");
3780 Result.assign(Lang);
3781 Lex.Lex();
3782 return false;
3783}
3784
3785template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003786bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3787 if (Lex.getKind() == lltok::APSInt)
3788 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3789
3790 if (Lex.getKind() != lltok::DwarfCC)
3791 return TokError("expected DWARF calling convention");
3792
3793 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3794 if (!CC)
3795 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3796 "'");
3797 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3798 Result.assign(CC);
3799 Lex.Lex();
3800 return false;
3801}
3802
3803template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003804bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3805 if (Lex.getKind() == lltok::APSInt)
3806 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3807
3808 if (Lex.getKind() != lltok::EmissionKind)
3809 return TokError("expected emission kind");
3810
3811 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3812 if (!Kind)
3813 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3814 "'");
3815 assert(*Kind <= Result.Max && "Expected valid emission kind");
3816 Result.assign(*Kind);
3817 Lex.Lex();
3818 return false;
3819}
3820
3821template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003822bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003823 DwarfAttEncodingField &Result) {
3824 if (Lex.getKind() == lltok::APSInt)
3825 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3826
3827 if (Lex.getKind() != lltok::DwarfAttEncoding)
3828 return TokError("expected DWARF type attribute encoding");
3829
3830 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3831 if (!Encoding)
3832 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3833 Lex.getStrVal() + "'");
3834 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3835 Result.assign(Encoding);
3836 Lex.Lex();
3837 return false;
3838}
3839
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003840/// DIFlagField
3841/// ::= uint32
3842/// ::= DIFlagVector
3843/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3844template <>
3845bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003846
3847 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003848 auto parseFlag = [&](DINode::DIFlags &Val) {
3849 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3850 uint32_t TempVal = static_cast<uint32_t>(Val);
3851 bool Res = ParseUInt32(TempVal);
3852 Val = static_cast<DINode::DIFlags>(TempVal);
3853 return Res;
3854 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003855
3856 if (Lex.getKind() != lltok::DIFlag)
3857 return TokError("expected debug info flag");
3858
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003859 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003860 if (!Val)
3861 return TokError(Twine("invalid debug info flag flag '") +
3862 Lex.getStrVal() + "'");
3863 Lex.Lex();
3864 return false;
3865 };
3866
3867 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003868 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003869 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003870 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003871 if (parseFlag(Val))
3872 return true;
3873 Combined |= Val;
3874 } while (EatIfPresent(lltok::bar));
3875
3876 Result.assign(Combined);
3877 return false;
3878}
3879
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003880template <>
3881bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003882 MDSignedField &Result) {
3883 if (Lex.getKind() != lltok::APSInt)
3884 return TokError("expected signed integer");
3885
3886 auto &S = Lex.getAPSIntVal();
3887 if (S < Result.Min)
3888 return TokError("value for '" + Name + "' too small, limit is " +
3889 Twine(Result.Min));
3890 if (S > Result.Max)
3891 return TokError("value for '" + Name + "' too large, limit is " +
3892 Twine(Result.Max));
3893 Result.assign(S.getExtValue());
3894 assert(Result.Val >= Result.Min && "Expected value in range");
3895 assert(Result.Val <= Result.Max && "Expected value in range");
3896 Lex.Lex();
3897 return false;
3898}
3899
3900template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003901bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3902 switch (Lex.getKind()) {
3903 default:
3904 return TokError("expected 'true' or 'false'");
3905 case lltok::kw_true:
3906 Result.assign(true);
3907 break;
3908 case lltok::kw_false:
3909 Result.assign(false);
3910 break;
3911 }
3912 Lex.Lex();
3913 return false;
3914}
3915
3916template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003917bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003918 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003919 if (!Result.AllowNull)
3920 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003921 Lex.Lex();
3922 Result.assign(nullptr);
3923 return false;
3924 }
3925
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003926 Metadata *MD;
3927 if (ParseMetadata(MD, nullptr))
3928 return true;
3929
3930 Result.assign(MD);
3931 return false;
3932}
3933
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003934template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00003935bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3936 MDSignedOrMDField &Result) {
3937 // Try to parse a signed int.
3938 if (Lex.getKind() == lltok::APSInt) {
3939 MDSignedField Res = Result.A;
3940 if (!ParseMDField(Loc, Name, Res)) {
3941 Result.assign(Res);
3942 return false;
3943 }
3944 return true;
3945 }
3946
3947 // Otherwise, try to parse as an MDField.
3948 MDField Res = Result.B;
3949 if (!ParseMDField(Loc, Name, Res)) {
3950 Result.assign(Res);
3951 return false;
3952 }
3953
3954 return true;
3955}
3956
3957template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003958bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3959 MDSignedOrUnsignedField &Result) {
3960 if (Lex.getKind() != lltok::APSInt)
3961 return false;
3962
3963 if (Lex.getAPSIntVal().isSigned()) {
3964 MDSignedField Res = Result.A;
3965 if (ParseMDField(Loc, Name, Res))
3966 return true;
3967 Result.assign(Res);
3968 return false;
3969 }
3970
3971 MDUnsignedField Res = Result.B;
3972 if (ParseMDField(Loc, Name, Res))
3973 return true;
3974 Result.assign(Res);
3975 return false;
3976}
3977
3978template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003979bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003980 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003981 std::string S;
3982 if (ParseStringConstant(S))
3983 return true;
3984
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003985 if (!Result.AllowEmpty && S.empty())
3986 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3987
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003988 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003989 return false;
3990}
3991
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003992template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003993bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3994 SmallVector<Metadata *, 4> MDs;
3995 if (ParseMDNodeVector(MDs))
3996 return true;
3997
3998 Result.assign(std::move(MDs));
3999 return false;
4000}
4001
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004002template <>
4003bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4004 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004005 Optional<DIFile::ChecksumKind> CSKind =
4006 DIFile::getChecksumKind(Lex.getStrVal());
4007
4008 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004009 return TokError(
4010 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4011
Scott Linder71603842018-02-12 19:45:54 +00004012 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004013 Lex.Lex();
4014 return false;
4015}
4016
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004017} // end namespace llvm
4018
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004019template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004020bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004021 do {
4022 if (Lex.getKind() != lltok::LabelStr)
4023 return TokError("expected field label here");
4024
4025 if (parseField())
4026 return true;
4027 } while (EatIfPresent(lltok::comma));
4028
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004029 return false;
4030}
4031
4032template <class ParserTy>
4033bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4034 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4035 Lex.Lex();
4036
4037 if (ParseToken(lltok::lparen, "expected '(' here"))
4038 return true;
4039 if (Lex.getKind() != lltok::rparen)
4040 if (ParseMDFieldsImplBody(parseField))
4041 return true;
4042
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004043 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004044 return ParseToken(lltok::rparen, "expected ')' here");
4045}
4046
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004047template <class FieldTy>
4048bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4049 if (Result.Seen)
4050 return TokError("field '" + Name + "' cannot be specified more than once");
4051
4052 LocTy Loc = Lex.getLoc();
4053 Lex.Lex();
4054 return ParseMDField(Loc, Name, Result);
4055}
4056
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004057bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4058 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004059
4060#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004061 if (Lex.getStrVal() == #CLASS) \
4062 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004063#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004064
4065 return TokError("expected metadata type");
4066}
4067
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004068#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4069#define NOP_FIELD(NAME, TYPE, INIT)
4070#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4071 if (!NAME.Seen) \
4072 return Error(ClosingLoc, "missing required field '" #NAME "'");
4073#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004074 if (Lex.getStrVal() == #NAME) \
4075 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004076#define PARSE_MD_FIELDS() \
4077 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4078 do { \
4079 LocTy ClosingLoc; \
4080 if (ParseMDFieldsImpl([&]() -> bool { \
4081 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4082 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4083 }, ClosingLoc)) \
4084 return true; \
4085 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4086 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004087#define GET_OR_DISTINCT(CLASS, ARGS) \
4088 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004089
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004090/// ParseDILocationFields:
4091/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
4092bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004093#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004094 OPTIONAL(line, LineField, ); \
4095 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004096 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004097 OPTIONAL(inlinedAt, MDField, );
4098 PARSE_MD_FIELDS();
4099#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004100
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00004101 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004102 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004103 return false;
4104}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004105
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004106/// ParseGenericDINode:
4107/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4108bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004109#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004110 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004111 OPTIONAL(header, MDStringField, ); \
4112 OPTIONAL(operands, MDFieldList, );
4113 PARSE_MD_FIELDS();
4114#undef VISIT_MD_FIELDS
4115
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004116 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004117 (Context, tag.Val, header.Val, operands.Val));
4118 return false;
4119}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004120
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004121/// ParseDISubrange:
4122/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004123/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004124bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004125#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004126 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004127 OPTIONAL(lowerBound, MDSignedField, );
4128 PARSE_MD_FIELDS();
4129#undef VISIT_MD_FIELDS
4130
Sander de Smalenfdf40912018-01-24 09:56:07 +00004131 if (count.isMDSignedField())
4132 Result = GET_OR_DISTINCT(
4133 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4134 else if (count.isMDField())
4135 Result = GET_OR_DISTINCT(
4136 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4137 else
4138 return true;
4139
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004140 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004141}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004142
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004143/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004144/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004145bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004146#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004147 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004148 REQUIRED(value, MDSignedOrUnsignedField, ); \
4149 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004150 PARSE_MD_FIELDS();
4151#undef VISIT_MD_FIELDS
4152
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004153 if (isUnsigned.Val && value.isMDSignedField())
4154 return TokError("unsigned enumerator with negative value");
4155
4156 int64_t Value = value.isMDSignedField()
4157 ? value.getMDSignedValue()
4158 : static_cast<int64_t>(value.getMDUnsignedValue());
4159 Result =
4160 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4161
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004162 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004163}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004164
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004165/// ParseDIBasicType:
4166/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
4167bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004168#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004169 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004170 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004171 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004172 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004173 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004174 PARSE_MD_FIELDS();
4175#undef VISIT_MD_FIELDS
4176
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004177 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004178 align.Val, encoding.Val));
4179 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004180}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004181
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004182/// ParseDIDerivedType:
4183/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004184/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004185/// align: 32, offset: 0, flags: 0, extraData: !3,
4186/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004187bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004188#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4189 REQUIRED(tag, DwarfTagField, ); \
4190 OPTIONAL(name, MDStringField, ); \
4191 OPTIONAL(file, MDField, ); \
4192 OPTIONAL(line, LineField, ); \
4193 OPTIONAL(scope, MDField, ); \
4194 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004195 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004196 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004197 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004198 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004199 OPTIONAL(extraData, MDField, ); \
4200 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004201 PARSE_MD_FIELDS();
4202#undef VISIT_MD_FIELDS
4203
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004204 Optional<unsigned> DWARFAddressSpace;
4205 if (dwarfAddressSpace.Val != UINT32_MAX)
4206 DWARFAddressSpace = dwarfAddressSpace.Val;
4207
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004208 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004209 (Context, tag.Val, name.Val, file.Val, line.Val,
4210 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004211 offset.Val, DWARFAddressSpace, flags.Val,
4212 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004213 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004214}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004215
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004216bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004217#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4218 REQUIRED(tag, DwarfTagField, ); \
4219 OPTIONAL(name, MDStringField, ); \
4220 OPTIONAL(file, MDField, ); \
4221 OPTIONAL(line, LineField, ); \
4222 OPTIONAL(scope, MDField, ); \
4223 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004224 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004225 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004226 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004227 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004228 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004229 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004230 OPTIONAL(vtableHolder, MDField, ); \
4231 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004232 OPTIONAL(identifier, MDStringField, ); \
4233 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004234 PARSE_MD_FIELDS();
4235#undef VISIT_MD_FIELDS
4236
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004237 // If this has an identifier try to build an ODR type.
4238 if (identifier.Val)
4239 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004240 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4241 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4242 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004243 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004244 Result = CT;
4245 return false;
4246 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004247
4248 // Create a new node, and save it in the context if it belongs in the type
4249 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004250 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004251 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004252 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4253 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004254 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4255 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004256 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004257}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004258
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004259bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004260#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004261 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004262 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004263 REQUIRED(types, MDField, );
4264 PARSE_MD_FIELDS();
4265#undef VISIT_MD_FIELDS
4266
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004267 Result = GET_OR_DISTINCT(DISubroutineType,
4268 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004269 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004270}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004271
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004272/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004273/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004274/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004275/// checksum: "000102030405060708090a0b0c0d0e0f",
4276/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004277bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004278 // The default constructed value for checksumkind is required, but will never
4279 // be used, as the parser checks if the field was actually Seen before using
4280 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004281#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4282 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004283 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004284 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004285 OPTIONAL(checksum, MDStringField, ); \
4286 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004287 PARSE_MD_FIELDS();
4288#undef VISIT_MD_FIELDS
4289
Scott Linder71603842018-02-12 19:45:54 +00004290 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4291 if (checksumkind.Seen && checksum.Seen)
4292 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4293 else if (checksumkind.Seen || checksum.Seen)
4294 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4295
Scott Linder16c7bda2018-02-23 23:01:06 +00004296 Optional<MDString *> OptSource;
4297 if (source.Seen)
4298 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004299 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004300 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004301 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004302}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004303
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004304/// ParseDICompileUnit:
4305/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004306/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004307/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004308/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004309/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004310bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004311 if (!IsDistinct)
4312 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4313
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4315 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004316 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004317 OPTIONAL(producer, MDStringField, ); \
4318 OPTIONAL(isOptimized, MDBoolField, ); \
4319 OPTIONAL(flags, MDStringField, ); \
4320 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4321 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004322 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004323 OPTIONAL(enums, MDField, ); \
4324 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004325 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004326 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004327 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004328 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004329 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004330 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4331 OPTIONAL(gnuPubnames, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004332 PARSE_MD_FIELDS();
4333#undef VISIT_MD_FIELDS
4334
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004335 Result = DICompileUnit::getDistinct(
4336 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4337 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004338 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004339 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004340 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004341}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004342
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004343/// ParseDISubprogram:
4344/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004345/// file: !1, line: 7, type: !2, isLocal: false,
4346/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004347/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004348/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004349/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004350/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004351bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004352 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004353#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4354 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004355 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004356 OPTIONAL(linkageName, MDStringField, ); \
4357 OPTIONAL(file, MDField, ); \
4358 OPTIONAL(line, LineField, ); \
4359 OPTIONAL(type, MDField, ); \
4360 OPTIONAL(isLocal, MDBoolField, ); \
4361 OPTIONAL(isDefinition, MDBoolField, (true)); \
4362 OPTIONAL(scopeLine, LineField, ); \
4363 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004364 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004365 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004366 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004367 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004368 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004369 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004370 OPTIONAL(templateParams, MDField, ); \
4371 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004372 OPTIONAL(variables, MDField, ); \
4373 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004374 PARSE_MD_FIELDS();
4375#undef VISIT_MD_FIELDS
4376
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004377 if (isDefinition.Val && !IsDistinct)
4378 return Lex.Error(
4379 Loc,
4380 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4381
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004382 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004383 DISubprogram,
4384 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4385 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4386 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4387 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4388 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004389 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004390}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004391
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004392/// ParseDILexicalBlock:
4393/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4394bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004395#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004396 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004397 OPTIONAL(file, MDField, ); \
4398 OPTIONAL(line, LineField, ); \
4399 OPTIONAL(column, ColumnField, );
4400 PARSE_MD_FIELDS();
4401#undef VISIT_MD_FIELDS
4402
4403 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004404 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004405 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004406}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004407
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004408/// ParseDILexicalBlockFile:
4409/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4410bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004411#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004412 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004413 OPTIONAL(file, MDField, ); \
4414 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4415 PARSE_MD_FIELDS();
4416#undef VISIT_MD_FIELDS
4417
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004418 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004419 (Context, scope.Val, file.Val, discriminator.Val));
4420 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004421}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004422
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004423/// ParseDINamespace:
4424/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4425bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004426#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4427 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004428 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004429 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004430 PARSE_MD_FIELDS();
4431#undef VISIT_MD_FIELDS
4432
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004433 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004434 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004435 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004436}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004437
Amjad Abouda9bcf162015-12-10 12:56:35 +00004438/// ParseDIMacro:
4439/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4440bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4441#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4442 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004443 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004444 REQUIRED(name, MDStringField, ); \
4445 OPTIONAL(value, MDStringField, );
4446 PARSE_MD_FIELDS();
4447#undef VISIT_MD_FIELDS
4448
4449 Result = GET_OR_DISTINCT(DIMacro,
4450 (Context, type.Val, line.Val, name.Val, value.Val));
4451 return false;
4452}
4453
4454/// ParseDIMacroFile:
4455/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4456bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4457#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4458 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004459 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004460 REQUIRED(file, MDField, ); \
4461 OPTIONAL(nodes, MDField, );
4462 PARSE_MD_FIELDS();
4463#undef VISIT_MD_FIELDS
4464
4465 Result = GET_OR_DISTINCT(DIMacroFile,
4466 (Context, type.Val, line.Val, file.Val, nodes.Val));
4467 return false;
4468}
4469
Adrian Prantlab1243f2015-06-29 23:03:47 +00004470/// ParseDIModule:
4471/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4472/// includePath: "/usr/include", isysroot: "/")
4473bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4474#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4475 REQUIRED(scope, MDField, ); \
4476 REQUIRED(name, MDStringField, ); \
4477 OPTIONAL(configMacros, MDStringField, ); \
4478 OPTIONAL(includePath, MDStringField, ); \
4479 OPTIONAL(isysroot, MDStringField, );
4480 PARSE_MD_FIELDS();
4481#undef VISIT_MD_FIELDS
4482
4483 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4484 configMacros.Val, includePath.Val, isysroot.Val));
4485 return false;
4486}
4487
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004488/// ParseDITemplateTypeParameter:
4489/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4490bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004491#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004492 OPTIONAL(name, MDStringField, ); \
4493 REQUIRED(type, MDField, );
4494 PARSE_MD_FIELDS();
4495#undef VISIT_MD_FIELDS
4496
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004497 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004498 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004499 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004500}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004501
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004502/// ParseDITemplateValueParameter:
4503/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004504/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004505bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004506#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004507 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004508 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004509 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004510 REQUIRED(value, MDField, );
4511 PARSE_MD_FIELDS();
4512#undef VISIT_MD_FIELDS
4513
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004514 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004515 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004516 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004517}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004518
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004519/// ParseDIGlobalVariable:
4520/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004521/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004522/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004523bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004524#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004525 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004526 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004527 OPTIONAL(linkageName, MDStringField, ); \
4528 OPTIONAL(file, MDField, ); \
4529 OPTIONAL(line, LineField, ); \
4530 OPTIONAL(type, MDField, ); \
4531 OPTIONAL(isLocal, MDBoolField, ); \
4532 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004533 OPTIONAL(declaration, MDField, ); \
4534 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004535 PARSE_MD_FIELDS();
4536#undef VISIT_MD_FIELDS
4537
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004538 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004539 (Context, scope.Val, name.Val, linkageName.Val,
4540 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004541 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004542 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004543}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004544
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004545/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004546/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004547/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4548/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004549/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004550/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4551/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004552bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004553#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004554 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004555 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004556 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004557 OPTIONAL(file, MDField, ); \
4558 OPTIONAL(line, LineField, ); \
4559 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004560 OPTIONAL(flags, DIFlagField, ); \
4561 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004562 PARSE_MD_FIELDS();
4563#undef VISIT_MD_FIELDS
4564
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004565 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004566 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004567 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004568 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004569}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004570
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004571/// ParseDIExpression:
4572/// ::= !DIExpression(0, 7, -1)
4573bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004574 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4575 Lex.Lex();
4576
4577 if (ParseToken(lltok::lparen, "expected '(' here"))
4578 return true;
4579
4580 SmallVector<uint64_t, 8> Elements;
4581 if (Lex.getKind() != lltok::rparen)
4582 do {
4583 if (Lex.getKind() == lltok::DwarfOp) {
4584 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4585 Lex.Lex();
4586 Elements.push_back(Op);
4587 continue;
4588 }
4589 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4590 }
4591
4592 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4593 return TokError("expected unsigned integer");
4594
4595 auto &U = Lex.getAPSIntVal();
4596 if (U.ugt(UINT64_MAX))
4597 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4598 Elements.push_back(U.getZExtValue());
4599 Lex.Lex();
4600 } while (EatIfPresent(lltok::comma));
4601
4602 if (ParseToken(lltok::rparen, "expected ')' here"))
4603 return true;
4604
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004605 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004606 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004607}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004608
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004609/// ParseDIGlobalVariableExpression:
4610/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4611bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4612 bool IsDistinct) {
4613#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4614 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004615 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004616 PARSE_MD_FIELDS();
4617#undef VISIT_MD_FIELDS
4618
4619 Result =
4620 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4621 return false;
4622}
4623
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004624/// ParseDIObjCProperty:
4625/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004626/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004627bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004628#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004629 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004630 OPTIONAL(file, MDField, ); \
4631 OPTIONAL(line, LineField, ); \
4632 OPTIONAL(setter, MDStringField, ); \
4633 OPTIONAL(getter, MDStringField, ); \
4634 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4635 OPTIONAL(type, MDField, );
4636 PARSE_MD_FIELDS();
4637#undef VISIT_MD_FIELDS
4638
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004639 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004640 (Context, name.Val, file.Val, line.Val, setter.Val,
4641 getter.Val, attributes.Val, type.Val));
4642 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004643}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004644
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004645/// ParseDIImportedEntity:
4646/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004647/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004648bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004649#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4650 REQUIRED(tag, DwarfTagField, ); \
4651 REQUIRED(scope, MDField, ); \
4652 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004653 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004654 OPTIONAL(line, LineField, ); \
4655 OPTIONAL(name, MDStringField, );
4656 PARSE_MD_FIELDS();
4657#undef VISIT_MD_FIELDS
4658
Adrian Prantld63bfd22017-07-19 00:09:54 +00004659 Result = GET_OR_DISTINCT(
4660 DIImportedEntity,
4661 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004662 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004663}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004664
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004665#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004666#undef NOP_FIELD
4667#undef REQUIRE_FIELD
4668#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004669
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004670/// ParseMetadataAsValue
4671/// ::= metadata i32 %local
4672/// ::= metadata i32 @global
4673/// ::= metadata i32 7
4674/// ::= metadata !0
4675/// ::= metadata !{...}
4676/// ::= metadata !"string"
4677bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4678 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004679 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004680 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004681 return true;
4682
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004683 V = MetadataAsValue::get(Context, MD);
4684 return false;
4685}
4686
4687/// ParseValueAsMetadata
4688/// ::= i32 %local
4689/// ::= i32 @global
4690/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004691bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4692 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004693 Type *Ty;
4694 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004695 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004696 return true;
4697 if (Ty->isMetadataTy())
4698 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4699
4700 Value *V;
4701 if (ParseValue(Ty, V, PFS))
4702 return true;
4703
4704 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004705 return false;
4706}
4707
4708/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004709/// ::= i32 %local
4710/// ::= i32 @global
4711/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004712/// ::= !42
4713/// ::= !{...}
4714/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004715/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004716bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004717 if (Lex.getKind() == lltok::MetadataVar) {
4718 MDNode *N;
4719 if (ParseSpecializedMDNode(N))
4720 return true;
4721 MD = N;
4722 return false;
4723 }
4724
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004725 // ValueAsMetadata:
4726 // <type> <value>
4727 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004728 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004729
4730 // '!'.
4731 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4732 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004733
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004734 // MDString:
4735 // ::= '!' STRINGCONSTANT
4736 if (Lex.getKind() == lltok::StringConstant) {
4737 MDString *S;
4738 if (ParseMDString(S))
4739 return true;
4740 MD = S;
4741 return false;
4742 }
4743
Dan Gohman8939ba332010-07-14 18:26:50 +00004744 // MDNode:
4745 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004746 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004747 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004748 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004749 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004750 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004751 return false;
4752}
4753
Victor Hernandez9d75c962010-01-11 22:31:58 +00004754//===----------------------------------------------------------------------===//
4755// Function Parsing.
4756//===----------------------------------------------------------------------===//
4757
Chris Lattner229907c2011-07-18 04:54:35 +00004758bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004759 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004760 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004761 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004762
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004764 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004765 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004766 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004767 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004768 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004769 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004770 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004771 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004772 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004773 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004774 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004775 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4776 (ID.UIntVal >> 1) & 1,
4777 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004778 return false;
4779 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004780 case ValID::t_GlobalName:
4781 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004782 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004783 case ValID::t_GlobalID:
4784 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004785 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004786 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004787 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004789 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004790 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791 return false;
4792 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004793 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4795 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004796
Dan Gohman518cda42011-12-17 00:04:22 +00004797 // The lexer has no type info, so builds all half, float, and double FP
4798 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004799 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004800 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004801 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004802 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004803 &Ignored);
4804 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004805 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004806 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004808 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004809
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004810 if (V->getType() != Ty)
4811 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004812 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004813
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 return false;
4815 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004816 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004818 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004819 return false;
4820 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004821 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004822 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004823 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004824 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004825 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004826 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004827 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004828 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004829 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004830 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004831 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004832 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004833 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004834 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004835 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004836 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004837 case ValID::t_None:
4838 if (!Ty->isTokenTy())
4839 return Error(ID.Loc, "invalid type for none constant");
4840 V = Constant::getNullValue(Ty);
4841 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004843 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004844 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004845
Chris Lattnerac161bf2009-01-02 07:01:27 +00004846 V = ID.ConstantVal;
4847 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004848 case ValID::t_ConstantStruct:
4849 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004850 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004851 if (ST->getNumElements() != ID.UIntVal)
4852 return Error(ID.Loc,
4853 "initializer with struct type has wrong # elements");
4854 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4855 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004856
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004857 // Verify that the elements are compatible with the structtype.
4858 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4859 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4860 return Error(ID.Loc, "element " + Twine(i) +
4861 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004862
David Blaikieadbda4b2015-08-03 20:08:41 +00004863 V = ConstantStruct::get(
4864 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004865 } else
4866 return Error(ID.Loc, "constant expression type mismatch");
4867 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004868 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004869 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004870}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004871
Alex Lorenzd2255952015-07-17 22:07:03 +00004872bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4873 C = nullptr;
4874 ValID ID;
4875 auto Loc = Lex.getLoc();
4876 if (ParseValID(ID, /*PFS=*/nullptr))
4877 return true;
4878 switch (ID.Kind) {
4879 case ValID::t_APSInt:
4880 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004881 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004882 case ValID::t_Constant:
4883 case ValID::t_ConstantStruct:
4884 case ValID::t_PackedConstantStruct: {
4885 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004886 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00004887 return true;
4888 assert(isa<Constant>(V) && "Expected a constant value");
4889 C = cast<Constant>(V);
4890 return false;
4891 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004892 case ValID::t_Null:
4893 C = Constant::getNullValue(Ty);
4894 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004895 default:
4896 return Error(Loc, "expected a constant value");
4897 }
4898}
4899
David Majnemer8a1c45d2015-12-12 05:38:55 +00004900bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004901 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004902 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004903 return ParseValID(ID, PFS) ||
4904 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905}
4906
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004907bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004908 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004909 return ParseType(Ty) ||
4910 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004911}
4912
Chris Lattner3ed871f2009-10-27 19:13:16 +00004913bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4914 PerFunctionState &PFS) {
4915 Value *V;
4916 Loc = Lex.getLoc();
4917 if (ParseTypeAndValue(V, PFS)) return true;
4918 if (!isa<BasicBlock>(V))
4919 return Error(Loc, "expected a basic block");
4920 BB = cast<BasicBlock>(V);
4921 return false;
4922}
4923
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00004925/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
4926/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
4927/// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
4928/// OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004929bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4930 // Parse the linkage.
4931 LocTy LinkageLoc = Lex.getLoc();
4932 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004933 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004934 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00004935 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00004936 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004937 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004938 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004939 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004940 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00004941 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
4942 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004943 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004944 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004945 return true;
4946
4947 // Verify that the linkage is ok.
4948 switch ((GlobalValue::LinkageTypes)Linkage) {
4949 case GlobalValue::ExternalLinkage:
4950 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004951 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004952 if (isDefine)
4953 return Error(LinkageLoc, "invalid linkage for function definition");
4954 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004955 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004957 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004958 case GlobalValue::LinkOnceAnyLinkage:
4959 case GlobalValue::LinkOnceODRLinkage:
4960 case GlobalValue::WeakAnyLinkage:
4961 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 if (!isDefine)
4963 return Error(LinkageLoc, "invalid linkage for function declaration");
4964 break;
4965 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004966 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004967 return Error(LinkageLoc, "invalid function linkage type");
4968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004969
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004970 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4971 return Error(LinkageLoc,
4972 "symbol with local linkage must have default visibility");
4973
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004974 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004976
Chris Lattnerac161bf2009-01-02 07:01:27 +00004977 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004978
4979 std::string FunctionName;
4980 if (Lex.getKind() == lltok::GlobalVar) {
4981 FunctionName = Lex.getStrVal();
4982 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4983 unsigned NameID = Lex.getUIntVal();
4984
4985 if (NameID != NumberedVals.size())
4986 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004987 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004988 } else {
4989 return TokError("expected function name");
4990 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004991
Chris Lattner3822f632009-01-02 08:05:26 +00004992 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004993
Chris Lattner3822f632009-01-02 08:05:26 +00004994 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004996
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004997 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004999 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005000 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005001 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005002 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005004 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005005 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Craig Topper2617dcc2014-04-15 06:32:26 +00005006 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005007 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005008 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005009 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005010
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005011 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005012 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005013 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005014 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005015 (EatIfPresent(lltok::kw_section) &&
5016 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005017 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005018 ParseOptionalAlignment(Alignment) ||
5019 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005020 ParseStringConstant(GC)) ||
5021 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005022 ParseGlobalTypeAndValue(Prefix)) ||
5023 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005024 ParseGlobalTypeAndValue(Prologue)) ||
5025 (EatIfPresent(lltok::kw_personality) &&
5026 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005027 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028
Michael Gottesman41748d72013-06-27 00:25:01 +00005029 if (FuncAttrs.contains(Attribute::Builtin))
5030 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005031
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005033 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005034 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005035 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005037
Chris Lattnerac161bf2009-01-02 07:01:27 +00005038 // Okay, if we got here, the function is syntactically valid. Convert types
5039 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005040 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005041 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005042
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005044 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005045 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 }
5047
Reid Kleckner7f720332017-04-13 00:58:09 +00005048 AttributeList PAL =
5049 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5050 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005051
Bill Wendling749a43d2012-12-30 13:50:49 +00005052 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005053 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5054
Chris Lattner229907c2011-07-18 04:54:35 +00005055 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005056 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00005057 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005058
Craig Topper2617dcc2014-04-15 06:32:26 +00005059 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 if (!FunctionName.empty()) {
5061 // If this was a definition of a forward reference, remove the definition
5062 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005063 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 if (FRVI != ForwardRefVals.end()) {
5065 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005066 if (!Fn)
5067 return Error(FRVI->second.second, "invalid forward reference to "
5068 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005069 if (Fn->getType() != PFT)
5070 return Error(FRVI->second.second, "invalid forward reference to "
5071 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005072
Chris Lattnerac161bf2009-01-02 07:01:27 +00005073 ForwardRefVals.erase(FRVI);
5074 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005075 // Reject redefinitions.
5076 return Error(NameLoc, "invalid redefinition of function '" +
5077 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005078 } else if (M->getNamedValue(FunctionName)) {
5079 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Dan Gohman399d6ae2009-08-29 23:37:49 +00005082 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 // If this is a definition of a forward referenced function, make sure the
5084 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005085 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 if (I != ForwardRefValIDs.end()) {
5087 Fn = cast<Function>(I->second.first);
5088 if (Fn->getType() != PFT)
5089 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005090 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005091 ForwardRefValIDs.erase(I);
5092 }
5093 }
5094
Craig Topper2617dcc2014-04-15 06:32:26 +00005095 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005096 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
5097 else // Move the forward-reference to the correct spot in the module.
5098 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5099
5100 if (FunctionName.empty())
5101 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005102
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005104 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005105 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005106 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107 Fn->setCallingConv(CC);
5108 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005109 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005110 Fn->setAlignment(Alignment);
5111 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005112 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005113 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005114 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005115 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005116 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005117 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005118
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 // Add all of the arguments we parsed to the function.
5120 Function::arg_iterator ArgIt = Fn->arg_begin();
5121 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5122 // If the argument has a name, insert it into the argument symbol table.
5123 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005124
Chris Lattnerac161bf2009-01-02 07:01:27 +00005125 // Set the name, if it conflicted, it will be auto-renamed.
5126 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005127
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005128 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5130 ArgList[i].Name + "'");
5131 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005132
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005133 if (isDefine)
5134 return false;
5135
Robin Morisset039781e2014-08-29 21:53:01 +00005136 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005137 ValID ID;
5138 if (FunctionName.empty()) {
5139 ID.Kind = ValID::t_GlobalID;
5140 ID.UIntVal = NumberedVals.size() - 1;
5141 } else {
5142 ID.Kind = ValID::t_GlobalName;
5143 ID.StrVal = FunctionName;
5144 }
5145 auto Blocks = ForwardRefBlockAddresses.find(ID);
5146 if (Blocks != ForwardRefBlockAddresses.end())
5147 return Error(Blocks->first.Loc,
5148 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149 return false;
5150}
5151
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005152bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5153 ValID ID;
5154 if (FunctionNumber == -1) {
5155 ID.Kind = ValID::t_GlobalName;
5156 ID.StrVal = F.getName();
5157 } else {
5158 ID.Kind = ValID::t_GlobalID;
5159 ID.UIntVal = FunctionNumber;
5160 }
5161
5162 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5163 if (Blocks == P.ForwardRefBlockAddresses.end())
5164 return false;
5165
5166 for (const auto &I : Blocks->second) {
5167 const ValID &BBID = I.first;
5168 GlobalValue *GV = I.second;
5169
5170 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5171 "Expected local id or name");
5172 BasicBlock *BB;
5173 if (BBID.Kind == ValID::t_LocalName)
5174 BB = GetBB(BBID.StrVal, BBID.Loc);
5175 else
5176 BB = GetBB(BBID.UIntVal, BBID.Loc);
5177 if (!BB)
5178 return P.Error(BBID.Loc, "referenced value is not a basic block");
5179
5180 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5181 GV->eraseFromParent();
5182 }
5183
5184 P.ForwardRefBlockAddresses.erase(Blocks);
5185 return false;
5186}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187
5188/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005189/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005191 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 return TokError("expected '{' in function body");
5193 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005194
Chris Lattner3432c622009-10-28 03:39:23 +00005195 int FunctionNumber = -1;
5196 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005197
Chris Lattner3432c622009-10-28 03:39:23 +00005198 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005199
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005200 // Resolve block addresses and allow basic blocks to be forward-declared
5201 // within this function.
5202 if (PFS.resolveForwardRefBlockAddresses())
5203 return true;
5204 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5205
Chris Lattnerbbddd962010-01-09 19:20:07 +00005206 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005207 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005208 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005209
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005210 while (Lex.getKind() != lltok::rbrace &&
5211 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005212 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005213
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005214 while (Lex.getKind() != lltok::rbrace)
5215 if (ParseUseListOrder(&PFS))
5216 return true;
5217
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 // Eat the }.
5219 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005220
Chris Lattnerac161bf2009-01-02 07:01:27 +00005221 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005222 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005223}
5224
5225/// ParseBasicBlock
5226/// ::= LabelStr? Instruction*
5227bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5228 // If this basic block starts out with a name, remember it.
5229 std::string Name;
5230 LocTy NameLoc = Lex.getLoc();
5231 if (Lex.getKind() == lltok::LabelStr) {
5232 Name = Lex.getStrVal();
5233 Lex.Lex();
5234 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005235
Chris Lattnerac161bf2009-01-02 07:01:27 +00005236 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005237 if (!BB)
5238 return Error(NameLoc,
5239 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005240
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005242
Chris Lattnerac161bf2009-01-02 07:01:27 +00005243 // Parse the instructions in this block until we get a terminator.
5244 Instruction *Inst;
5245 do {
5246 // This instruction may have three possibilities for a name: a) none
5247 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5248 LocTy NameLoc = Lex.getLoc();
5249 int NameID = -1;
5250 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005251
Chris Lattnerac161bf2009-01-02 07:01:27 +00005252 if (Lex.getKind() == lltok::LocalVarID) {
5253 NameID = Lex.getUIntVal();
5254 Lex.Lex();
5255 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5256 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005257 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005258 NameStr = Lex.getStrVal();
5259 Lex.Lex();
5260 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5261 return true;
5262 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005263
Chris Lattner77b89dc2009-12-30 05:23:43 +00005264 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005265 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005266 case InstError: return true;
5267 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005268 BB->getInstList().push_back(Inst);
5269
Chris Lattner77b89dc2009-12-30 05:23:43 +00005270 // With a normal result, we check to see if the instruction is followed by
5271 // a comma and metadata.
5272 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005273 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005274 return true;
5275 break;
5276 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005277 BB->getInstList().push_back(Inst);
5278
Chris Lattner77b89dc2009-12-30 05:23:43 +00005279 // If the instruction parser ate an extra comma at the end of it, it
5280 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005281 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005282 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005283 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005284 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005285
Chris Lattnerac161bf2009-01-02 07:01:27 +00005286 // Set the name on the instruction.
5287 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5288 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005289
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 return false;
5291}
5292
5293//===----------------------------------------------------------------------===//
5294// Instruction Parsing.
5295//===----------------------------------------------------------------------===//
5296
5297/// ParseInstruction - Parse one of the many different instructions.
5298///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005299int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5300 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005301 lltok::Kind Token = Lex.getKind();
5302 if (Token == lltok::Eof)
5303 return TokError("found end of file when expecting more instructions");
5304 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005305 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005306 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005307
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308 switch (Token) {
5309 default: return Error(Loc, "expected instruction opcode");
5310 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005311 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005312 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5313 case lltok::kw_br: return ParseBr(Inst, PFS);
5314 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005315 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005317 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005318 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5319 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005320 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5321 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005322 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005323 // Binary Operators.
5324 case lltok::kw_add:
5325 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005326 case lltok::kw_mul:
5327 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005328 bool NUW = EatIfPresent(lltok::kw_nuw);
5329 bool NSW = EatIfPresent(lltok::kw_nsw);
5330 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005331
Chris Lattnera676c0f2011-02-07 16:40:21 +00005332 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005333
Chris Lattnera676c0f2011-02-07 16:40:21 +00005334 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5335 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5336 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005337 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005338 case lltok::kw_fadd:
5339 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005340 case lltok::kw_fmul:
5341 case lltok::kw_fdiv:
5342 case lltok::kw_frem: {
5343 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5344 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5345 if (Res != 0)
5346 return Res;
5347 if (FMF.any())
5348 Inst->setFastMathFlags(FMF);
5349 return 0;
5350 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005351
Chris Lattner35315d02011-02-06 21:44:57 +00005352 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005353 case lltok::kw_udiv:
5354 case lltok::kw_lshr:
5355 case lltok::kw_ashr: {
5356 bool Exact = EatIfPresent(lltok::kw_exact);
5357
5358 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5359 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5360 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005361 }
5362
Chris Lattnerac161bf2009-01-02 07:01:27 +00005363 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005364 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005365 case lltok::kw_and:
5366 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005367 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005368 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5369 case lltok::kw_fcmp: {
5370 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5371 int Res = ParseCompare(Inst, PFS, KeywordVal);
5372 if (Res != 0)
5373 return Res;
5374 if (FMF.any())
5375 Inst->setFastMathFlags(FMF);
5376 return 0;
5377 }
5378
Chris Lattnerac161bf2009-01-02 07:01:27 +00005379 // Casts.
5380 case lltok::kw_trunc:
5381 case lltok::kw_zext:
5382 case lltok::kw_sext:
5383 case lltok::kw_fptrunc:
5384 case lltok::kw_fpext:
5385 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005386 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 case lltok::kw_uitofp:
5388 case lltok::kw_sitofp:
5389 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005390 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005391 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005392 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393 // Other.
5394 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005395 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005396 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5397 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5398 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5399 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005400 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005401 // Call.
5402 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5403 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5404 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005405 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005406 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005407 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005408 case lltok::kw_load: return ParseLoad(Inst, PFS);
5409 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005410 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5411 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005412 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005413 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5414 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5415 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5416 }
5417}
5418
5419/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5420bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005421 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005422 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005423 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005424 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5425 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5426 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5427 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5428 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5429 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5430 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5431 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5432 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5433 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5434 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5435 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5436 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5437 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5438 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5439 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5440 }
5441 } else {
5442 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005443 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005444 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5445 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5446 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5447 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5448 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5449 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5450 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5451 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5452 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5453 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5454 }
5455 }
5456 Lex.Lex();
5457 return false;
5458}
5459
5460//===----------------------------------------------------------------------===//
5461// Terminator Instructions.
5462//===----------------------------------------------------------------------===//
5463
5464/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005465/// ::= 'ret' void (',' !dbg, !1)*
5466/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005467bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005468 PerFunctionState &PFS) {
5469 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005470 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005471 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005472
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005473 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005474
Chris Lattnerfdd87902009-10-05 05:54:46 +00005475 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005476 if (!ResType->isVoidTy())
5477 return Error(TypeLoc, "value doesn't match function result type '" +
5478 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005479
Owen Anderson55f1c092009-08-13 21:58:54 +00005480 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005481 return false;
5482 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005483
Chris Lattnerac161bf2009-01-02 07:01:27 +00005484 Value *RV;
5485 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005486
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005487 if (ResType != RV->getType())
5488 return Error(TypeLoc, "value doesn't match function result type '" +
5489 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005490
Owen Anderson55f1c092009-08-13 21:58:54 +00005491 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005492 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005493}
5494
Chris Lattnerac161bf2009-01-02 07:01:27 +00005495/// ParseBr
5496/// ::= 'br' TypeAndValue
5497/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5498bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5499 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005500 Value *Op0;
5501 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005502 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005503
Chris Lattnerac161bf2009-01-02 07:01:27 +00005504 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5505 Inst = BranchInst::Create(BB);
5506 return false;
5507 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005508
Owen Anderson55f1c092009-08-13 21:58:54 +00005509 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005510 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005511
Chris Lattnerac161bf2009-01-02 07:01:27 +00005512 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005513 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005514 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005515 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005516 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005517
Chris Lattner3ed871f2009-10-27 19:13:16 +00005518 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005519 return false;
5520}
5521
5522/// ParseSwitch
5523/// Instruction
5524/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5525/// JumpTable
5526/// ::= (TypeAndValue ',' TypeAndValue)*
5527bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5528 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005529 Value *Cond;
5530 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005531 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5532 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005533 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005534 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5535 return true;
5536
Duncan Sands19d0b472010-02-16 11:11:14 +00005537 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005538 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005539
Chris Lattnerac161bf2009-01-02 07:01:27 +00005540 // Parse the jump table pairs.
5541 SmallPtrSet<Value*, 32> SeenCases;
5542 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5543 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005544 Value *Constant;
5545 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005546
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5548 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005549 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005550 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005551
David Blaikie70573dc2014-11-19 07:49:26 +00005552 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 return Error(CondLoc, "duplicate case value in switch");
5554 if (!isa<ConstantInt>(Constant))
5555 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005556
Chris Lattner3ed871f2009-10-27 19:13:16 +00005557 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005559
Chris Lattnerac161bf2009-01-02 07:01:27 +00005560 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005561
Chris Lattner3ed871f2009-10-27 19:13:16 +00005562 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005563 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5564 SI->addCase(Table[i].first, Table[i].second);
5565 Inst = SI;
5566 return false;
5567}
5568
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005569/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005570/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005571/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5572bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005573 LocTy AddrLoc;
5574 Value *Address;
5575 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005576 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5577 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005578 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005579
Duncan Sands19d0b472010-02-16 11:11:14 +00005580 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005581 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005582
Chris Lattner3ed871f2009-10-27 19:13:16 +00005583 // Parse the destination list.
5584 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005585
Chris Lattner3ed871f2009-10-27 19:13:16 +00005586 if (Lex.getKind() != lltok::rsquare) {
5587 BasicBlock *DestBB;
5588 if (ParseTypeAndBasicBlock(DestBB, PFS))
5589 return true;
5590 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005591
Chris Lattner3ed871f2009-10-27 19:13:16 +00005592 while (EatIfPresent(lltok::comma)) {
5593 if (ParseTypeAndBasicBlock(DestBB, PFS))
5594 return true;
5595 DestList.push_back(DestBB);
5596 }
5597 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005598
Chris Lattner3ed871f2009-10-27 19:13:16 +00005599 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5600 return true;
5601
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005602 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005603 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5604 IBI->addDestination(DestList[i]);
5605 Inst = IBI;
5606 return false;
5607}
5608
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609/// ParseInvoke
5610/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5611/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5612bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5613 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005614 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005615 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005616 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005617 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005618 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619 LocTy RetTypeLoc;
5620 ValID CalleeID;
5621 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005622 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005623
Chris Lattner3ed871f2009-10-27 19:13:16 +00005624 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005625 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005626 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005627 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005628 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5629 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005630 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005631 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005632 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005633 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005634 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005635 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005636
Chris Lattnerac161bf2009-01-02 07:01:27 +00005637 // If RetType is a non-function pointer type, then this is the short syntax
5638 // for the call, which means that RetType is just the return type. Infer the
5639 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005640 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5641 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005642 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005643 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005644 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5645 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005646
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647 if (!FunctionType::isValidReturnType(RetType))
5648 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005649
Owen Anderson4056ca92009-07-29 22:17:13 +00005650 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005651 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005652
David Blaikie41ba2b42015-07-27 23:32:19 +00005653 CalleeID.FTy = Ty;
5654
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655 // Look up the callee.
5656 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005657 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
5658 /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005659 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005660
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005661 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005662 SmallVector<Value *, 8> Args;
5663 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005664
Chris Lattnerac161bf2009-01-02 07:01:27 +00005665 // Loop through FunctionType's arguments and ensure they are specified
5666 // correctly. Also, gather any parameter attributes.
5667 FunctionType::param_iterator I = Ty->param_begin();
5668 FunctionType::param_iterator E = Ty->param_end();
5669 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005670 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005671 if (I != E) {
5672 ExpectedTy = *I++;
5673 } else if (!Ty->isVarArg()) {
5674 return Error(ArgList[i].Loc, "too many arguments specified");
5675 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005676
Chris Lattnerac161bf2009-01-02 07:01:27 +00005677 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5678 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005679 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005680 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005681 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005682 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005683
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 if (I != E)
5685 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005686
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005687 if (FnAttrs.hasAlignmentAttr())
5688 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005689
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005690 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005691 AttributeList PAL =
5692 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5693 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005694
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005695 InvokeInst *II =
5696 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697 II->setCallingConv(CC);
5698 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005699 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 Inst = II;
5701 return false;
5702}
5703
Bill Wendlingf891bf82011-07-31 06:30:59 +00005704/// ParseResume
5705/// ::= 'resume' TypeAndValue
5706bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5707 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005708 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5709 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005710
Bill Wendlingf891bf82011-07-31 06:30:59 +00005711 ResumeInst *RI = ResumeInst::Create(Exn);
5712 Inst = RI;
5713 return false;
5714}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715
David Majnemer654e1302015-07-31 17:58:14 +00005716bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5717 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005718 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005719 return true;
5720
5721 while (Lex.getKind() != lltok::rsquare) {
5722 // If this isn't the first argument, we need a comma.
5723 if (!Args.empty() &&
5724 ParseToken(lltok::comma, "expected ',' in argument list"))
5725 return true;
5726
5727 // Parse the argument.
5728 LocTy ArgLoc;
5729 Type *ArgTy = nullptr;
5730 if (ParseType(ArgTy, ArgLoc))
5731 return true;
5732
5733 Value *V;
5734 if (ArgTy->isMetadataTy()) {
5735 if (ParseMetadataAsValue(V, PFS))
5736 return true;
5737 } else {
5738 if (ParseValue(ArgTy, V, PFS))
5739 return true;
5740 }
5741 Args.push_back(V);
5742 }
5743
5744 Lex.Lex(); // Lex the ']'.
5745 return false;
5746}
5747
5748/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005749/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005750bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005751 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005752
David Majnemer8a1c45d2015-12-12 05:38:55 +00005753 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5754 return true;
5755
5756 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005757 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005758
5759 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5760 return true;
5761
5762 BasicBlock *UnwindBB = nullptr;
5763 if (Lex.getKind() == lltok::kw_to) {
5764 Lex.Lex();
5765 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5766 return true;
5767 } else {
5768 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5769 return true;
5770 }
5771 }
5772
David Majnemer8a1c45d2015-12-12 05:38:55 +00005773 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005774 return false;
5775}
5776
5777/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005778/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005779bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005780 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005781
David Majnemer8a1c45d2015-12-12 05:38:55 +00005782 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5783 return true;
5784
5785 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005786 return true;
5787
David Majnemer0bc0eef2015-08-15 02:46:08 +00005788 BasicBlock *BB;
5789 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5790 ParseTypeAndBasicBlock(BB, PFS))
5791 return true;
5792
David Majnemer8a1c45d2015-12-12 05:38:55 +00005793 Inst = CatchReturnInst::Create(CatchPad, BB);
5794 return false;
5795}
5796
5797/// ParseCatchSwitch
5798/// ::= 'catchswitch' within Parent
5799bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5800 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005801
5802 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5803 return true;
5804
5805 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5806 Lex.getKind() != lltok::LocalVarID)
5807 return TokError("expected scope value for catchswitch");
5808
5809 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5810 return true;
5811
5812 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5813 return true;
5814
5815 SmallVector<BasicBlock *, 32> Table;
5816 do {
5817 BasicBlock *DestBB;
5818 if (ParseTypeAndBasicBlock(DestBB, PFS))
5819 return true;
5820 Table.push_back(DestBB);
5821 } while (EatIfPresent(lltok::comma));
5822
5823 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5824 return true;
5825
5826 if (ParseToken(lltok::kw_unwind,
5827 "expected 'unwind' after catchswitch scope"))
5828 return true;
5829
5830 BasicBlock *UnwindBB = nullptr;
5831 if (EatIfPresent(lltok::kw_to)) {
5832 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5833 return true;
5834 } else {
5835 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5836 return true;
5837 }
5838
5839 auto *CatchSwitch =
5840 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5841 for (BasicBlock *DestBB : Table)
5842 CatchSwitch->addHandler(DestBB);
5843 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005844 return false;
5845}
5846
5847/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005848/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005849bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005850 Value *CatchSwitch = nullptr;
5851
5852 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5853 return true;
5854
5855 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5856 return TokError("expected scope value for catchpad");
5857
5858 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5859 return true;
5860
David Majnemer654e1302015-07-31 17:58:14 +00005861 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005862 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005863 return true;
5864
David Majnemer8a1c45d2015-12-12 05:38:55 +00005865 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005866 return false;
5867}
5868
David Majnemer654e1302015-07-31 17:58:14 +00005869/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005870/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005871bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005872 Value *ParentPad = nullptr;
5873
5874 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5875 return true;
5876
5877 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5878 Lex.getKind() != lltok::LocalVarID)
5879 return TokError("expected scope value for cleanuppad");
5880
5881 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5882 return true;
5883
David Majnemer654e1302015-07-31 17:58:14 +00005884 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005885 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005886 return true;
5887
David Majnemer8a1c45d2015-12-12 05:38:55 +00005888 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005889 return false;
5890}
5891
Chris Lattnerac161bf2009-01-02 07:01:27 +00005892//===----------------------------------------------------------------------===//
5893// Binary Operators.
5894//===----------------------------------------------------------------------===//
5895
5896/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005897/// ::= ArithmeticOps TypeAndValue ',' Value
5898///
5899/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5900/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005901bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005902 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005903 LocTy Loc; Value *LHS, *RHS;
5904 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5905 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5906 ParseValue(LHS->getType(), RHS, PFS))
5907 return true;
5908
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005909 bool Valid;
5910 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005911 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005912 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005913 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5914 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005915 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005916 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5917 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005918 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005919
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005920 if (!Valid)
5921 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005922
Chris Lattnerac161bf2009-01-02 07:01:27 +00005923 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5924 return false;
5925}
5926
5927/// ParseLogical
5928/// ::= ArithmeticOps TypeAndValue ',' Value {
5929bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5930 unsigned Opc) {
5931 LocTy Loc; Value *LHS, *RHS;
5932 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5933 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5934 ParseValue(LHS->getType(), RHS, PFS))
5935 return true;
5936
Duncan Sands9dff9be2010-02-15 16:12:20 +00005937 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005938 return Error(Loc,"instruction requires integer or integer vector operands");
5939
5940 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5941 return false;
5942}
5943
Chris Lattnerac161bf2009-01-02 07:01:27 +00005944/// ParseCompare
5945/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5946/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005947bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5948 unsigned Opc) {
5949 // Parse the integer/fp comparison predicate.
5950 LocTy Loc;
5951 unsigned Pred;
5952 Value *LHS, *RHS;
5953 if (ParseCmpPredicate(Pred, Opc) ||
5954 ParseTypeAndValue(LHS, Loc, PFS) ||
5955 ParseToken(lltok::comma, "expected ',' after compare value") ||
5956 ParseValue(LHS->getType(), RHS, PFS))
5957 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005958
Chris Lattnerac161bf2009-01-02 07:01:27 +00005959 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005960 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005961 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005962 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005963 } else {
5964 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005965 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00005966 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005967 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005968 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005969 }
5970 return false;
5971}
5972
5973//===----------------------------------------------------------------------===//
5974// Other Instructions.
5975//===----------------------------------------------------------------------===//
5976
5977
5978/// ParseCast
5979/// ::= CastOpc TypeAndValue 'to' Type
5980bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5981 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005982 LocTy Loc;
5983 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005984 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005985 if (ParseTypeAndValue(Op, Loc, PFS) ||
5986 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5987 ParseType(DestTy))
5988 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005989
Chris Lattner89d856e2009-03-01 00:53:13 +00005990 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5991 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005993 getTypeString(Op->getType()) + "' to '" +
5994 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005995 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005996 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5997 return false;
5998}
5999
6000/// ParseSelect
6001/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6002bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6003 LocTy Loc;
6004 Value *Op0, *Op1, *Op2;
6005 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6006 ParseToken(lltok::comma, "expected ',' after select condition") ||
6007 ParseTypeAndValue(Op1, PFS) ||
6008 ParseToken(lltok::comma, "expected ',' after select value") ||
6009 ParseTypeAndValue(Op2, PFS))
6010 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006011
Chris Lattnerac161bf2009-01-02 07:01:27 +00006012 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6013 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006014
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015 Inst = SelectInst::Create(Op0, Op1, Op2);
6016 return false;
6017}
6018
Chris Lattnerb55ab542009-01-05 08:18:44 +00006019/// ParseVA_Arg
6020/// ::= 'va_arg' TypeAndValue ',' Type
6021bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006022 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006023 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006024 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006025 if (ParseTypeAndValue(Op, PFS) ||
6026 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006027 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006029
Chris Lattnerb55ab542009-01-05 08:18:44 +00006030 if (!EltTy->isFirstClassType())
6031 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006032
6033 Inst = new VAArgInst(Op, EltTy);
6034 return false;
6035}
6036
6037/// ParseExtractElement
6038/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6039bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6040 LocTy Loc;
6041 Value *Op0, *Op1;
6042 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6043 ParseToken(lltok::comma, "expected ',' after extract value") ||
6044 ParseTypeAndValue(Op1, PFS))
6045 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006046
Chris Lattnerac161bf2009-01-02 07:01:27 +00006047 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6048 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006049
Eric Christopherc9742252009-07-25 02:28:41 +00006050 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006051 return false;
6052}
6053
6054/// ParseInsertElement
6055/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6056bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6057 LocTy Loc;
6058 Value *Op0, *Op1, *Op2;
6059 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6060 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6061 ParseTypeAndValue(Op1, PFS) ||
6062 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6063 ParseTypeAndValue(Op2, PFS))
6064 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006065
Chris Lattnerac161bf2009-01-02 07:01:27 +00006066 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006067 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006068
Chris Lattnerac161bf2009-01-02 07:01:27 +00006069 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6070 return false;
6071}
6072
6073/// ParseShuffleVector
6074/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6075bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6076 LocTy Loc;
6077 Value *Op0, *Op1, *Op2;
6078 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6079 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6080 ParseTypeAndValue(Op1, PFS) ||
6081 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6082 ParseTypeAndValue(Op2, PFS))
6083 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006084
Chris Lattnerac161bf2009-01-02 07:01:27 +00006085 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006086 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006087
Chris Lattnerac161bf2009-01-02 07:01:27 +00006088 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6089 return false;
6090}
6091
6092/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006093/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006094int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006095 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006096 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006097
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006098 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006099 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6100 ParseValue(Ty, Op0, PFS) ||
6101 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006102 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006103 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6104 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006105
Chris Lattnerf4f03422009-12-30 05:27:33 +00006106 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006107 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006108
6109 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006110 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006111
Chris Lattner3822f632009-01-02 08:05:26 +00006112 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006113 break;
6114
Chris Lattnerf4f03422009-12-30 05:27:33 +00006115 if (Lex.getKind() == lltok::MetadataVar) {
6116 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006117 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006118 }
Devang Patel8f842d32009-10-16 18:45:49 +00006119
Chris Lattner3822f632009-01-02 08:05:26 +00006120 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006121 ParseValue(Ty, Op0, PFS) ||
6122 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006123 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006124 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6125 return true;
6126 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006127
Chris Lattnerac161bf2009-01-02 07:01:27 +00006128 if (!Ty->isFirstClassType())
6129 return Error(TypeLoc, "phi node must have first class type");
6130
Jay Foad52131342011-03-30 11:28:46 +00006131 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6133 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6134 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006135 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006136}
6137
Bill Wendlingfae14752011-08-12 20:24:12 +00006138/// ParseLandingPad
6139/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6140/// Clause
6141/// ::= 'catch' TypeAndValue
6142/// ::= 'filter'
6143/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6144bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006145 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006146
David Majnemer7fddecc2015-06-17 20:52:32 +00006147 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006148 return true;
6149
David Majnemer7fddecc2015-06-17 20:52:32 +00006150 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006151 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6152
6153 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6154 LandingPadInst::ClauseType CT;
6155 if (EatIfPresent(lltok::kw_catch))
6156 CT = LandingPadInst::Catch;
6157 else if (EatIfPresent(lltok::kw_filter))
6158 CT = LandingPadInst::Filter;
6159 else
6160 return TokError("expected 'catch' or 'filter' clause type");
6161
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006162 Value *V;
6163 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006164 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006165 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006166
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006167 // A 'catch' type expects a non-array constant. A filter clause expects an
6168 // array constant.
6169 if (CT == LandingPadInst::Catch) {
6170 if (isa<ArrayType>(V->getType()))
6171 Error(VLoc, "'catch' clause has an invalid type");
6172 } else {
6173 if (!isa<ArrayType>(V->getType()))
6174 Error(VLoc, "'filter' clause has an invalid type");
6175 }
6176
Owen Andersonf8f259d2015-03-09 07:13:42 +00006177 Constant *CV = dyn_cast<Constant>(V);
6178 if (!CV)
6179 return Error(VLoc, "clause argument must be a constant");
6180 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006181 }
6182
Owen Andersonf8f259d2015-03-09 07:13:42 +00006183 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006184 return false;
6185}
6186
Chris Lattnerac161bf2009-01-02 07:01:27 +00006187/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006188/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6189/// OptionalAttrs Type Value ParameterList OptionalAttrs
6190/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6191/// OptionalAttrs Type Value ParameterList OptionalAttrs
6192/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6193/// OptionalAttrs Type Value ParameterList OptionalAttrs
6194/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6195/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006196bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006197 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006198 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006199 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006200 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006201 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006202 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006203 LocTy RetTypeLoc;
6204 ValID CalleeID;
6205 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006206 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006207 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006208
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006209 if (TCK != CallInst::TCK_None &&
6210 ParseToken(lltok::kw_call,
6211 "expected 'tail call', 'musttail call', or 'notail call'"))
6212 return true;
6213
6214 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6215
6216 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006217 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006218 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006219 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6220 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006221 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6222 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006223 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006224
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006225 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6226 return Error(CallLoc, "fast-math-flags specified for call without "
6227 "floating-point scalar or vector return type");
6228
Chris Lattnerac161bf2009-01-02 07:01:27 +00006229 // If RetType is a non-function pointer type, then this is the short syntax
6230 // for the call, which means that RetType is just the return type. Infer the
6231 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006232 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6233 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006234 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006235 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006236 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6237 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006238
Chris Lattnerac161bf2009-01-02 07:01:27 +00006239 if (!FunctionType::isValidReturnType(RetType))
6240 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006241
Owen Anderson4056ca92009-07-29 22:17:13 +00006242 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006243 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006244
David Blaikie41ba2b42015-07-27 23:32:19 +00006245 CalleeID.FTy = Ty;
6246
Chris Lattnerac161bf2009-01-02 07:01:27 +00006247 // Look up the callee.
6248 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00006249 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6250 /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006251 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006252
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006253 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006254 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006255
Chris Lattnerac161bf2009-01-02 07:01:27 +00006256 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006257
Chris Lattnerac161bf2009-01-02 07:01:27 +00006258 // Loop through FunctionType's arguments and ensure they are specified
6259 // correctly. Also, gather any parameter attributes.
6260 FunctionType::param_iterator I = Ty->param_begin();
6261 FunctionType::param_iterator E = Ty->param_end();
6262 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006263 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006264 if (I != E) {
6265 ExpectedTy = *I++;
6266 } else if (!Ty->isVarArg()) {
6267 return Error(ArgList[i].Loc, "too many arguments specified");
6268 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006269
Chris Lattnerac161bf2009-01-02 07:01:27 +00006270 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6271 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006272 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006273 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006274 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006275 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006276
Chris Lattnerac161bf2009-01-02 07:01:27 +00006277 if (I != E)
6278 return Error(CallLoc, "not enough parameters specified for call");
6279
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006280 if (FnAttrs.hasAlignmentAttr())
6281 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006282
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006283 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006284 AttributeList PAL =
6285 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6286 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006287
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006288 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006289 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006290 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006291 if (FMF.any())
6292 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006293 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006294 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006295 Inst = CI;
6296 return false;
6297}
6298
6299//===----------------------------------------------------------------------===//
6300// Memory Instructions.
6301//===----------------------------------------------------------------------===//
6302
6303/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006304/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006305/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006306int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006307 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006308 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006309 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006310 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006311 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006312
6313 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006314 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006315
David Majnemera3b0eb22015-02-16 08:38:03 +00006316 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006317
David Majnemera3b0eb22015-02-16 08:38:03 +00006318 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6319 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006320
Chris Lattnerb2f39502009-12-30 05:44:30 +00006321 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006322 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006323 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006324 if (ParseOptionalAlignment(Alignment))
6325 return true;
6326 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6327 return true;
6328 } else if (Lex.getKind() == lltok::kw_addrspace) {
6329 ASLoc = Lex.getLoc();
6330 if (ParseOptionalAddrSpace(AddrSpace))
6331 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006332 } else if (Lex.getKind() == lltok::MetadataVar) {
6333 AteExtraComma = true;
6334 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006335 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006336 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006337 if (EatIfPresent(lltok::comma)) {
6338 if (Lex.getKind() == lltok::kw_align) {
6339 if (ParseOptionalAlignment(Alignment))
6340 return true;
6341 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6342 return true;
6343 } else if (Lex.getKind() == lltok::kw_addrspace) {
6344 ASLoc = Lex.getLoc();
6345 if (ParseOptionalAddrSpace(AddrSpace))
6346 return true;
6347 } else if (Lex.getKind() == lltok::MetadataVar) {
6348 AteExtraComma = true;
6349 }
6350 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006351 }
6352 }
6353
Dan Gohman2140a742010-05-28 01:14:11 +00006354 if (Size && !Size->getType()->isIntegerTy())
6355 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006356
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006357 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006358 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006359 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006360 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006361 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006362}
6363
6364/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006365/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006366/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006367/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006368int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006369 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006370 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006371 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006372 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006373 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006374 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006375
6376 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006377 isAtomic = true;
6378 Lex.Lex();
6379 }
6380
Chris Lattnerbc639292011-11-27 06:56:53 +00006381 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006382 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006383 isVolatile = true;
6384 Lex.Lex();
6385 }
6386
David Blaikie15d9a4c2015-04-06 20:59:48 +00006387 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006388 LocTy ExplicitTypeLoc = Lex.getLoc();
6389 if (ParseType(Ty) ||
6390 ParseToken(lltok::comma, "expected comma after load's type") ||
6391 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006392 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006393 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6394 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006395
David Blaikie15d9a4c2015-04-06 20:59:48 +00006396 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006397 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006398 if (isAtomic && !Alignment)
6399 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006400 if (Ordering == AtomicOrdering::Release ||
6401 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006402 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006403
David Blaikiea79ac142015-02-27 21:17:42 +00006404 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6405 return Error(ExplicitTypeLoc,
6406 "explicit pointee type doesn't match operand's pointee type");
6407
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006408 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006409 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006410}
6411
6412/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006413
6414/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6415/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006416/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006417int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006418 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006419 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006420 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006421 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006422 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006423 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006424
6425 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006426 isAtomic = true;
6427 Lex.Lex();
6428 }
6429
Chris Lattnerbc639292011-11-27 06:56:53 +00006430 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006431 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006432 isVolatile = true;
6433 Lex.Lex();
6434 }
6435
Chris Lattnerac161bf2009-01-02 07:01:27 +00006436 if (ParseTypeAndValue(Val, Loc, PFS) ||
6437 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006438 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006439 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006440 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006441 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006442
Duncan Sands19d0b472010-02-16 11:11:14 +00006443 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006444 return Error(PtrLoc, "store operand must be a pointer");
6445 if (!Val->getType()->isFirstClassType())
6446 return Error(Loc, "store operand must be a first class value");
6447 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6448 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006449 if (isAtomic && !Alignment)
6450 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006451 if (Ordering == AtomicOrdering::Acquire ||
6452 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006453 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006454
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006455 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006456 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006457}
6458
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006459/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006460/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6461/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006462int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006463 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6464 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006465 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6466 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006467 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006468 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006469 bool isWeak = false;
6470
6471 if (EatIfPresent(lltok::kw_weak))
6472 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006473
6474 if (EatIfPresent(lltok::kw_volatile))
6475 isVolatile = true;
6476
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006477 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6478 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6479 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6480 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6481 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006482 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006483 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006484 return true;
6485
JF Bastien800f87a2016-04-06 21:19:33 +00006486 if (SuccessOrdering == AtomicOrdering::Unordered ||
6487 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006488 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006489 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6490 return TokError("cmpxchg failure argument shall be no stronger than the "
6491 "success argument");
6492 if (FailureOrdering == AtomicOrdering::Release ||
6493 FailureOrdering == AtomicOrdering::AcquireRelease)
6494 return TokError(
6495 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006496 if (!Ptr->getType()->isPointerTy())
6497 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6498 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6499 return Error(CmpLoc, "compare value and pointer type do not match");
6500 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6501 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006502 if (!New->getType()->isFirstClassType())
6503 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006504 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006505 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006506 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006507 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006508 Inst = CXI;
6509 return AteExtraComma ? InstExtraComma : InstNormal;
6510}
6511
6512/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006513/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6514/// 'singlethread'? AtomicOrdering
6515int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006516 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6517 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006518 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006519 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006520 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006521 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006522
6523 if (EatIfPresent(lltok::kw_volatile))
6524 isVolatile = true;
6525
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006526 switch (Lex.getKind()) {
6527 default: return TokError("expected binary operation in atomicrmw");
6528 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6529 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6530 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6531 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6532 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6533 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6534 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6535 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6536 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6537 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6538 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6539 }
6540 Lex.Lex(); // Eat the operation.
6541
6542 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6543 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6544 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006545 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006546 return true;
6547
JF Bastien800f87a2016-04-06 21:19:33 +00006548 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006549 return TokError("atomicrmw cannot be unordered");
6550 if (!Ptr->getType()->isPointerTy())
6551 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6552 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6553 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6554 if (!Val->getType()->isIntegerTy())
6555 return Error(ValLoc, "atomicrmw operand must be an integer");
6556 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6557 if (Size < 8 || (Size & (Size - 1)))
6558 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6559 " integer");
6560
6561 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006562 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006563 RMWI->setVolatile(isVolatile);
6564 Inst = RMWI;
6565 return AteExtraComma ? InstExtraComma : InstNormal;
6566}
6567
Eli Friedmanfee02c62011-07-25 23:16:38 +00006568/// ParseFence
6569/// ::= 'fence' 'singlethread'? AtomicOrdering
6570int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006571 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006572 SyncScope::ID SSID = SyncScope::System;
6573 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006574 return true;
6575
JF Bastien800f87a2016-04-06 21:19:33 +00006576 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006577 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006578 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006579 return TokError("fence cannot be monotonic");
6580
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006581 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006582 return InstNormal;
6583}
6584
Chris Lattnerac161bf2009-01-02 07:01:27 +00006585/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006586/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006587int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006588 Value *Ptr = nullptr;
6589 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006590 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006591
Dan Gohman16cbbe42009-07-29 15:58:36 +00006592 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006593
David Blaikie79e6c742015-02-27 19:29:02 +00006594 Type *Ty = nullptr;
6595 LocTy ExplicitTypeLoc = Lex.getLoc();
6596 if (ParseType(Ty) ||
6597 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6598 ParseTypeAndValue(Ptr, Loc, PFS))
6599 return true;
6600
Eli Benderskyd9806682013-04-22 17:03:42 +00006601 Type *BaseType = Ptr->getType();
6602 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6603 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006604 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006605
David Blaikie8d757942015-03-09 23:08:44 +00006606 if (Ty != BasePointerType->getElementType())
6607 return Error(ExplicitTypeLoc,
6608 "explicit pointee type doesn't match operand's pointee type");
6609
Chris Lattnerac161bf2009-01-02 07:01:27 +00006610 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006611 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006612 // GEP returns a vector of pointers if at least one of parameters is a vector.
6613 // All vector parameters should have the same vector width.
6614 unsigned GEPWidth = BaseType->isVectorTy() ?
6615 BaseType->getVectorNumElements() : 0;
6616
Chris Lattner3822f632009-01-02 08:05:26 +00006617 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006618 if (Lex.getKind() == lltok::MetadataVar) {
6619 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006620 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006621 }
Chris Lattner3822f632009-01-02 08:05:26 +00006622 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006623 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006624 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006625
Nadav Rotem3924cb02011-12-05 06:29:09 +00006626 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006627 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6628 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006629 return Error(EltLoc,
6630 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006631 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006632 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006633 Indices.push_back(Val);
6634 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006635
Craig Toppere3dcce92015-08-01 22:20:21 +00006636 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006637 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006638 return Error(Loc, "base element of getelementptr must be sized");
6639
David Blaikied33bad32015-04-17 22:32:13 +00006640 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006641 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006642 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006643 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006644 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006645 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006646}
6647
6648/// ParseExtractValue
6649/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006650int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006651 Value *Val; LocTy Loc;
6652 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006653 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006654 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006655 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006656 return true;
6657
Chris Lattner392be582010-02-12 20:49:41 +00006658 if (!Val->getType()->isAggregateType())
6659 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006660
Jay Foad57aa6362011-07-13 10:26:04 +00006661 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006662 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006663 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006664 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006665}
6666
6667/// ParseInsertValue
6668/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006669int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006670 Value *Val0, *Val1; LocTy Loc0, Loc1;
6671 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006672 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006673 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6674 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6675 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006676 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006677 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006678
Chris Lattner392be582010-02-12 20:49:41 +00006679 if (!Val0->getType()->isAggregateType())
6680 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006681
David Majnemer30074532015-02-11 07:43:58 +00006682 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6683 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006684 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006685 if (IndexedType != Val1->getType())
6686 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6687 getTypeString(Val1->getType()) + "' instead of '" +
6688 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006689 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006690 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006691}
Nick Lewycky49f89192009-04-04 07:22:01 +00006692
6693//===----------------------------------------------------------------------===//
6694// Embedded metadata.
6695//===----------------------------------------------------------------------===//
6696
6697/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006698/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006699/// Element
6700/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006701bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006702 if (ParseToken(lltok::lbrace, "expected '{' here"))
6703 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006704
Dan Gohman1e0213a2010-07-13 19:33:27 +00006705 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006706 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006707 return false;
6708
Nick Lewycky49f89192009-04-04 07:22:01 +00006709 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006710 // Null is a special case since it is typeless.
6711 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006712 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006713 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006714 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006715
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006716 Metadata *MD;
6717 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006718 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006719 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006720 } while (EatIfPresent(lltok::comma));
6721
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006722 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006723}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006724
6725//===----------------------------------------------------------------------===//
6726// Use-list order directives.
6727//===----------------------------------------------------------------------===//
6728bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6729 SMLoc Loc) {
6730 if (V->use_empty())
6731 return Error(Loc, "value has no uses");
6732
6733 unsigned NumUses = 0;
6734 SmallDenseMap<const Use *, unsigned, 16> Order;
6735 for (const Use &U : V->uses()) {
6736 if (++NumUses > Indexes.size())
6737 break;
6738 Order[&U] = Indexes[NumUses - 1];
6739 }
6740 if (NumUses < 2)
6741 return Error(Loc, "value only has one use");
6742 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6743 return Error(Loc, "wrong number of indexes, expected " +
6744 Twine(std::distance(V->use_begin(), V->use_end())));
6745
6746 V->sortUseList([&](const Use &L, const Use &R) {
6747 return Order.lookup(&L) < Order.lookup(&R);
6748 });
6749 return false;
6750}
6751
6752/// ParseUseListOrderIndexes
6753/// ::= '{' uint32 (',' uint32)+ '}'
6754bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6755 SMLoc Loc = Lex.getLoc();
6756 if (ParseToken(lltok::lbrace, "expected '{' here"))
6757 return true;
6758 if (Lex.getKind() == lltok::rbrace)
6759 return Lex.Error("expected non-empty list of uselistorder indexes");
6760
6761 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6762 // indexes should be distinct numbers in the range [0, size-1], and should
6763 // not be in order.
6764 unsigned Offset = 0;
6765 unsigned Max = 0;
6766 bool IsOrdered = true;
6767 assert(Indexes.empty() && "Expected empty order vector");
6768 do {
6769 unsigned Index;
6770 if (ParseUInt32(Index))
6771 return true;
6772
6773 // Update consistency checks.
6774 Offset += Index - Indexes.size();
6775 Max = std::max(Max, Index);
6776 IsOrdered &= Index == Indexes.size();
6777
6778 Indexes.push_back(Index);
6779 } while (EatIfPresent(lltok::comma));
6780
6781 if (ParseToken(lltok::rbrace, "expected '}' here"))
6782 return true;
6783
6784 if (Indexes.size() < 2)
6785 return Error(Loc, "expected >= 2 uselistorder indexes");
6786 if (Offset != 0 || Max >= Indexes.size())
6787 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6788 if (IsOrdered)
6789 return Error(Loc, "expected uselistorder indexes to change the order");
6790
6791 return false;
6792}
6793
6794/// ParseUseListOrder
6795/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6796bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6797 SMLoc Loc = Lex.getLoc();
6798 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6799 return true;
6800
6801 Value *V;
6802 SmallVector<unsigned, 16> Indexes;
6803 if (ParseTypeAndValue(V, PFS) ||
6804 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6805 ParseUseListOrderIndexes(Indexes))
6806 return true;
6807
6808 return sortUseListOrder(V, Indexes, Loc);
6809}
6810
6811/// ParseUseListOrderBB
6812/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6813bool LLParser::ParseUseListOrderBB() {
6814 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6815 SMLoc Loc = Lex.getLoc();
6816 Lex.Lex();
6817
6818 ValID Fn, Label;
6819 SmallVector<unsigned, 16> Indexes;
6820 if (ParseValID(Fn) ||
6821 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6822 ParseValID(Label) ||
6823 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6824 ParseUseListOrderIndexes(Indexes))
6825 return true;
6826
6827 // Check the function.
6828 GlobalValue *GV;
6829 if (Fn.Kind == ValID::t_GlobalName)
6830 GV = M->getNamedValue(Fn.StrVal);
6831 else if (Fn.Kind == ValID::t_GlobalID)
6832 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6833 else
6834 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6835 if (!GV)
6836 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6837 auto *F = dyn_cast<Function>(GV);
6838 if (!F)
6839 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6840 if (F->isDeclaration())
6841 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6842
6843 // Check the basic block.
6844 if (Label.Kind == ValID::t_LocalID)
6845 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6846 if (Label.Kind != ValID::t_LocalName)
6847 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006848 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006849 if (!V)
6850 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6851 if (!isa<BasicBlock>(V))
6852 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6853
6854 return sortUseListOrder(V, Indexes, Loc);
6855}