blob: d59b21dd4c79f5c46a428ed1bd7c666e686f2564 [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;
1151 case lltok::kw_sanitize_address:
1152 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001153 case lltok::kw_sanitize_hwaddress:
1154 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001155 case lltok::kw_sanitize_thread:
1156 B.addAttribute(Attribute::SanitizeThread); break;
1157 case lltok::kw_sanitize_memory:
1158 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001159 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001160 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001161 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001162
1163 // Error handling.
1164 case lltok::kw_inreg:
1165 case lltok::kw_signext:
1166 case lltok::kw_zeroext:
1167 HaveError |=
1168 Error(Lex.getLoc(),
1169 "invalid use of attribute on a function");
1170 break;
1171 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001172 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001173 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001174 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001175 case lltok::kw_nest:
1176 case lltok::kw_noalias:
1177 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001178 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001179 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001180 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001181 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001182 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001183 HaveError |=
1184 Error(Lex.getLoc(),
1185 "invalid use of parameter-only attribute on a function");
1186 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001187 }
1188
1189 Lex.Lex();
1190 }
1191}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001192
1193//===----------------------------------------------------------------------===//
1194// GlobalValue Reference/Resolution Routines.
1195//===----------------------------------------------------------------------===//
1196
Karl Schimpf77729782015-09-03 18:06:44 +00001197static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1198 const std::string &Name) {
1199 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1200 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1201 else
1202 return new GlobalVariable(*M, PTy->getElementType(), false,
1203 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1204 nullptr, GlobalVariable::NotThreadLocal,
1205 PTy->getAddressSpace());
1206}
1207
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208/// GetGlobalVal - Get a value with the specified name or ID, creating a
1209/// forward reference record if needed. This can return null if the value
1210/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001211GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001213 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001214 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001215 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001216 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001218
Chris Lattnerac161bf2009-01-02 07:01:27 +00001219 // Look this name up in the normal function symbol table.
1220 GlobalValue *Val =
1221 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001222
Chris Lattnerac161bf2009-01-02 07:01:27 +00001223 // If this is a forward reference for the value, see if we already created a
1224 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001225 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001226 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 if (I != ForwardRefVals.end())
1228 Val = I->second.first;
1229 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001230
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231 // If we have the value in the symbol table or fwd-ref table, return it.
1232 if (Val) {
1233 if (Val->getType() == Ty) return Val;
1234 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001235 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001236 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001237 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001238
Chris Lattnerac161bf2009-01-02 07:01:27 +00001239 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001240 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001241 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1242 return FwdVal;
1243}
1244
Chris Lattner229907c2011-07-18 04:54:35 +00001245GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1246 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001247 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001248 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001249 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001250 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001251
Craig Topper2617dcc2014-04-15 06:32:26 +00001252 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001253
Chris Lattnerac161bf2009-01-02 07:01:27 +00001254 // If this is a forward reference for the value, see if we already created a
1255 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001256 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001257 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001258 if (I != ForwardRefValIDs.end())
1259 Val = I->second.first;
1260 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001261
Chris Lattnerac161bf2009-01-02 07:01:27 +00001262 // If we have the value in the symbol table or fwd-ref table, return it.
1263 if (Val) {
1264 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001265 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001266 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001267 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001268 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001269
Chris Lattnerac161bf2009-01-02 07:01:27 +00001270 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001271 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001272 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1273 return FwdVal;
1274}
1275
Chris Lattnerac161bf2009-01-02 07:01:27 +00001276//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001277// Comdat Reference/Resolution Routines.
1278//===----------------------------------------------------------------------===//
1279
1280Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1281 // Look this name up in the comdat symbol table.
1282 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1283 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1284 if (I != ComdatSymTab.end())
1285 return &I->second;
1286
1287 // Otherwise, create a new forward reference for this value and remember it.
1288 Comdat *C = M->getOrInsertComdat(Name);
1289 ForwardRefComdats[Name] = Loc;
1290 return C;
1291}
1292
David Majnemerdad0a642014-06-27 18:19:56 +00001293//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001294// Helper Routines.
1295//===----------------------------------------------------------------------===//
1296
1297/// ParseToken - If the current token has the specified kind, eat it and return
1298/// success. Otherwise, emit the specified error and return failure.
1299bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1300 if (Lex.getKind() != T)
1301 return TokError(ErrMsg);
1302 Lex.Lex();
1303 return false;
1304}
1305
Chris Lattner3822f632009-01-02 08:05:26 +00001306/// ParseStringConstant
1307/// ::= StringConstant
1308bool LLParser::ParseStringConstant(std::string &Result) {
1309 if (Lex.getKind() != lltok::StringConstant)
1310 return TokError("expected string constant");
1311 Result = Lex.getStrVal();
1312 Lex.Lex();
1313 return false;
1314}
1315
1316/// ParseUInt32
1317/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001318bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001319 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1320 return TokError("expected integer");
1321 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1322 if (Val64 != unsigned(Val64))
1323 return TokError("expected 32-bit integer (too large)");
1324 Val = Val64;
1325 Lex.Lex();
1326 return false;
1327}
1328
Hal Finkelb0407ba2014-07-18 15:51:28 +00001329/// ParseUInt64
1330/// ::= uint64
1331bool LLParser::ParseUInt64(uint64_t &Val) {
1332 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1333 return TokError("expected integer");
1334 Val = Lex.getAPSIntVal().getLimitedValue();
1335 Lex.Lex();
1336 return false;
1337}
1338
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001339/// ParseTLSModel
1340/// := 'localdynamic'
1341/// := 'initialexec'
1342/// := 'localexec'
1343bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1344 switch (Lex.getKind()) {
1345 default:
1346 return TokError("expected localdynamic, initialexec or localexec");
1347 case lltok::kw_localdynamic:
1348 TLM = GlobalVariable::LocalDynamicTLSModel;
1349 break;
1350 case lltok::kw_initialexec:
1351 TLM = GlobalVariable::InitialExecTLSModel;
1352 break;
1353 case lltok::kw_localexec:
1354 TLM = GlobalVariable::LocalExecTLSModel;
1355 break;
1356 }
1357
1358 Lex.Lex();
1359 return false;
1360}
1361
1362/// ParseOptionalThreadLocal
1363/// := /*empty*/
1364/// := 'thread_local'
1365/// := 'thread_local' '(' tlsmodel ')'
1366bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1367 TLM = GlobalVariable::NotThreadLocal;
1368 if (!EatIfPresent(lltok::kw_thread_local))
1369 return false;
1370
1371 TLM = GlobalVariable::GeneralDynamicTLSModel;
1372 if (Lex.getKind() == lltok::lparen) {
1373 Lex.Lex();
1374 return ParseTLSModel(TLM) ||
1375 ParseToken(lltok::rparen, "expected ')' after thread local model");
1376 }
1377 return false;
1378}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001379
1380/// ParseOptionalAddrSpace
1381/// := /*empty*/
1382/// := 'addrspace' '(' uint32 ')'
1383bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1384 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001385 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001386 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001387 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001388 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001389 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001390}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001391
Artur Pilipenko17376c42015-08-03 14:31:49 +00001392/// ParseStringAttribute
1393/// := StringConstant
1394/// := StringConstant '=' StringConstant
1395bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1396 std::string Attr = Lex.getStrVal();
1397 Lex.Lex();
1398 std::string Val;
1399 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1400 return true;
1401 B.addAttribute(Attr, Val);
1402 return false;
1403}
1404
Bill Wendling34c2eb22012-12-04 23:40:58 +00001405/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1406bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1407 bool HaveError = false;
1408
1409 B.clear();
1410
Eugene Zelenko1804a772016-08-25 00:45:04 +00001411 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001412 lltok::Kind Token = Lex.getKind();
1413 switch (Token) {
1414 default: // End of attributes.
1415 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001416 case lltok::StringConstant: {
1417 if (ParseStringAttribute(B))
1418 return true;
1419 continue;
1420 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001421 case lltok::kw_align: {
1422 unsigned Alignment;
1423 if (ParseOptionalAlignment(Alignment))
1424 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001425 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001426 continue;
1427 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001428 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001429 case lltok::kw_dereferenceable: {
1430 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001431 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001432 return true;
1433 B.addDereferenceableAttr(Bytes);
1434 continue;
1435 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001436 case lltok::kw_dereferenceable_or_null: {
1437 uint64_t Bytes;
1438 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1439 return true;
1440 B.addDereferenceableOrNullAttr(Bytes);
1441 continue;
1442 }
Reid Klecknera534a382013-12-19 02:14:12 +00001443 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001444 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1445 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1446 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1447 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001448 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001449 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1450 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001451 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001452 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1453 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001454 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001455 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001456 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001457 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001458
Stephen Lin7577ed52013-04-20 13:16:13 +00001459 case lltok::kw_alignstack:
1460 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001461 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001462 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001463 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001464 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001465 case lltok::kw_minsize:
1466 case lltok::kw_naked:
1467 case lltok::kw_nobuiltin:
1468 case lltok::kw_noduplicate:
1469 case lltok::kw_noimplicitfloat:
1470 case lltok::kw_noinline:
1471 case lltok::kw_nonlazybind:
1472 case lltok::kw_noredzone:
1473 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001474 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001475 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001476 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001477 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001478 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001479 case lltok::kw_returns_twice:
1480 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001481 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001482 case lltok::kw_sanitize_memory:
1483 case lltok::kw_sanitize_thread:
1484 case lltok::kw_ssp:
1485 case lltok::kw_sspreq:
1486 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001487 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001488 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001489 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001490 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1491 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001492 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001493
Bill Wendling34c2eb22012-12-04 23:40:58 +00001494 Lex.Lex();
1495 }
1496}
1497
1498/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1499bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1500 bool HaveError = false;
1501
1502 B.clear();
1503
Eugene Zelenko1804a772016-08-25 00:45:04 +00001504 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001505 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001506 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001507 default: // End of attributes.
1508 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001509 case lltok::StringConstant: {
1510 if (ParseStringAttribute(B))
1511 return true;
1512 continue;
1513 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001514 case lltok::kw_dereferenceable: {
1515 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001516 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001517 return true;
1518 B.addDereferenceableAttr(Bytes);
1519 continue;
1520 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001521 case lltok::kw_dereferenceable_or_null: {
1522 uint64_t Bytes;
1523 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1524 return true;
1525 B.addDereferenceableOrNullAttr(Bytes);
1526 continue;
1527 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001528 case lltok::kw_align: {
1529 unsigned Alignment;
1530 if (ParseOptionalAlignment(Alignment))
1531 return true;
1532 B.addAlignmentAttr(Alignment);
1533 continue;
1534 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001535 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1536 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001537 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001538 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1539 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001540
Bill Wendling34c2eb22012-12-04 23:40:58 +00001541 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001542 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001543 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001544 case lltok::kw_nest:
1545 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001546 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001547 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001548 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001549 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001550 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001551 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001552
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001553 case lltok::kw_alignstack:
1554 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001555 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001556 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001557 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001558 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001559 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001560 case lltok::kw_minsize:
1561 case lltok::kw_naked:
1562 case lltok::kw_nobuiltin:
1563 case lltok::kw_noduplicate:
1564 case lltok::kw_noimplicitfloat:
1565 case lltok::kw_noinline:
1566 case lltok::kw_nonlazybind:
1567 case lltok::kw_noredzone:
1568 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001569 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001570 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001571 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001572 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001573 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001574 case lltok::kw_returns_twice:
1575 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001576 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001577 case lltok::kw_sanitize_memory:
1578 case lltok::kw_sanitize_thread:
1579 case lltok::kw_ssp:
1580 case lltok::kw_sspreq:
1581 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001582 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001583 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001584 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001585 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001586 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001587
1588 case lltok::kw_readnone:
1589 case lltok::kw_readonly:
1590 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001591 }
1592
Chris Lattnerac161bf2009-01-02 07:01:27 +00001593 Lex.Lex();
1594 }
1595}
1596
Rafael Espindolac6269912016-05-10 17:16:45 +00001597static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1598 HasLinkage = true;
1599 switch (Kind) {
1600 default:
1601 HasLinkage = false;
1602 return GlobalValue::ExternalLinkage;
1603 case lltok::kw_private:
1604 return GlobalValue::PrivateLinkage;
1605 case lltok::kw_internal:
1606 return GlobalValue::InternalLinkage;
1607 case lltok::kw_weak:
1608 return GlobalValue::WeakAnyLinkage;
1609 case lltok::kw_weak_odr:
1610 return GlobalValue::WeakODRLinkage;
1611 case lltok::kw_linkonce:
1612 return GlobalValue::LinkOnceAnyLinkage;
1613 case lltok::kw_linkonce_odr:
1614 return GlobalValue::LinkOnceODRLinkage;
1615 case lltok::kw_available_externally:
1616 return GlobalValue::AvailableExternallyLinkage;
1617 case lltok::kw_appending:
1618 return GlobalValue::AppendingLinkage;
1619 case lltok::kw_common:
1620 return GlobalValue::CommonLinkage;
1621 case lltok::kw_extern_weak:
1622 return GlobalValue::ExternalWeakLinkage;
1623 case lltok::kw_external:
1624 return GlobalValue::ExternalLinkage;
1625 }
1626}
1627
Chris Lattnerac161bf2009-01-02 07:01:27 +00001628/// ParseOptionalLinkage
1629/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001630/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001631/// ::= 'internal'
1632/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001633/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001634/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001635/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001636/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001637/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001639/// ::= 'extern_weak'
1640/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001641bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1642 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001643 unsigned &DLLStorageClass,
1644 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001645 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1646 if (HasLinkage)
1647 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001648 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001649 ParseOptionalVisibility(Visibility);
1650 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001651
1652 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1653 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1654 }
1655
Chris Lattnerac161bf2009-01-02 07:01:27 +00001656 return false;
1657}
1658
Sean Fertilec70d28b2017-10-26 15:00:26 +00001659void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1660 switch (Lex.getKind()) {
1661 default:
1662 DSOLocal = false;
1663 break;
1664 case lltok::kw_dso_local:
1665 DSOLocal = true;
1666 Lex.Lex();
1667 break;
1668 case lltok::kw_dso_preemptable:
1669 DSOLocal = false;
1670 Lex.Lex();
1671 break;
1672 }
1673}
1674
Chris Lattnerac161bf2009-01-02 07:01:27 +00001675/// ParseOptionalVisibility
1676/// ::= /*empty*/
1677/// ::= 'default'
1678/// ::= 'hidden'
1679/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001680///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001681void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001683 default:
1684 Res = GlobalValue::DefaultVisibility;
1685 return;
1686 case lltok::kw_default:
1687 Res = GlobalValue::DefaultVisibility;
1688 break;
1689 case lltok::kw_hidden:
1690 Res = GlobalValue::HiddenVisibility;
1691 break;
1692 case lltok::kw_protected:
1693 Res = GlobalValue::ProtectedVisibility;
1694 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001695 }
1696 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001697}
1698
Nico Rieck7157bb72014-01-14 15:22:47 +00001699/// ParseOptionalDLLStorageClass
1700/// ::= /*empty*/
1701/// ::= 'dllimport'
1702/// ::= 'dllexport'
1703///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001704void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001705 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001706 default:
1707 Res = GlobalValue::DefaultStorageClass;
1708 return;
1709 case lltok::kw_dllimport:
1710 Res = GlobalValue::DLLImportStorageClass;
1711 break;
1712 case lltok::kw_dllexport:
1713 Res = GlobalValue::DLLExportStorageClass;
1714 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001715 }
1716 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001717}
1718
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719/// ParseOptionalCallingConv
1720/// ::= /*empty*/
1721/// ::= 'ccc'
1722/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001723/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724/// ::= 'coldcc'
1725/// ::= 'x86_stdcallcc'
1726/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001727/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001728/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001729/// ::= 'arm_apcscc'
1730/// ::= 'arm_aapcscc'
1731/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001732/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001733/// ::= 'avr_intrcc'
1734/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001735/// ::= 'ptx_kernel'
1736/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001737/// ::= 'spir_func'
1738/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001739/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001740/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001741/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001742/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001743/// ::= 'preserve_mostcc'
1744/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001745/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001746/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001747/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001748/// ::= 'hhvmcc'
1749/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001750/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001751/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001752/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001753/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001754/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001755/// ::= 'amdgpu_gs'
1756/// ::= 'amdgpu_ps'
1757/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001758/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001759/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001760///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001761bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001762 switch (Lex.getKind()) {
1763 default: CC = CallingConv::C; return false;
1764 case lltok::kw_ccc: CC = CallingConv::C; break;
1765 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1766 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1767 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1768 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001769 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001770 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001771 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001772 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1773 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1774 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001775 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001776 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1777 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001778 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1779 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001780 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1781 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001782 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001783 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001784 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001785 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001786 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001787 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1788 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001789 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001790 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001791 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001792 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1793 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001794 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001795 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001796 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001797 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001798 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001799 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1800 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1801 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001802 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001803 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001804 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001805 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001806 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001807 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001808
Chris Lattnerac161bf2009-01-02 07:01:27 +00001809 Lex.Lex();
1810 return false;
1811}
1812
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001813/// ParseMetadataAttachment
1814/// ::= !dbg !42
1815bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1816 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1817
1818 std::string Name = Lex.getStrVal();
1819 Kind = M->getMDKindID(Name);
1820 Lex.Lex();
1821
1822 return ParseMDNode(MD);
1823}
1824
Chris Lattner5c427632009-12-30 05:31:19 +00001825/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001826/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001827bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001828 do {
1829 if (Lex.getKind() != lltok::MetadataVar)
1830 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001831
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001832 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001833 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001834 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001835 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001836
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001837 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001838 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001839 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001840
Chris Lattner596760d2009-12-29 21:25:40 +00001841 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001842 } while (EatIfPresent(lltok::comma));
1843 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001844}
1845
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001846/// ParseGlobalObjectMetadataAttachment
1847/// ::= !dbg !57
1848bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1849 unsigned MDK;
1850 MDNode *N;
1851 if (ParseMetadataAttachment(MDK, N))
1852 return true;
1853
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001854 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001855 return false;
1856}
1857
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001858/// ParseOptionalFunctionMetadata
1859/// ::= (!dbg !57)*
1860bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001861 while (Lex.getKind() == lltok::MetadataVar)
1862 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001863 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001864 return false;
1865}
1866
Chris Lattnerac161bf2009-01-02 07:01:27 +00001867/// ParseOptionalAlignment
1868/// ::= /* empty */
1869/// ::= 'align' 4
1870bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1871 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001872 if (!EatIfPresent(lltok::kw_align))
1873 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001874 LocTy AlignLoc = Lex.getLoc();
1875 if (ParseUInt32(Alignment)) return true;
1876 if (!isPowerOf2_32(Alignment))
1877 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001878 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001879 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001880 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881}
1882
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001883/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001884/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001885/// ::= AttrKind '(' 4 ')'
1886///
1887/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1888bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1889 uint64_t &Bytes) {
1890 assert((AttrKind == lltok::kw_dereferenceable ||
1891 AttrKind == lltok::kw_dereferenceable_or_null) &&
1892 "contract!");
1893
Hal Finkelb0407ba2014-07-18 15:51:28 +00001894 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001895 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001896 return false;
1897 LocTy ParenLoc = Lex.getLoc();
1898 if (!EatIfPresent(lltok::lparen))
1899 return Error(ParenLoc, "expected '('");
1900 LocTy DerefLoc = Lex.getLoc();
1901 if (ParseUInt64(Bytes)) return true;
1902 ParenLoc = Lex.getLoc();
1903 if (!EatIfPresent(lltok::rparen))
1904 return Error(ParenLoc, "expected ')'");
1905 if (!Bytes)
1906 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1907 return false;
1908}
1909
Chris Lattnerb2f39502009-12-30 05:44:30 +00001910/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001911/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001912/// ::= ',' align 4
1913///
1914/// This returns with AteExtraComma set to true if it ate an excess comma at the
1915/// end.
1916bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1917 bool &AteExtraComma) {
1918 AteExtraComma = false;
1919 while (EatIfPresent(lltok::comma)) {
1920 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001921 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001922 AteExtraComma = true;
1923 return false;
1924 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001925
Chris Lattner95b0ff42010-04-23 00:50:50 +00001926 if (Lex.getKind() != lltok::kw_align)
1927 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001928
Chris Lattner95b0ff42010-04-23 00:50:50 +00001929 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001930 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931
Devang Patelea8a4b92009-09-17 23:04:48 +00001932 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933}
1934
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001935/// ParseOptionalCommaAddrSpace
1936/// ::=
1937/// ::= ',' addrspace(1)
1938///
1939/// This returns with AteExtraComma set to true if it ate an excess comma at the
1940/// end.
1941bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1942 LocTy &Loc,
1943 bool &AteExtraComma) {
1944 AteExtraComma = false;
1945 while (EatIfPresent(lltok::comma)) {
1946 // Metadata at the end is an early exit.
1947 if (Lex.getKind() == lltok::MetadataVar) {
1948 AteExtraComma = true;
1949 return false;
1950 }
1951
1952 Loc = Lex.getLoc();
1953 if (Lex.getKind() != lltok::kw_addrspace)
1954 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1955
1956 if (ParseOptionalAddrSpace(AddrSpace))
1957 return true;
1958 }
1959
1960 return false;
1961}
1962
George Burgess IV278199f2016-04-12 01:05:35 +00001963bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1964 Optional<unsigned> &HowManyArg) {
1965 Lex.Lex();
1966
1967 auto StartParen = Lex.getLoc();
1968 if (!EatIfPresent(lltok::lparen))
1969 return Error(StartParen, "expected '('");
1970
1971 if (ParseUInt32(BaseSizeArg))
1972 return true;
1973
1974 if (EatIfPresent(lltok::comma)) {
1975 auto HowManyAt = Lex.getLoc();
1976 unsigned HowMany;
1977 if (ParseUInt32(HowMany))
1978 return true;
1979 if (HowMany == BaseSizeArg)
1980 return Error(HowManyAt,
1981 "'allocsize' indices can't refer to the same parameter");
1982 HowManyArg = HowMany;
1983 } else
1984 HowManyArg = None;
1985
1986 auto EndParen = Lex.getLoc();
1987 if (!EatIfPresent(lltok::rparen))
1988 return Error(EndParen, "expected ')'");
1989 return false;
1990}
1991
Eli Friedmanfee02c62011-07-25 23:16:38 +00001992/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001993/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00001994/// else: ::=
1995///
1996/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001997bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00001998 AtomicOrdering &Ordering) {
1999 if (!isAtomic)
2000 return false;
2001
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002002 return ParseScope(SSID) || ParseOrdering(Ordering);
2003}
Tim Northovere94a5182014-03-11 10:48:52 +00002004
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002005/// ParseScope
2006/// ::= syncscope("singlethread" | "<target scope>")?
2007///
2008/// This sets synchronization scope ID to the ID of the parsed value.
2009bool LLParser::ParseScope(SyncScope::ID &SSID) {
2010 SSID = SyncScope::System;
2011 if (EatIfPresent(lltok::kw_syncscope)) {
2012 auto StartParenAt = Lex.getLoc();
2013 if (!EatIfPresent(lltok::lparen))
2014 return Error(StartParenAt, "Expected '(' in syncscope");
2015
2016 std::string SSN;
2017 auto SSNAt = Lex.getLoc();
2018 if (ParseStringConstant(SSN))
2019 return Error(SSNAt, "Expected synchronization scope name");
2020
2021 auto EndParenAt = Lex.getLoc();
2022 if (!EatIfPresent(lltok::rparen))
2023 return Error(EndParenAt, "Expected ')' in syncscope");
2024
2025 SSID = Context.getOrInsertSyncScopeID(SSN);
2026 }
2027
2028 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002029}
2030
2031/// ParseOrdering
2032/// ::= AtomicOrdering
2033///
2034/// This sets Ordering to the parsed value.
2035bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002036 switch (Lex.getKind()) {
2037 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002038 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2039 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2040 // Not specified yet:
2041 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2042 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2043 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2044 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2045 case lltok::kw_seq_cst:
2046 Ordering = AtomicOrdering::SequentiallyConsistent;
2047 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002048 }
2049 Lex.Lex();
2050 return false;
2051}
2052
Charles Davisbe5557e2010-02-12 00:31:15 +00002053/// ParseOptionalStackAlignment
2054/// ::= /* empty */
2055/// ::= 'alignstack' '(' 4 ')'
2056bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2057 Alignment = 0;
2058 if (!EatIfPresent(lltok::kw_alignstack))
2059 return false;
2060 LocTy ParenLoc = Lex.getLoc();
2061 if (!EatIfPresent(lltok::lparen))
2062 return Error(ParenLoc, "expected '('");
2063 LocTy AlignLoc = Lex.getLoc();
2064 if (ParseUInt32(Alignment)) return true;
2065 ParenLoc = Lex.getLoc();
2066 if (!EatIfPresent(lltok::rparen))
2067 return Error(ParenLoc, "expected ')'");
2068 if (!isPowerOf2_32(Alignment))
2069 return Error(AlignLoc, "stack alignment is not a power of two");
2070 return false;
2071}
Devang Patelea8a4b92009-09-17 23:04:48 +00002072
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002073/// ParseIndexList - This parses the index list for an insert/extractvalue
2074/// instruction. This sets AteExtraComma in the case where we eat an extra
2075/// comma at the end of the line and find that it is followed by metadata.
2076/// Clients that don't allow metadata can call the version of this function that
2077/// only takes one argument.
2078///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079/// ParseIndexList
2080/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002081///
2082bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2083 bool &AteExtraComma) {
2084 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002085
Chris Lattnerac161bf2009-01-02 07:01:27 +00002086 if (Lex.getKind() != lltok::comma)
2087 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002088
Chris Lattner3822f632009-01-02 08:05:26 +00002089 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002090 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002091 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002092 AteExtraComma = true;
2093 return false;
2094 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002095 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002096 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002097 Indices.push_back(Idx);
2098 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002099
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 return false;
2101}
2102
2103//===----------------------------------------------------------------------===//
2104// Type Parsing.
2105//===----------------------------------------------------------------------===//
2106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002107/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002108bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002109 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110 switch (Lex.getKind()) {
2111 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002112 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002114 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002116 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002119 // Type ::= StructType
2120 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 return true;
2122 break;
2123 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002124 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 Lex.Lex(); // eat the lsquare.
2126 if (ParseArrayVectorType(Result, false))
2127 return true;
2128 break;
2129 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002130 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002131 Lex.Lex();
2132 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002133 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002134 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 } else if (ParseArrayVectorType(Result, true))
2137 return true;
2138 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002139 case lltok::LocalVar: {
2140 // Type ::= %foo
2141 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002142
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002143 // If the type hasn't been defined yet, create a forward definition and
2144 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002145 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002146 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002147 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002149 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 Lex.Lex();
2151 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002152 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002153
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002154 case lltok::LocalVarID: {
2155 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002156 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002157
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002158 // If the type hasn't been defined yet, create a forward definition and
2159 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002160 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002161 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002162 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002163 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002164 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002165 Lex.Lex();
2166 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 }
2168 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002169
2170 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002171 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 switch (Lex.getKind()) {
2173 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002174 default:
2175 if (!AllowVoid && Result->isVoidTy())
2176 return Error(TypeLoc, "void type only allowed for function results");
2177 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002179 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002181 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002183 if (Result->isVoidTy())
2184 return TokError("pointers to void are invalid - use i8* instead");
2185 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002186 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002187 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002188 Lex.Lex();
2189 break;
2190
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002191 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002193 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002195 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002196 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002197 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002198 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002199 unsigned AddrSpace;
2200 if (ParseOptionalAddrSpace(AddrSpace) ||
2201 ParseToken(lltok::star, "expected '*' in address space"))
2202 return true;
2203
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002204 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 break;
2206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002207
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2209 case lltok::lparen:
2210 if (ParseFunctionType(Result))
2211 return true;
2212 break;
2213 }
2214 }
2215}
2216
2217/// ParseParameterList
2218/// ::= '(' ')'
2219/// ::= '(' Arg (',' Arg)* ')'
2220/// Arg
2221/// ::= Type OptionalAttributes Value OptionalAttributes
2222bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002223 PerFunctionState &PFS, bool IsMustTailCall,
2224 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 if (ParseToken(lltok::lparen, "expected '(' in call"))
2226 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 while (Lex.getKind() != lltok::rparen) {
2229 // If this isn't the first argument, we need a comma.
2230 if (!ArgList.empty() &&
2231 ParseToken(lltok::comma, "expected ',' in argument list"))
2232 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Reid Kleckner83498642014-08-26 00:33:28 +00002234 // Parse an ellipsis if this is a musttail call in a variadic function.
2235 if (Lex.getKind() == lltok::dotdotdot) {
2236 const char *Msg = "unexpected ellipsis in argument list for ";
2237 if (!IsMustTailCall)
2238 return TokError(Twine(Msg) + "non-musttail call");
2239 if (!InVarArgsFunc)
2240 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2241 Lex.Lex(); // Lex the '...', it is purely for readability.
2242 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2243 }
2244
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 // Parse the argument.
2246 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002247 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002248 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002250 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002252
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002253 if (ArgTy->isMetadataTy()) {
2254 if (ParseMetadataAsValue(V, PFS))
2255 return true;
2256 } else {
2257 // Otherwise, handle normal operands.
2258 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2259 return true;
2260 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002261 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002262 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 }
2264
Reid Kleckner83498642014-08-26 00:33:28 +00002265 if (IsMustTailCall && InVarArgsFunc)
2266 return TokError("expected '...' at end of argument list for musttail call "
2267 "in varargs function");
2268
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269 Lex.Lex(); // Lex the ')'.
2270 return false;
2271}
2272
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002273/// ParseOptionalOperandBundles
2274/// ::= /*empty*/
2275/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2276///
2277/// OperandBundle
2278/// ::= bundle-tag '(' ')'
2279/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2280///
2281/// bundle-tag ::= String Constant
2282bool LLParser::ParseOptionalOperandBundles(
2283 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2284 LocTy BeginLoc = Lex.getLoc();
2285 if (!EatIfPresent(lltok::lsquare))
2286 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002288 while (Lex.getKind() != lltok::rsquare) {
2289 // If this isn't the first operand bundle, we need a comma.
2290 if (!BundleList.empty() &&
2291 ParseToken(lltok::comma, "expected ',' in input list"))
2292 return true;
2293
2294 std::string Tag;
2295 if (ParseStringConstant(Tag))
2296 return true;
2297
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002298 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2299 return true;
2300
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002301 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002302 while (Lex.getKind() != lltok::rparen) {
2303 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002304 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002305 ParseToken(lltok::comma, "expected ',' in input list"))
2306 return true;
2307
2308 Type *Ty = nullptr;
2309 Value *Input = nullptr;
2310 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2311 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002312 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002313 }
2314
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002315 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2316
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002317 Lex.Lex(); // Lex the ')'.
2318 }
2319
2320 if (BundleList.empty())
2321 return Error(BeginLoc, "operand bundle set must not be empty");
2322
2323 Lex.Lex(); // Lex the ']'.
2324 return false;
2325}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326
Chris Lattner2ed06b42009-01-05 18:34:07 +00002327/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002328/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329/// ::= '(' ArgTypeListI ')'
2330/// ArgTypeListI
2331/// ::= /*empty*/
2332/// ::= '...'
2333/// ::= ArgTypeList ',' '...'
2334/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002335///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002336bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2337 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338 isVarArg = false;
2339 assert(Lex.getKind() == lltok::lparen);
2340 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002341
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 if (Lex.getKind() == lltok::rparen) {
2343 // empty
2344 } else if (Lex.getKind() == lltok::dotdotdot) {
2345 isVarArg = true;
2346 Lex.Lex();
2347 } else {
2348 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002349 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002350 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002353 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002354 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
Chris Lattnerfdd87902009-10-05 05:54:46 +00002356 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002357 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002358
Chris Lattnerdef19492011-06-17 06:36:20 +00002359 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002360 Name = Lex.getStrVal();
2361 Lex.Lex();
2362 }
Chris Lattner3822f632009-01-02 08:05:26 +00002363
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002364 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002365 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002366
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002367 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002368 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002369 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370
Chris Lattner3822f632009-01-02 08:05:26 +00002371 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002373 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 break;
2376 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Chris Lattnerac161bf2009-01-02 07:01:27 +00002378 // Otherwise must be an argument type.
2379 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002380 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002381
Chris Lattnerfdd87902009-10-05 05:54:46 +00002382 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002383 return Error(TypeLoc, "argument can not have void type");
2384
Chris Lattnerdef19492011-06-17 06:36:20 +00002385 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002386 Name = Lex.getStrVal();
2387 Lex.Lex();
2388 } else {
2389 Name = "";
2390 }
Chris Lattner3822f632009-01-02 08:05:26 +00002391
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002392 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002393 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002395 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002396 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002397 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 }
2399 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002400
Chris Lattner3822f632009-01-02 08:05:26 +00002401 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002403
Chris Lattnerac161bf2009-01-02 07:01:27 +00002404/// ParseFunctionType
2405/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 assert(Lex.getKind() == lltok::lparen);
2408
Chris Lattnerce473c72009-01-05 08:04:33 +00002409 if (!FunctionType::isValidReturnType(Result))
2410 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002411
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002412 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002414 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 // Reject names on the arguments lists.
2418 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2419 if (!ArgList[i].Name.empty())
2420 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002421 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002422 return Error(ArgList[i].Loc,
2423 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002425
Jay Foadb804a2b2011-07-12 14:06:48 +00002426 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002428 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002429
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 return false;
2432}
2433
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002434/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2435/// other structs.
2436bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2437 SmallVector<Type*, 8> Elts;
2438 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002439
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002440 Result = StructType::get(Context, Elts, Packed);
2441 return false;
2442}
2443
2444/// ParseStructDefinition - Parse a struct in a 'type' definition.
2445bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2446 std::pair<Type*, LocTy> &Entry,
2447 Type *&ResultTy) {
2448 // If the type was already defined, diagnose the redefinition.
2449 if (Entry.first && !Entry.second.isValid())
2450 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002451
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002452 // If we have opaque, just return without filling in the definition for the
2453 // struct. This counts as a definition as far as the .ll file goes.
2454 if (EatIfPresent(lltok::kw_opaque)) {
2455 // This type is being defined, so clear the location to indicate this.
2456 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002457
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002458 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002459 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002460 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002461 ResultTy = Entry.first;
2462 return false;
2463 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002464
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002465 // If the type starts with '<', then it is either a packed struct or a vector.
2466 bool isPacked = EatIfPresent(lltok::less);
2467
2468 // If we don't have a struct, then we have a random type alias, which we
2469 // accept for compatibility with old files. These types are not allowed to be
2470 // forward referenced and not allowed to be recursive.
2471 if (Lex.getKind() != lltok::lbrace) {
2472 if (Entry.first)
2473 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002474
Craig Topper2617dcc2014-04-15 06:32:26 +00002475 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002476 if (isPacked)
2477 return ParseArrayVectorType(ResultTy, true);
2478 return ParseType(ResultTy);
2479 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002480
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002481 // This type is being defined, so clear the location to indicate this.
2482 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002483
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002484 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002485 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002486 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002487
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002488 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002489
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002490 SmallVector<Type*, 8> Body;
2491 if (ParseStructBody(Body) ||
2492 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2493 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002494
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002495 STy->setBody(Body, isPacked);
2496 ResultTy = STy;
2497 return false;
2498}
2499
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002501/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002503/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002505/// ::= '<' '{' Type (',' Type)* '}' '>'
2506bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 assert(Lex.getKind() == lltok::lbrace);
2508 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002509
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002510 // Handle the empty struct.
2511 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002513
Chris Lattnerf880ca22009-03-09 04:49:14 +00002514 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002515 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002516 if (ParseType(Ty)) return true;
2517 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002518
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002519 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002520 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
Chris Lattner3822f632009-01-02 08:05:26 +00002522 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002523 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002524 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002525
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002526 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002527 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002528
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002529 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002530 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002531
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002532 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533}
2534
2535/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2536/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002537/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002538/// ::= '[' APSINTVAL 'x' Types ']'
2539/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002540bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2542 Lex.getAPSIntVal().getBitWidth() > 64)
2543 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 LocTy SizeLoc = Lex.getLoc();
2546 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002547 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002548
Chris Lattner3822f632009-01-02 08:05:26 +00002549 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2550 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002551
2552 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002553 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002554 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002555
Chris Lattner3822f632009-01-02 08:05:26 +00002556 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2557 "expected end of sequential type"))
2558 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002559
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002561 if (Size == 0)
2562 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 if ((unsigned)Size != Size)
2564 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002565 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002566 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002567 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002569 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002571 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 }
2573 return false;
2574}
2575
2576//===----------------------------------------------------------------------===//
2577// Function Semantic Analysis.
2578//===----------------------------------------------------------------------===//
2579
Chris Lattner3432c622009-10-28 03:39:23 +00002580LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2581 int functionNumber)
2582 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002583
2584 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002585 for (Argument &A : F.args())
2586 if (!A.hasName())
2587 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588}
2589
2590LLParser::PerFunctionState::~PerFunctionState() {
2591 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002592
David Blaikie9ebdc692015-09-21 21:07:50 +00002593 for (const auto &P : ForwardRefVals) {
2594 if (isa<BasicBlock>(P.second.first))
2595 continue;
2596 P.second.first->replaceAllUsesWith(
2597 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002598 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002599 }
2600
2601 for (const auto &P : ForwardRefValIDs) {
2602 if (isa<BasicBlock>(P.second.first))
2603 continue;
2604 P.second.first->replaceAllUsesWith(
2605 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002606 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002607 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608}
2609
Chris Lattner3432c622009-10-28 03:39:23 +00002610bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002611 if (!ForwardRefVals.empty())
2612 return P.Error(ForwardRefVals.begin()->second.second,
2613 "use of undefined value '%" + ForwardRefVals.begin()->first +
2614 "'");
2615 if (!ForwardRefValIDs.empty())
2616 return P.Error(ForwardRefValIDs.begin()->second.second,
2617 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002618 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 return false;
2620}
2621
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002622static bool isValidVariableType(Module *M, Type *Ty, Value *Val, bool IsCall) {
2623 if (Val->getType() == Ty)
2624 return true;
2625 // For calls we also accept variables in the program address space
2626 if (IsCall && isa<PointerType>(Ty)) {
2627 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
2628 M->getDataLayout().getProgramAddressSpace());
2629 if (Val->getType() == TyInProgAS)
2630 return true;
2631 }
2632 return false;
2633}
2634
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635/// GetVal - Get a value with the specified name or ID, creating a
2636/// forward reference record if needed. This can return null if the value
2637/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002638Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002639 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002641 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002642
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 // If this is a forward reference for the value, see if we already created a
2644 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002645 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002646 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 if (I != ForwardRefVals.end())
2648 Val = I->second.first;
2649 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002650
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 // If we have the value in the symbol table or fwd-ref table, return it.
2652 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002653 if (isValidVariableType(P.M, Ty, Val, IsCall))
2654 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002655 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656 P.Error(Loc, "'%" + Name + "' is not a basic block");
2657 else
2658 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002659 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002660 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002662
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002664 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002666 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002668
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 // Otherwise, create a new forward reference for this value and remember it.
2670 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002671 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002672 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002673 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002674 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002675 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002676
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2678 return FwdVal;
2679}
2680
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002681Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2682 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002684 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002685
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 // If this is a forward reference for the value, see if we already created a
2687 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002688 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002689 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 if (I != ForwardRefValIDs.end())
2691 Val = I->second.first;
2692 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 // If we have the value in the symbol table or fwd-ref table, return it.
2695 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002696 if (isValidVariableType(P.M, Ty, Val, IsCall))
2697 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002698 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002699 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002701 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002702 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002703 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002706 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002708 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002710
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 // Otherwise, create a new forward reference for this value and remember it.
2712 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002713 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002714 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002715 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002716 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002718
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2720 return FwdVal;
2721}
2722
2723/// SetInstName - After an instruction is parsed and inserted into its
2724/// basic block, this installs its name.
2725bool LLParser::PerFunctionState::SetInstName(int NameID,
2726 const std::string &NameStr,
2727 LocTy NameLoc, Instruction *Inst) {
2728 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002729 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730 if (NameID != -1 || !NameStr.empty())
2731 return P.Error(NameLoc, "instructions returning void cannot have a name");
2732 return false;
2733 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002734
Chris Lattnerac161bf2009-01-02 07:01:27 +00002735 // If this was a numbered instruction, verify that the instruction is the
2736 // expected value and resolve any forward references.
2737 if (NameStr.empty()) {
2738 // If neither a name nor an ID was specified, just use the next ID.
2739 if (NameID == -1)
2740 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 if (unsigned(NameID) != NumberedVals.size())
2743 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002744 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002745
David Blaikie9ebdc692015-09-21 21:07:50 +00002746 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002747 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002748 Value *Sentinel = FI->second.first;
2749 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002751 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002752
2753 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002754 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 ForwardRefValIDs.erase(FI);
2756 }
2757
2758 NumberedVals.push_back(Inst);
2759 return false;
2760 }
2761
2762 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002763 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002764 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002765 Value *Sentinel = FI->second.first;
2766 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002767 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002768 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002769
2770 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002771 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 ForwardRefVals.erase(FI);
2773 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 // Set the name on the instruction.
2776 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002777
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002778 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002779 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 NameStr + "'");
2781 return false;
2782}
2783
2784/// GetBB - Get a basic block with the specified name or ID, creating a
2785/// forward reference record if needed.
2786BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2787 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002788 return dyn_cast_or_null<BasicBlock>(
2789 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790}
2791
2792BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002793 return dyn_cast_or_null<BasicBlock>(
2794 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002795}
2796
2797/// DefineBB - Define the specified basic block, which is either named or
2798/// unnamed. If there is an error, this returns null otherwise it returns
2799/// the block being defined.
2800BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2801 LocTy Loc) {
2802 BasicBlock *BB;
2803 if (Name.empty())
2804 BB = GetBB(NumberedVals.size(), Loc);
2805 else
2806 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002807 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 // Move the block to the end of the function. Forward ref'd blocks are
2810 // inserted wherever they happen to be referenced.
2811 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 // Remove the block from forward ref sets.
2814 if (Name.empty()) {
2815 ForwardRefValIDs.erase(NumberedVals.size());
2816 NumberedVals.push_back(BB);
2817 } else {
2818 // BB forward references are already in the function symbol table.
2819 ForwardRefVals.erase(Name);
2820 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002821
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 return BB;
2823}
2824
2825//===----------------------------------------------------------------------===//
2826// Constants.
2827//===----------------------------------------------------------------------===//
2828
2829/// ParseValID - Parse an abstract value that doesn't necessarily have a
2830/// type implied. For example, if we parse "4" we don't know what integer type
2831/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002832/// sanity. PFS is used to convert function-local operands of metadata (since
2833/// metadata operands are not just parsed here but also converted to values).
2834/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002835bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002836 ID.Loc = Lex.getLoc();
2837 switch (Lex.getKind()) {
2838 default: return TokError("expected value token");
2839 case lltok::GlobalID: // @42
2840 ID.UIntVal = Lex.getUIntVal();
2841 ID.Kind = ValID::t_GlobalID;
2842 break;
2843 case lltok::GlobalVar: // @foo
2844 ID.StrVal = Lex.getStrVal();
2845 ID.Kind = ValID::t_GlobalName;
2846 break;
2847 case lltok::LocalVarID: // %42
2848 ID.UIntVal = Lex.getUIntVal();
2849 ID.Kind = ValID::t_LocalID;
2850 break;
2851 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 ID.StrVal = Lex.getStrVal();
2853 ID.Kind = ValID::t_LocalName;
2854 break;
2855 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002856 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 ID.Kind = ValID::t_APSInt;
2858 break;
2859 case lltok::APFloat:
2860 ID.APFloatVal = Lex.getAPFloatVal();
2861 ID.Kind = ValID::t_APFloat;
2862 break;
2863 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002864 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 ID.Kind = ValID::t_Constant;
2866 break;
2867 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002868 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 ID.Kind = ValID::t_Constant;
2870 break;
2871 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2872 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2873 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002874 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002875
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 case lltok::lbrace: {
2877 // ValID ::= '{' ConstVector '}'
2878 Lex.Lex();
2879 SmallVector<Constant*, 16> Elts;
2880 if (ParseGlobalValueVector(Elts) ||
2881 ParseToken(lltok::rbrace, "expected end of struct constant"))
2882 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002883
David Blaikieadbda4b2015-08-03 20:08:41 +00002884 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002885 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002886 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2887 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002888 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 return false;
2890 }
2891 case lltok::less: {
2892 // ValID ::= '<' ConstVector '>' --> Vector.
2893 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2894 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002895 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002896
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 SmallVector<Constant*, 16> Elts;
2898 LocTy FirstEltLoc = Lex.getLoc();
2899 if (ParseGlobalValueVector(Elts) ||
2900 (isPackedStruct &&
2901 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2902 ParseToken(lltok::greater, "expected end of constant"))
2903 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002904
Chris Lattnerac161bf2009-01-02 07:01:27 +00002905 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002906 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2907 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2908 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002909 ID.UIntVal = Elts.size();
2910 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002911 return false;
2912 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002913
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 if (Elts.empty())
2915 return Error(ID.Loc, "constant vector must not be empty");
2916
Duncan Sands9dff9be2010-02-15 16:12:20 +00002917 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002918 !Elts[0]->getType()->isFloatingPointTy() &&
2919 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002920 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002921 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002922
Chris Lattnerac161bf2009-01-02 07:01:27 +00002923 // Verify that all the vector elements have the same type.
2924 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2925 if (Elts[i]->getType() != Elts[0]->getType())
2926 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002927 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002928 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002929
Chris Lattner69229312011-02-15 00:14:00 +00002930 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 ID.Kind = ValID::t_Constant;
2932 return false;
2933 }
2934 case lltok::lsquare: { // Array Constant
2935 Lex.Lex();
2936 SmallVector<Constant*, 16> Elts;
2937 LocTy FirstEltLoc = Lex.getLoc();
2938 if (ParseGlobalValueVector(Elts) ||
2939 ParseToken(lltok::rsquare, "expected end of array constant"))
2940 return true;
2941
2942 // Handle empty element.
2943 if (Elts.empty()) {
2944 // Use undef instead of an array because it's inconvenient to determine
2945 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002946 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002947 return false;
2948 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002949
Chris Lattnerac161bf2009-01-02 07:01:27 +00002950 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002951 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002952 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002953
Owen Anderson4056ca92009-07-29 22:17:13 +00002954 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002955
Chris Lattnerac161bf2009-01-02 07:01:27 +00002956 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002957 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002958 if (Elts[i]->getType() != Elts[0]->getType())
2959 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002960 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002961 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002963
Jay Foad83be3612011-06-22 09:24:39 +00002964 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002965 ID.Kind = ValID::t_Constant;
2966 return false;
2967 }
2968 case lltok::kw_c: // c "foo"
2969 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002970 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2971 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2973 ID.Kind = ValID::t_Constant;
2974 return false;
2975
2976 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002977 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2978 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002979 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002980 Lex.Lex();
2981 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002982 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002983 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002984 ParseStringConstant(ID.StrVal) ||
2985 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 ParseToken(lltok::StringConstant, "expected constraint string"))
2987 return true;
2988 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002989 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002990 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002991 ID.Kind = ValID::t_InlineAsm;
2992 return false;
2993 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002994
Chris Lattner3432c622009-10-28 03:39:23 +00002995 case lltok::kw_blockaddress: {
2996 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2997 Lex.Lex();
2998
2999 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003000
Chris Lattner3432c622009-10-28 03:39:23 +00003001 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3002 ParseValID(Fn) ||
3003 ParseToken(lltok::comma, "expected comma in block address expression")||
3004 ParseValID(Label) ||
3005 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3006 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003007
Chris Lattner3432c622009-10-28 03:39:23 +00003008 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3009 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003010 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003011 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003012
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003013 // Try to find the function (but skip it if it's forward-referenced).
3014 GlobalValue *GV = nullptr;
3015 if (Fn.Kind == ValID::t_GlobalID) {
3016 if (Fn.UIntVal < NumberedVals.size())
3017 GV = NumberedVals[Fn.UIntVal];
3018 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3019 GV = M->getNamedValue(Fn.StrVal);
3020 }
3021 Function *F = nullptr;
3022 if (GV) {
3023 // Confirm that it's actually a function with a definition.
3024 if (!isa<Function>(GV))
3025 return Error(Fn.Loc, "expected function name in blockaddress");
3026 F = cast<Function>(GV);
3027 if (F->isDeclaration())
3028 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3029 }
3030
3031 if (!F) {
3032 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003033 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003034 ForwardRefBlockAddresses.insert(std::make_pair(
3035 std::move(Fn),
3036 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003037 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3038 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003039 if (!FwdRef)
3040 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3041 GlobalValue::InternalLinkage, nullptr, "");
3042 ID.ConstantVal = FwdRef;
3043 ID.Kind = ValID::t_Constant;
3044 return false;
3045 }
3046
3047 // We found the function; now find the basic block. Don't use PFS, since we
3048 // might be inside a constant expression.
3049 BasicBlock *BB;
3050 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3051 if (Label.Kind == ValID::t_LocalID)
3052 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3053 else
3054 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3055 if (!BB)
3056 return Error(Label.Loc, "referenced value is not a basic block");
3057 } else {
3058 if (Label.Kind == ValID::t_LocalID)
3059 return Error(Label.Loc, "cannot take address of numeric label after "
3060 "the function is defined");
3061 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003062 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003063 if (!BB)
3064 return Error(Label.Loc, "referenced value is not a basic block");
3065 }
3066
3067 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003068 ID.Kind = ValID::t_Constant;
3069 return false;
3070 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003071
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 case lltok::kw_trunc:
3073 case lltok::kw_zext:
3074 case lltok::kw_sext:
3075 case lltok::kw_fptrunc:
3076 case lltok::kw_fpext:
3077 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003078 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 case lltok::kw_uitofp:
3080 case lltok::kw_sitofp:
3081 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003082 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003085 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003086 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 Constant *SrcVal;
3088 Lex.Lex();
3089 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3090 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003091 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003092 ParseType(DestTy) ||
3093 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3094 return true;
3095 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3096 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003097 getTypeString(SrcVal->getType()) + "' to '" +
3098 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003099 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003100 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003101 ID.Kind = ValID::t_Constant;
3102 return false;
3103 }
3104 case lltok::kw_extractvalue: {
3105 Lex.Lex();
3106 Constant *Val;
3107 SmallVector<unsigned, 4> Indices;
3108 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3109 ParseGlobalTypeAndValue(Val) ||
3110 ParseIndexList(Indices) ||
3111 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3112 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003113
Chris Lattner392be582010-02-12 20:49:41 +00003114 if (!Val->getType()->isAggregateType())
3115 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003116 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003117 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003118 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003119 ID.Kind = ValID::t_Constant;
3120 return false;
3121 }
3122 case lltok::kw_insertvalue: {
3123 Lex.Lex();
3124 Constant *Val0, *Val1;
3125 SmallVector<unsigned, 4> Indices;
3126 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3127 ParseGlobalTypeAndValue(Val0) ||
3128 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3129 ParseGlobalTypeAndValue(Val1) ||
3130 ParseIndexList(Indices) ||
3131 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3132 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003133 if (!Val0->getType()->isAggregateType())
3134 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003135 Type *IndexedType =
3136 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3137 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003138 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003139 if (IndexedType != Val1->getType())
3140 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3141 getTypeString(Val1->getType()) +
3142 "' instead of '" + getTypeString(IndexedType) +
3143 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003144 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003145 ID.Kind = ValID::t_Constant;
3146 return false;
3147 }
3148 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003149 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003150 unsigned PredVal, Opc = Lex.getUIntVal();
3151 Constant *Val0, *Val1;
3152 Lex.Lex();
3153 if (ParseCmpPredicate(PredVal, Opc) ||
3154 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3155 ParseGlobalTypeAndValue(Val0) ||
3156 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3157 ParseGlobalTypeAndValue(Val1) ||
3158 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3159 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003160
Chris Lattnerac161bf2009-01-02 07:01:27 +00003161 if (Val0->getType() != Val1->getType())
3162 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003163
Chris Lattnerac161bf2009-01-02 07:01:27 +00003164 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003165
Chris Lattnerac161bf2009-01-02 07:01:27 +00003166 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003167 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003168 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003169 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003170 } else {
3171 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003172 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003173 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003175 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 }
3177 ID.Kind = ValID::t_Constant;
3178 return false;
3179 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003180
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 // Binary Operators.
3182 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003183 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003184 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003185 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003186 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003187 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003188 case lltok::kw_udiv:
3189 case lltok::kw_sdiv:
3190 case lltok::kw_fdiv:
3191 case lltok::kw_urem:
3192 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003193 case lltok::kw_frem:
3194 case lltok::kw_shl:
3195 case lltok::kw_lshr:
3196 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003197 bool NUW = false;
3198 bool NSW = false;
3199 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 unsigned Opc = Lex.getUIntVal();
3201 Constant *Val0, *Val1;
3202 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003203 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003204 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3205 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003206 if (EatIfPresent(lltok::kw_nuw))
3207 NUW = true;
3208 if (EatIfPresent(lltok::kw_nsw)) {
3209 NSW = true;
3210 if (EatIfPresent(lltok::kw_nuw))
3211 NUW = true;
3212 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003213 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3214 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003215 if (EatIfPresent(lltok::kw_exact))
3216 Exact = true;
3217 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3219 ParseGlobalTypeAndValue(Val0) ||
3220 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3221 ParseGlobalTypeAndValue(Val1) ||
3222 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3223 return true;
3224 if (Val0->getType() != Val1->getType())
3225 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003226 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003227 if (NUW)
3228 return Error(ModifierLoc, "nuw only applies to integer operations");
3229 if (NSW)
3230 return Error(ModifierLoc, "nsw only applies to integer operations");
3231 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003232 // Check that the type is valid for the operator.
3233 switch (Opc) {
3234 case Instruction::Add:
3235 case Instruction::Sub:
3236 case Instruction::Mul:
3237 case Instruction::UDiv:
3238 case Instruction::SDiv:
3239 case Instruction::URem:
3240 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003241 case Instruction::Shl:
3242 case Instruction::AShr:
3243 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003244 if (!Val0->getType()->isIntOrIntVectorTy())
3245 return Error(ID.Loc, "constexpr requires integer operands");
3246 break;
3247 case Instruction::FAdd:
3248 case Instruction::FSub:
3249 case Instruction::FMul:
3250 case Instruction::FDiv:
3251 case Instruction::FRem:
3252 if (!Val0->getType()->isFPOrFPVectorTy())
3253 return Error(ID.Loc, "constexpr requires fp operands");
3254 break;
3255 default: llvm_unreachable("Unknown binary operator!");
3256 }
Dan Gohman1b849082009-09-07 23:54:19 +00003257 unsigned Flags = 0;
3258 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3259 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003260 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003261 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003262 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003263 ID.Kind = ValID::t_Constant;
3264 return false;
3265 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003266
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003268 case lltok::kw_and:
3269 case lltok::kw_or:
3270 case lltok::kw_xor: {
3271 unsigned Opc = Lex.getUIntVal();
3272 Constant *Val0, *Val1;
3273 Lex.Lex();
3274 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3275 ParseGlobalTypeAndValue(Val0) ||
3276 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3277 ParseGlobalTypeAndValue(Val1) ||
3278 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3279 return true;
3280 if (Val0->getType() != Val1->getType())
3281 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003282 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003283 return Error(ID.Loc,
3284 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003285 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003286 ID.Kind = ValID::t_Constant;
3287 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003288 }
3289
Chris Lattnerac161bf2009-01-02 07:01:27 +00003290 case lltok::kw_getelementptr:
3291 case lltok::kw_shufflevector:
3292 case lltok::kw_insertelement:
3293 case lltok::kw_extractelement:
3294 case lltok::kw_select: {
3295 unsigned Opc = Lex.getUIntVal();
3296 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003297 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003298 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003299 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003300
Dan Gohman1639c392009-07-27 21:53:46 +00003301 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003302 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003303
3304 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3305 return true;
3306
3307 LocTy ExplicitTypeLoc = Lex.getLoc();
3308 if (Opc == Instruction::GetElementPtr) {
3309 if (ParseType(Ty) ||
3310 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3311 return true;
3312 }
3313
Peter Collingbourned93620b2016-11-10 22:34:55 +00003314 Optional<unsigned> InRangeOp;
3315 if (ParseGlobalValueVector(
3316 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003317 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3318 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003319
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003321 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003322 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003323 return Error(ID.Loc, "base of getelementptr must be a pointer");
3324
3325 Type *BaseType = Elts[0]->getType();
3326 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003327 if (Ty != BasePointerType->getElementType())
3328 return Error(
3329 ExplicitTypeLoc,
3330 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003331
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003332 unsigned GEPWidth =
3333 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3334
Jay Foaded8db7d2011-07-21 14:31:17 +00003335 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003336 for (Constant *Val : Indices) {
3337 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003338 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003339 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003340 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003341 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003342 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003343 return Error(
3344 ID.Loc,
3345 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003346 // GEPWidth may have been unknown because the base is a scalar,
3347 // but it is known now.
3348 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003349 }
3350 }
3351
Craig Toppere3dcce92015-08-01 22:20:21 +00003352 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003353 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003354 return Error(ID.Loc, "base element of getelementptr must be sized");
3355
David Blaikie4a2e73b2015-04-02 18:55:32 +00003356 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003357 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003358
3359 if (InRangeOp) {
3360 if (*InRangeOp == 0)
3361 return Error(ID.Loc,
3362 "inrange keyword may not appear on pointer operand");
3363 --*InRangeOp;
3364 }
3365
3366 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3367 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003368 } else if (Opc == Instruction::Select) {
3369 if (Elts.size() != 3)
3370 return Error(ID.Loc, "expected three operands to select");
3371 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3372 Elts[2]))
3373 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003374 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003375 } else if (Opc == Instruction::ShuffleVector) {
3376 if (Elts.size() != 3)
3377 return Error(ID.Loc, "expected three operands to shufflevector");
3378 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3379 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003380 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003381 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003382 } else if (Opc == Instruction::ExtractElement) {
3383 if (Elts.size() != 2)
3384 return Error(ID.Loc, "expected two operands to extractelement");
3385 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3386 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003387 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003388 } else {
3389 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3390 if (Elts.size() != 3)
3391 return Error(ID.Loc, "expected three operands to insertelement");
3392 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3393 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003394 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003395 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003396 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003397
Chris Lattnerac161bf2009-01-02 07:01:27 +00003398 ID.Kind = ValID::t_Constant;
3399 return false;
3400 }
3401 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003402
Chris Lattnerac161bf2009-01-02 07:01:27 +00003403 Lex.Lex();
3404 return false;
3405}
3406
3407/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003408bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003409 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003410 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003411 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003412 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003413 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003414 if (V && !(C = dyn_cast<Constant>(V)))
3415 return Error(ID.Loc, "global values must be constants");
3416 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003417}
3418
Victor Hernandez9d75c962010-01-11 22:31:58 +00003419bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003420 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003421 return ParseType(Ty) ||
3422 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003423}
3424
Rafael Espindola83a362c2015-01-06 22:55:16 +00003425bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003426 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003427
3428 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003429 if (!EatIfPresent(lltok::kw_comdat))
3430 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003431
3432 if (EatIfPresent(lltok::lparen)) {
3433 if (Lex.getKind() != lltok::ComdatVar)
3434 return TokError("expected comdat variable");
3435 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3436 Lex.Lex();
3437 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3438 return true;
3439 } else {
3440 if (GlobalName.empty())
3441 return TokError("comdat cannot be unnamed");
3442 C = getComdat(GlobalName, KwLoc);
3443 }
3444
David Majnemerdad0a642014-06-27 18:19:56 +00003445 return false;
3446}
3447
Victor Hernandez9d75c962010-01-11 22:31:58 +00003448/// ParseGlobalValueVector
3449/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003450/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3451bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3452 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003453 // Empty list.
3454 if (Lex.getKind() == lltok::rbrace ||
3455 Lex.getKind() == lltok::rsquare ||
3456 Lex.getKind() == lltok::greater ||
3457 Lex.getKind() == lltok::rparen)
3458 return false;
3459
Peter Collingbourned93620b2016-11-10 22:34:55 +00003460 do {
3461 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3462 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003463
Peter Collingbourned93620b2016-11-10 22:34:55 +00003464 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003465 if (ParseGlobalTypeAndValue(C)) return true;
3466 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003467 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003468
3469 return false;
3470}
3471
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003472bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003473 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003474 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003475 return true;
3476
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003477 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003478 return false;
3479}
3480
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003481/// MDNode:
3482/// ::= !{ ... }
3483/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003484/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003485bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003486 if (Lex.getKind() == lltok::MetadataVar)
3487 return ParseSpecializedMDNode(N);
3488
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003489 return ParseToken(lltok::exclaim, "expected '!' here") ||
3490 ParseMDNodeTail(N);
3491}
3492
3493bool LLParser::ParseMDNodeTail(MDNode *&N) {
3494 // !{ ... }
3495 if (Lex.getKind() == lltok::lbrace)
3496 return ParseMDTuple(N);
3497
3498 // !42
3499 return ParseMDNodeID(N);
3500}
3501
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003502namespace {
3503
3504/// Structure to represent an optional metadata field.
3505template <class FieldTy> struct MDFieldImpl {
3506 typedef MDFieldImpl ImplTy;
3507 FieldTy Val;
3508 bool Seen;
3509
3510 void assign(FieldTy Val) {
3511 Seen = true;
3512 this->Val = std::move(Val);
3513 }
3514
3515 explicit MDFieldImpl(FieldTy Default)
3516 : Val(std::move(Default)), Seen(false) {}
3517};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003518
Sander de Smalenfdf40912018-01-24 09:56:07 +00003519/// Structure to represent an optional metadata field that
3520/// can be of either type (A or B) and encapsulates the
3521/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3522/// to reimplement the specifics for representing each Field.
3523template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3524 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3525 FieldTypeA A;
3526 FieldTypeB B;
3527 bool Seen;
3528
3529 enum {
3530 IsInvalid = 0,
3531 IsTypeA = 1,
3532 IsTypeB = 2
3533 } WhatIs;
3534
3535 void assign(FieldTypeA A) {
3536 Seen = true;
3537 this->A = std::move(A);
3538 WhatIs = IsTypeA;
3539 }
3540
3541 void assign(FieldTypeB B) {
3542 Seen = true;
3543 this->B = std::move(B);
3544 WhatIs = IsTypeB;
3545 }
3546
3547 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3548 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3549 WhatIs(IsInvalid) {}
3550};
3551
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003552struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3553 uint64_t Max;
3554
3555 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3556 : ImplTy(Default), Max(Max) {}
3557};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003558
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003559struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003560 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003561};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003562
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003563struct ColumnField : public MDUnsignedField {
3564 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3565};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003566
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003567struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003568 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003569 DwarfTagField(dwarf::Tag DefaultTag)
3570 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003571};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003572
Amjad Abouda9bcf162015-12-10 12:56:35 +00003573struct DwarfMacinfoTypeField : public MDUnsignedField {
3574 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3575 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3576 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3577};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003578
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003579struct DwarfAttEncodingField : public MDUnsignedField {
3580 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3581};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003582
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003583struct DwarfVirtualityField : public MDUnsignedField {
3584 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3585};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003586
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003587struct DwarfLangField : public MDUnsignedField {
3588 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3589};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003590
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003591struct DwarfCCField : public MDUnsignedField {
3592 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3593};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003594
Adrian Prantlb939a252016-03-31 23:56:58 +00003595struct EmissionKindField : public MDUnsignedField {
3596 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3597};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003598
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003599struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3600 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003601};
3602
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003603struct MDSignedField : public MDFieldImpl<int64_t> {
3604 int64_t Min;
3605 int64_t Max;
3606
3607 MDSignedField(int64_t Default = 0)
3608 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3609 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3610 : ImplTy(Default), Min(Min), Max(Max) {}
3611};
3612
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003613struct MDBoolField : public MDFieldImpl<bool> {
3614 MDBoolField(bool Default = false) : ImplTy(Default) {}
3615};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003616
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003617struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003618 bool AllowNull;
3619
3620 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003621};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003622
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003623struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3624 MDConstant() : ImplTy(nullptr) {}
3625};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003626
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003627struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003628 bool AllowEmpty;
3629 MDStringField(bool AllowEmpty = true)
3630 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003631};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003632
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003633struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3634 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3635};
3636
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003637struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003638 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3639};
3640
Sander de Smalenfdf40912018-01-24 09:56:07 +00003641struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3642 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3643 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3644
3645 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3646 bool AllowNull = true)
3647 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3648
3649 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3650 bool isMDField() const { return WhatIs == IsTypeB; }
3651 int64_t getMDSignedValue() const {
3652 assert(isMDSignedField() && "Wrong field type");
3653 return A.Val;
3654 }
3655 Metadata *getMDFieldValue() const {
3656 assert(isMDField() && "Wrong field type");
3657 return B.Val;
3658 }
3659};
3660
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003661struct MDSignedOrUnsignedField
3662 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3663 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3664
3665 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3666 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3667 int64_t getMDSignedValue() const {
3668 assert(isMDSignedField() && "Wrong field type");
3669 return A.Val;
3670 }
3671 uint64_t getMDUnsignedValue() const {
3672 assert(isMDUnsignedField() && "Wrong field type");
3673 return B.Val;
3674 }
3675};
3676
Eugene Zelenko1804a772016-08-25 00:45:04 +00003677} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003678
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003679namespace llvm {
3680
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003681template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003682bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003683 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003684 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3685 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003686
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003687 auto &U = Lex.getAPSIntVal();
3688 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003689 return TokError("value for '" + Name + "' too large, limit is " +
3690 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003691 Result.assign(U.getZExtValue());
3692 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003693 Lex.Lex();
3694 return false;
3695}
3696
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003697template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003698bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3699 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3700}
3701template <>
3702bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3703 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3704}
3705
3706template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003707bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3708 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003709 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003710
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003711 if (Lex.getKind() != lltok::DwarfTag)
3712 return TokError("expected DWARF tag");
3713
3714 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3715 if (Tag == dwarf::DW_TAG_invalid)
3716 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003717 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003718
3719 Result.assign(Tag);
3720 Lex.Lex();
3721 return false;
3722}
3723
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003724template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003725bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003726 DwarfMacinfoTypeField &Result) {
3727 if (Lex.getKind() == lltok::APSInt)
3728 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3729
3730 if (Lex.getKind() != lltok::DwarfMacinfo)
3731 return TokError("expected DWARF macinfo type");
3732
3733 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3734 if (Macinfo == dwarf::DW_MACINFO_invalid)
3735 return TokError(
3736 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3737 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3738
3739 Result.assign(Macinfo);
3740 Lex.Lex();
3741 return false;
3742}
3743
3744template <>
3745bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003746 DwarfVirtualityField &Result) {
3747 if (Lex.getKind() == lltok::APSInt)
3748 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3749
3750 if (Lex.getKind() != lltok::DwarfVirtuality)
3751 return TokError("expected DWARF virtuality code");
3752
3753 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003754 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003755 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3756 Lex.getStrVal() + "'");
3757 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3758 Result.assign(Virtuality);
3759 Lex.Lex();
3760 return false;
3761}
3762
3763template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003764bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3765 if (Lex.getKind() == lltok::APSInt)
3766 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3767
3768 if (Lex.getKind() != lltok::DwarfLang)
3769 return TokError("expected DWARF language");
3770
3771 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3772 if (!Lang)
3773 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3774 "'");
3775 assert(Lang <= Result.Max && "Expected valid DWARF language");
3776 Result.assign(Lang);
3777 Lex.Lex();
3778 return false;
3779}
3780
3781template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003782bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3783 if (Lex.getKind() == lltok::APSInt)
3784 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3785
3786 if (Lex.getKind() != lltok::DwarfCC)
3787 return TokError("expected DWARF calling convention");
3788
3789 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3790 if (!CC)
3791 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3792 "'");
3793 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3794 Result.assign(CC);
3795 Lex.Lex();
3796 return false;
3797}
3798
3799template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003800bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3801 if (Lex.getKind() == lltok::APSInt)
3802 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3803
3804 if (Lex.getKind() != lltok::EmissionKind)
3805 return TokError("expected emission kind");
3806
3807 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3808 if (!Kind)
3809 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3810 "'");
3811 assert(*Kind <= Result.Max && "Expected valid emission kind");
3812 Result.assign(*Kind);
3813 Lex.Lex();
3814 return false;
3815}
3816
3817template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003818bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003819 DwarfAttEncodingField &Result) {
3820 if (Lex.getKind() == lltok::APSInt)
3821 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3822
3823 if (Lex.getKind() != lltok::DwarfAttEncoding)
3824 return TokError("expected DWARF type attribute encoding");
3825
3826 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3827 if (!Encoding)
3828 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3829 Lex.getStrVal() + "'");
3830 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3831 Result.assign(Encoding);
3832 Lex.Lex();
3833 return false;
3834}
3835
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003836/// DIFlagField
3837/// ::= uint32
3838/// ::= DIFlagVector
3839/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3840template <>
3841bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003842
3843 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003844 auto parseFlag = [&](DINode::DIFlags &Val) {
3845 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3846 uint32_t TempVal = static_cast<uint32_t>(Val);
3847 bool Res = ParseUInt32(TempVal);
3848 Val = static_cast<DINode::DIFlags>(TempVal);
3849 return Res;
3850 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003851
3852 if (Lex.getKind() != lltok::DIFlag)
3853 return TokError("expected debug info flag");
3854
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003855 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003856 if (!Val)
3857 return TokError(Twine("invalid debug info flag flag '") +
3858 Lex.getStrVal() + "'");
3859 Lex.Lex();
3860 return false;
3861 };
3862
3863 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003864 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003865 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003866 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003867 if (parseFlag(Val))
3868 return true;
3869 Combined |= Val;
3870 } while (EatIfPresent(lltok::bar));
3871
3872 Result.assign(Combined);
3873 return false;
3874}
3875
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003876template <>
3877bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003878 MDSignedField &Result) {
3879 if (Lex.getKind() != lltok::APSInt)
3880 return TokError("expected signed integer");
3881
3882 auto &S = Lex.getAPSIntVal();
3883 if (S < Result.Min)
3884 return TokError("value for '" + Name + "' too small, limit is " +
3885 Twine(Result.Min));
3886 if (S > Result.Max)
3887 return TokError("value for '" + Name + "' too large, limit is " +
3888 Twine(Result.Max));
3889 Result.assign(S.getExtValue());
3890 assert(Result.Val >= Result.Min && "Expected value in range");
3891 assert(Result.Val <= Result.Max && "Expected value in range");
3892 Lex.Lex();
3893 return false;
3894}
3895
3896template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003897bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3898 switch (Lex.getKind()) {
3899 default:
3900 return TokError("expected 'true' or 'false'");
3901 case lltok::kw_true:
3902 Result.assign(true);
3903 break;
3904 case lltok::kw_false:
3905 Result.assign(false);
3906 break;
3907 }
3908 Lex.Lex();
3909 return false;
3910}
3911
3912template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003913bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003914 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003915 if (!Result.AllowNull)
3916 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003917 Lex.Lex();
3918 Result.assign(nullptr);
3919 return false;
3920 }
3921
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003922 Metadata *MD;
3923 if (ParseMetadata(MD, nullptr))
3924 return true;
3925
3926 Result.assign(MD);
3927 return false;
3928}
3929
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003930template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00003931bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3932 MDSignedOrMDField &Result) {
3933 // Try to parse a signed int.
3934 if (Lex.getKind() == lltok::APSInt) {
3935 MDSignedField Res = Result.A;
3936 if (!ParseMDField(Loc, Name, Res)) {
3937 Result.assign(Res);
3938 return false;
3939 }
3940 return true;
3941 }
3942
3943 // Otherwise, try to parse as an MDField.
3944 MDField Res = Result.B;
3945 if (!ParseMDField(Loc, Name, Res)) {
3946 Result.assign(Res);
3947 return false;
3948 }
3949
3950 return true;
3951}
3952
3953template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003954bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3955 MDSignedOrUnsignedField &Result) {
3956 if (Lex.getKind() != lltok::APSInt)
3957 return false;
3958
3959 if (Lex.getAPSIntVal().isSigned()) {
3960 MDSignedField Res = Result.A;
3961 if (ParseMDField(Loc, Name, Res))
3962 return true;
3963 Result.assign(Res);
3964 return false;
3965 }
3966
3967 MDUnsignedField Res = Result.B;
3968 if (ParseMDField(Loc, Name, Res))
3969 return true;
3970 Result.assign(Res);
3971 return false;
3972}
3973
3974template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003975bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003976 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003977 std::string S;
3978 if (ParseStringConstant(S))
3979 return true;
3980
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003981 if (!Result.AllowEmpty && S.empty())
3982 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3983
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003984 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003985 return false;
3986}
3987
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003988template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003989bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3990 SmallVector<Metadata *, 4> MDs;
3991 if (ParseMDNodeVector(MDs))
3992 return true;
3993
3994 Result.assign(std::move(MDs));
3995 return false;
3996}
3997
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003998template <>
3999bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4000 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004001 Optional<DIFile::ChecksumKind> CSKind =
4002 DIFile::getChecksumKind(Lex.getStrVal());
4003
4004 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004005 return TokError(
4006 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4007
Scott Linder71603842018-02-12 19:45:54 +00004008 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004009 Lex.Lex();
4010 return false;
4011}
4012
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004013} // end namespace llvm
4014
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004015template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004016bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004017 do {
4018 if (Lex.getKind() != lltok::LabelStr)
4019 return TokError("expected field label here");
4020
4021 if (parseField())
4022 return true;
4023 } while (EatIfPresent(lltok::comma));
4024
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004025 return false;
4026}
4027
4028template <class ParserTy>
4029bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4030 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4031 Lex.Lex();
4032
4033 if (ParseToken(lltok::lparen, "expected '(' here"))
4034 return true;
4035 if (Lex.getKind() != lltok::rparen)
4036 if (ParseMDFieldsImplBody(parseField))
4037 return true;
4038
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004039 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004040 return ParseToken(lltok::rparen, "expected ')' here");
4041}
4042
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004043template <class FieldTy>
4044bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4045 if (Result.Seen)
4046 return TokError("field '" + Name + "' cannot be specified more than once");
4047
4048 LocTy Loc = Lex.getLoc();
4049 Lex.Lex();
4050 return ParseMDField(Loc, Name, Result);
4051}
4052
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004053bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4054 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004055
4056#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004057 if (Lex.getStrVal() == #CLASS) \
4058 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004059#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004060
4061 return TokError("expected metadata type");
4062}
4063
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004064#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4065#define NOP_FIELD(NAME, TYPE, INIT)
4066#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4067 if (!NAME.Seen) \
4068 return Error(ClosingLoc, "missing required field '" #NAME "'");
4069#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004070 if (Lex.getStrVal() == #NAME) \
4071 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004072#define PARSE_MD_FIELDS() \
4073 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4074 do { \
4075 LocTy ClosingLoc; \
4076 if (ParseMDFieldsImpl([&]() -> bool { \
4077 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4078 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4079 }, ClosingLoc)) \
4080 return true; \
4081 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4082 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004083#define GET_OR_DISTINCT(CLASS, ARGS) \
4084 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004085
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004086/// ParseDILocationFields:
4087/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
4088bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004089#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004090 OPTIONAL(line, LineField, ); \
4091 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004092 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004093 OPTIONAL(inlinedAt, MDField, );
4094 PARSE_MD_FIELDS();
4095#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004096
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00004097 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004098 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004099 return false;
4100}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004101
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004102/// ParseGenericDINode:
4103/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4104bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004105#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004106 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004107 OPTIONAL(header, MDStringField, ); \
4108 OPTIONAL(operands, MDFieldList, );
4109 PARSE_MD_FIELDS();
4110#undef VISIT_MD_FIELDS
4111
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004112 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004113 (Context, tag.Val, header.Val, operands.Val));
4114 return false;
4115}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004116
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004117/// ParseDISubrange:
4118/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004119/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004120bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004121#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004122 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004123 OPTIONAL(lowerBound, MDSignedField, );
4124 PARSE_MD_FIELDS();
4125#undef VISIT_MD_FIELDS
4126
Sander de Smalenfdf40912018-01-24 09:56:07 +00004127 if (count.isMDSignedField())
4128 Result = GET_OR_DISTINCT(
4129 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4130 else if (count.isMDField())
4131 Result = GET_OR_DISTINCT(
4132 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4133 else
4134 return true;
4135
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004136 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004137}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004138
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004139/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004140/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004141bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004142#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004143 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004144 REQUIRED(value, MDSignedOrUnsignedField, ); \
4145 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004146 PARSE_MD_FIELDS();
4147#undef VISIT_MD_FIELDS
4148
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004149 if (isUnsigned.Val && value.isMDSignedField())
4150 return TokError("unsigned enumerator with negative value");
4151
4152 int64_t Value = value.isMDSignedField()
4153 ? value.getMDSignedValue()
4154 : static_cast<int64_t>(value.getMDUnsignedValue());
4155 Result =
4156 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4157
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004158 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004159}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004160
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004161/// ParseDIBasicType:
4162/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
4163bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004164#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004165 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004166 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004167 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004168 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004169 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004170 PARSE_MD_FIELDS();
4171#undef VISIT_MD_FIELDS
4172
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004173 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004174 align.Val, encoding.Val));
4175 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004176}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004177
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004178/// ParseDIDerivedType:
4179/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004180/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004181/// align: 32, offset: 0, flags: 0, extraData: !3,
4182/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004183bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004184#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4185 REQUIRED(tag, DwarfTagField, ); \
4186 OPTIONAL(name, MDStringField, ); \
4187 OPTIONAL(file, MDField, ); \
4188 OPTIONAL(line, LineField, ); \
4189 OPTIONAL(scope, MDField, ); \
4190 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004191 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004192 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004193 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004194 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004195 OPTIONAL(extraData, MDField, ); \
4196 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004197 PARSE_MD_FIELDS();
4198#undef VISIT_MD_FIELDS
4199
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004200 Optional<unsigned> DWARFAddressSpace;
4201 if (dwarfAddressSpace.Val != UINT32_MAX)
4202 DWARFAddressSpace = dwarfAddressSpace.Val;
4203
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004204 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004205 (Context, tag.Val, name.Val, file.Val, line.Val,
4206 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004207 offset.Val, DWARFAddressSpace, flags.Val,
4208 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004209 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004210}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004211
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004212bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004213#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4214 REQUIRED(tag, DwarfTagField, ); \
4215 OPTIONAL(name, MDStringField, ); \
4216 OPTIONAL(file, MDField, ); \
4217 OPTIONAL(line, LineField, ); \
4218 OPTIONAL(scope, MDField, ); \
4219 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004220 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004221 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004222 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004223 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004224 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004225 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004226 OPTIONAL(vtableHolder, MDField, ); \
4227 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004228 OPTIONAL(identifier, MDStringField, ); \
4229 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004230 PARSE_MD_FIELDS();
4231#undef VISIT_MD_FIELDS
4232
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004233 // If this has an identifier try to build an ODR type.
4234 if (identifier.Val)
4235 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004236 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4237 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4238 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004239 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004240 Result = CT;
4241 return false;
4242 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004243
4244 // Create a new node, and save it in the context if it belongs in the type
4245 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004246 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004247 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004248 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4249 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004250 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4251 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004252 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004253}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004254
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004255bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004256#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004257 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004258 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004259 REQUIRED(types, MDField, );
4260 PARSE_MD_FIELDS();
4261#undef VISIT_MD_FIELDS
4262
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004263 Result = GET_OR_DISTINCT(DISubroutineType,
4264 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004265 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004266}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004267
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004268/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004269/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004270/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004271/// checksum: "000102030405060708090a0b0c0d0e0f",
4272/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004273bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004274 // The default constructed value for checksumkind is required, but will never
4275 // be used, as the parser checks if the field was actually Seen before using
4276 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004277#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4278 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004279 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004280 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004281 OPTIONAL(checksum, MDStringField, ); \
4282 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004283 PARSE_MD_FIELDS();
4284#undef VISIT_MD_FIELDS
4285
Scott Linder71603842018-02-12 19:45:54 +00004286 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4287 if (checksumkind.Seen && checksum.Seen)
4288 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4289 else if (checksumkind.Seen || checksum.Seen)
4290 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4291
Scott Linder16c7bda2018-02-23 23:01:06 +00004292 Optional<MDString *> OptSource;
4293 if (source.Seen)
4294 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004295 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004296 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004297 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004298}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004299
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004300/// ParseDICompileUnit:
4301/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004302/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004303/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004304/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004305/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004306bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004307 if (!IsDistinct)
4308 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4309
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004310#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4311 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004312 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004313 OPTIONAL(producer, MDStringField, ); \
4314 OPTIONAL(isOptimized, MDBoolField, ); \
4315 OPTIONAL(flags, MDStringField, ); \
4316 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4317 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004318 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004319 OPTIONAL(enums, MDField, ); \
4320 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004321 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004322 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004323 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004324 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004325 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004326 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4327 OPTIONAL(gnuPubnames, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004328 PARSE_MD_FIELDS();
4329#undef VISIT_MD_FIELDS
4330
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004331 Result = DICompileUnit::getDistinct(
4332 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4333 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004334 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004335 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004336 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004337}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004338
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004339/// ParseDISubprogram:
4340/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004341/// file: !1, line: 7, type: !2, isLocal: false,
4342/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004343/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004344/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004345/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004346/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004347bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004348 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004349#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4350 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004351 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004352 OPTIONAL(linkageName, MDStringField, ); \
4353 OPTIONAL(file, MDField, ); \
4354 OPTIONAL(line, LineField, ); \
4355 OPTIONAL(type, MDField, ); \
4356 OPTIONAL(isLocal, MDBoolField, ); \
4357 OPTIONAL(isDefinition, MDBoolField, (true)); \
4358 OPTIONAL(scopeLine, LineField, ); \
4359 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004360 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004361 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004362 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004363 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004364 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004365 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004366 OPTIONAL(templateParams, MDField, ); \
4367 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004368 OPTIONAL(variables, MDField, ); \
4369 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004370 PARSE_MD_FIELDS();
4371#undef VISIT_MD_FIELDS
4372
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004373 if (isDefinition.Val && !IsDistinct)
4374 return Lex.Error(
4375 Loc,
4376 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4377
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004378 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004379 DISubprogram,
4380 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4381 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4382 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4383 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4384 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004385 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004386}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004387
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004388/// ParseDILexicalBlock:
4389/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4390bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004391#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004392 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004393 OPTIONAL(file, MDField, ); \
4394 OPTIONAL(line, LineField, ); \
4395 OPTIONAL(column, ColumnField, );
4396 PARSE_MD_FIELDS();
4397#undef VISIT_MD_FIELDS
4398
4399 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004400 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004401 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004402}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004403
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004404/// ParseDILexicalBlockFile:
4405/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4406bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004407#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004408 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004409 OPTIONAL(file, MDField, ); \
4410 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4411 PARSE_MD_FIELDS();
4412#undef VISIT_MD_FIELDS
4413
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004414 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004415 (Context, scope.Val, file.Val, discriminator.Val));
4416 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004417}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004418
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004419/// ParseDINamespace:
4420/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4421bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004422#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4423 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004424 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004425 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004426 PARSE_MD_FIELDS();
4427#undef VISIT_MD_FIELDS
4428
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004429 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004430 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004431 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004432}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004433
Amjad Abouda9bcf162015-12-10 12:56:35 +00004434/// ParseDIMacro:
4435/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4436bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4437#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4438 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004439 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004440 REQUIRED(name, MDStringField, ); \
4441 OPTIONAL(value, MDStringField, );
4442 PARSE_MD_FIELDS();
4443#undef VISIT_MD_FIELDS
4444
4445 Result = GET_OR_DISTINCT(DIMacro,
4446 (Context, type.Val, line.Val, name.Val, value.Val));
4447 return false;
4448}
4449
4450/// ParseDIMacroFile:
4451/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4452bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4453#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4454 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004455 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004456 REQUIRED(file, MDField, ); \
4457 OPTIONAL(nodes, MDField, );
4458 PARSE_MD_FIELDS();
4459#undef VISIT_MD_FIELDS
4460
4461 Result = GET_OR_DISTINCT(DIMacroFile,
4462 (Context, type.Val, line.Val, file.Val, nodes.Val));
4463 return false;
4464}
4465
Adrian Prantlab1243f2015-06-29 23:03:47 +00004466/// ParseDIModule:
4467/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4468/// includePath: "/usr/include", isysroot: "/")
4469bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4470#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4471 REQUIRED(scope, MDField, ); \
4472 REQUIRED(name, MDStringField, ); \
4473 OPTIONAL(configMacros, MDStringField, ); \
4474 OPTIONAL(includePath, MDStringField, ); \
4475 OPTIONAL(isysroot, MDStringField, );
4476 PARSE_MD_FIELDS();
4477#undef VISIT_MD_FIELDS
4478
4479 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4480 configMacros.Val, includePath.Val, isysroot.Val));
4481 return false;
4482}
4483
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004484/// ParseDITemplateTypeParameter:
4485/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4486bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004487#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004488 OPTIONAL(name, MDStringField, ); \
4489 REQUIRED(type, MDField, );
4490 PARSE_MD_FIELDS();
4491#undef VISIT_MD_FIELDS
4492
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004493 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004494 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004495 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004496}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004497
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004498/// ParseDITemplateValueParameter:
4499/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004500/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004501bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004502#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004503 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004504 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004505 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004506 REQUIRED(value, MDField, );
4507 PARSE_MD_FIELDS();
4508#undef VISIT_MD_FIELDS
4509
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004510 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004511 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004512 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004513}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004514
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004515/// ParseDIGlobalVariable:
4516/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004517/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004518/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004519bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004520#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004521 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004522 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004523 OPTIONAL(linkageName, MDStringField, ); \
4524 OPTIONAL(file, MDField, ); \
4525 OPTIONAL(line, LineField, ); \
4526 OPTIONAL(type, MDField, ); \
4527 OPTIONAL(isLocal, MDBoolField, ); \
4528 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004529 OPTIONAL(declaration, MDField, ); \
4530 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004531 PARSE_MD_FIELDS();
4532#undef VISIT_MD_FIELDS
4533
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004534 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004535 (Context, scope.Val, name.Val, linkageName.Val,
4536 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004537 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004538 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004539}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004540
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004541/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004542/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004543/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4544/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004545/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004546/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4547/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004548bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004549#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004550 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004551 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004552 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004553 OPTIONAL(file, MDField, ); \
4554 OPTIONAL(line, LineField, ); \
4555 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004556 OPTIONAL(flags, DIFlagField, ); \
4557 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004558 PARSE_MD_FIELDS();
4559#undef VISIT_MD_FIELDS
4560
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004561 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004562 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004563 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004564 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004565}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004566
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004567/// ParseDIExpression:
4568/// ::= !DIExpression(0, 7, -1)
4569bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004570 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4571 Lex.Lex();
4572
4573 if (ParseToken(lltok::lparen, "expected '(' here"))
4574 return true;
4575
4576 SmallVector<uint64_t, 8> Elements;
4577 if (Lex.getKind() != lltok::rparen)
4578 do {
4579 if (Lex.getKind() == lltok::DwarfOp) {
4580 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4581 Lex.Lex();
4582 Elements.push_back(Op);
4583 continue;
4584 }
4585 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4586 }
4587
4588 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4589 return TokError("expected unsigned integer");
4590
4591 auto &U = Lex.getAPSIntVal();
4592 if (U.ugt(UINT64_MAX))
4593 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4594 Elements.push_back(U.getZExtValue());
4595 Lex.Lex();
4596 } while (EatIfPresent(lltok::comma));
4597
4598 if (ParseToken(lltok::rparen, "expected ')' here"))
4599 return true;
4600
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004601 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004602 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004603}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004604
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004605/// ParseDIGlobalVariableExpression:
4606/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4607bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4608 bool IsDistinct) {
4609#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4610 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004611 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004612 PARSE_MD_FIELDS();
4613#undef VISIT_MD_FIELDS
4614
4615 Result =
4616 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4617 return false;
4618}
4619
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004620/// ParseDIObjCProperty:
4621/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004622/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004623bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004624#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004625 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004626 OPTIONAL(file, MDField, ); \
4627 OPTIONAL(line, LineField, ); \
4628 OPTIONAL(setter, MDStringField, ); \
4629 OPTIONAL(getter, MDStringField, ); \
4630 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4631 OPTIONAL(type, MDField, );
4632 PARSE_MD_FIELDS();
4633#undef VISIT_MD_FIELDS
4634
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004635 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004636 (Context, name.Val, file.Val, line.Val, setter.Val,
4637 getter.Val, attributes.Val, type.Val));
4638 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004639}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004640
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004641/// ParseDIImportedEntity:
4642/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004643/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004644bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004645#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4646 REQUIRED(tag, DwarfTagField, ); \
4647 REQUIRED(scope, MDField, ); \
4648 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004649 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004650 OPTIONAL(line, LineField, ); \
4651 OPTIONAL(name, MDStringField, );
4652 PARSE_MD_FIELDS();
4653#undef VISIT_MD_FIELDS
4654
Adrian Prantld63bfd22017-07-19 00:09:54 +00004655 Result = GET_OR_DISTINCT(
4656 DIImportedEntity,
4657 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004658 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004659}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004660
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004661#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004662#undef NOP_FIELD
4663#undef REQUIRE_FIELD
4664#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004665
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004666/// ParseMetadataAsValue
4667/// ::= metadata i32 %local
4668/// ::= metadata i32 @global
4669/// ::= metadata i32 7
4670/// ::= metadata !0
4671/// ::= metadata !{...}
4672/// ::= metadata !"string"
4673bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4674 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004675 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004676 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004677 return true;
4678
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004679 V = MetadataAsValue::get(Context, MD);
4680 return false;
4681}
4682
4683/// ParseValueAsMetadata
4684/// ::= i32 %local
4685/// ::= i32 @global
4686/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004687bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4688 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004689 Type *Ty;
4690 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004691 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004692 return true;
4693 if (Ty->isMetadataTy())
4694 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4695
4696 Value *V;
4697 if (ParseValue(Ty, V, PFS))
4698 return true;
4699
4700 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004701 return false;
4702}
4703
4704/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004705/// ::= i32 %local
4706/// ::= i32 @global
4707/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004708/// ::= !42
4709/// ::= !{...}
4710/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004711/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004712bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004713 if (Lex.getKind() == lltok::MetadataVar) {
4714 MDNode *N;
4715 if (ParseSpecializedMDNode(N))
4716 return true;
4717 MD = N;
4718 return false;
4719 }
4720
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004721 // ValueAsMetadata:
4722 // <type> <value>
4723 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004724 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004725
4726 // '!'.
4727 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4728 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004729
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004730 // MDString:
4731 // ::= '!' STRINGCONSTANT
4732 if (Lex.getKind() == lltok::StringConstant) {
4733 MDString *S;
4734 if (ParseMDString(S))
4735 return true;
4736 MD = S;
4737 return false;
4738 }
4739
Dan Gohman8939ba332010-07-14 18:26:50 +00004740 // MDNode:
4741 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004742 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004743 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004744 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004745 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004746 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004747 return false;
4748}
4749
Victor Hernandez9d75c962010-01-11 22:31:58 +00004750//===----------------------------------------------------------------------===//
4751// Function Parsing.
4752//===----------------------------------------------------------------------===//
4753
Chris Lattner229907c2011-07-18 04:54:35 +00004754bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004755 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004756 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004757 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004758
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004761 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004762 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004763 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004764 case ValID::t_LocalName:
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.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004767 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004768 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004769 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004770 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004771 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4772 (ID.UIntVal >> 1) & 1,
4773 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004774 return false;
4775 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 case ValID::t_GlobalName:
4777 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004778 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004779 case ValID::t_GlobalID:
4780 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004781 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004782 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004783 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004784 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004785 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004786 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004787 return false;
4788 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004789 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4791 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004792
Dan Gohman518cda42011-12-17 00:04:22 +00004793 // The lexer has no type info, so builds all half, float, and double FP
4794 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004795 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004797 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004798 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004799 &Ignored);
4800 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004801 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004802 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004804 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004805
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004806 if (V->getType() != Ty)
4807 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004808 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004809
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810 return false;
4811 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004812 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004813 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004814 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004815 return false;
4816 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004817 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004818 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004819 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004820 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004822 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004823 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004824 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004825 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004826 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004828 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004829 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004831 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004833 case ValID::t_None:
4834 if (!Ty->isTokenTy())
4835 return Error(ID.Loc, "invalid type for none constant");
4836 V = Constant::getNullValue(Ty);
4837 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004838 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004839 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004841
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 V = ID.ConstantVal;
4843 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004844 case ValID::t_ConstantStruct:
4845 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004846 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004847 if (ST->getNumElements() != ID.UIntVal)
4848 return Error(ID.Loc,
4849 "initializer with struct type has wrong # elements");
4850 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4851 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004852
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004853 // Verify that the elements are compatible with the structtype.
4854 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4855 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4856 return Error(ID.Loc, "element " + Twine(i) +
4857 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004858
David Blaikieadbda4b2015-08-03 20:08:41 +00004859 V = ConstantStruct::get(
4860 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004861 } else
4862 return Error(ID.Loc, "constant expression type mismatch");
4863 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004864 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004865 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004866}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004867
Alex Lorenzd2255952015-07-17 22:07:03 +00004868bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4869 C = nullptr;
4870 ValID ID;
4871 auto Loc = Lex.getLoc();
4872 if (ParseValID(ID, /*PFS=*/nullptr))
4873 return true;
4874 switch (ID.Kind) {
4875 case ValID::t_APSInt:
4876 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004877 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004878 case ValID::t_Constant:
4879 case ValID::t_ConstantStruct:
4880 case ValID::t_PackedConstantStruct: {
4881 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004882 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00004883 return true;
4884 assert(isa<Constant>(V) && "Expected a constant value");
4885 C = cast<Constant>(V);
4886 return false;
4887 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004888 case ValID::t_Null:
4889 C = Constant::getNullValue(Ty);
4890 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004891 default:
4892 return Error(Loc, "expected a constant value");
4893 }
4894}
4895
David Majnemer8a1c45d2015-12-12 05:38:55 +00004896bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004897 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004898 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004899 return ParseValID(ID, PFS) ||
4900 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004901}
4902
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004903bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004904 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004905 return ParseType(Ty) ||
4906 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004907}
4908
Chris Lattner3ed871f2009-10-27 19:13:16 +00004909bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4910 PerFunctionState &PFS) {
4911 Value *V;
4912 Loc = Lex.getLoc();
4913 if (ParseTypeAndValue(V, PFS)) return true;
4914 if (!isa<BasicBlock>(V))
4915 return Error(Loc, "expected a basic block");
4916 BB = cast<BasicBlock>(V);
4917 return false;
4918}
4919
Chris Lattnerac161bf2009-01-02 07:01:27 +00004920/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00004921/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
4922/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
4923/// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
4924/// OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4926 // Parse the linkage.
4927 LocTy LinkageLoc = Lex.getLoc();
4928 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004929 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004930 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00004931 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00004932 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004933 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004934 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004935 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004936 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00004937 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
4938 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004939 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004940 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 return true;
4942
4943 // Verify that the linkage is ok.
4944 switch ((GlobalValue::LinkageTypes)Linkage) {
4945 case GlobalValue::ExternalLinkage:
4946 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004947 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 if (isDefine)
4949 return Error(LinkageLoc, "invalid linkage for function definition");
4950 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004951 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004952 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004953 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004954 case GlobalValue::LinkOnceAnyLinkage:
4955 case GlobalValue::LinkOnceODRLinkage:
4956 case GlobalValue::WeakAnyLinkage:
4957 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004958 if (!isDefine)
4959 return Error(LinkageLoc, "invalid linkage for function declaration");
4960 break;
4961 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004962 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963 return Error(LinkageLoc, "invalid function linkage type");
4964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004965
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004966 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4967 return Error(LinkageLoc,
4968 "symbol with local linkage must have default visibility");
4969
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004970 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004971 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004972
Chris Lattnerac161bf2009-01-02 07:01:27 +00004973 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004974
4975 std::string FunctionName;
4976 if (Lex.getKind() == lltok::GlobalVar) {
4977 FunctionName = Lex.getStrVal();
4978 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4979 unsigned NameID = Lex.getUIntVal();
4980
4981 if (NameID != NumberedVals.size())
4982 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004983 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004984 } else {
4985 return TokError("expected function name");
4986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004987
Chris Lattner3822f632009-01-02 08:05:26 +00004988 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004989
Chris Lattner3822f632009-01-02 08:05:26 +00004990 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004991 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004993 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004994 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004995 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004996 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004997 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004999 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005000 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005001 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Craig Topper2617dcc2014-04-15 06:32:26 +00005002 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005003 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005004 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005005 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005006
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005007 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005008 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005009 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005010 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005011 (EatIfPresent(lltok::kw_section) &&
5012 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005013 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005014 ParseOptionalAlignment(Alignment) ||
5015 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005016 ParseStringConstant(GC)) ||
5017 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005018 ParseGlobalTypeAndValue(Prefix)) ||
5019 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005020 ParseGlobalTypeAndValue(Prologue)) ||
5021 (EatIfPresent(lltok::kw_personality) &&
5022 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005023 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024
Michael Gottesman41748d72013-06-27 00:25:01 +00005025 if (FuncAttrs.contains(Attribute::Builtin))
5026 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005027
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005029 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005030 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005031 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005033
Chris Lattnerac161bf2009-01-02 07:01:27 +00005034 // Okay, if we got here, the function is syntactically valid. Convert types
5035 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005036 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005037 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005038
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005040 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005041 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005042 }
5043
Reid Kleckner7f720332017-04-13 00:58:09 +00005044 AttributeList PAL =
5045 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5046 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005047
Bill Wendling749a43d2012-12-30 13:50:49 +00005048 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005049 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5050
Chris Lattner229907c2011-07-18 04:54:35 +00005051 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005052 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00005053 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005054
Craig Topper2617dcc2014-04-15 06:32:26 +00005055 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005056 if (!FunctionName.empty()) {
5057 // If this was a definition of a forward reference, remove the definition
5058 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005059 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 if (FRVI != ForwardRefVals.end()) {
5061 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005062 if (!Fn)
5063 return Error(FRVI->second.second, "invalid forward reference to "
5064 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005065 if (Fn->getType() != PFT)
5066 return Error(FRVI->second.second, "invalid forward reference to "
5067 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005068
Chris Lattnerac161bf2009-01-02 07:01:27 +00005069 ForwardRefVals.erase(FRVI);
5070 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005071 // Reject redefinitions.
5072 return Error(NameLoc, "invalid redefinition of function '" +
5073 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005074 } else if (M->getNamedValue(FunctionName)) {
5075 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005077
Dan Gohman399d6ae2009-08-29 23:37:49 +00005078 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005079 // If this is a definition of a forward referenced function, make sure the
5080 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005081 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 if (I != ForwardRefValIDs.end()) {
5083 Fn = cast<Function>(I->second.first);
5084 if (Fn->getType() != PFT)
5085 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005086 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005087 ForwardRefValIDs.erase(I);
5088 }
5089 }
5090
Craig Topper2617dcc2014-04-15 06:32:26 +00005091 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005092 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
5093 else // Move the forward-reference to the correct spot in the module.
5094 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5095
5096 if (FunctionName.empty())
5097 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005098
Chris Lattnerac161bf2009-01-02 07:01:27 +00005099 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005100 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005102 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 Fn->setCallingConv(CC);
5104 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005105 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 Fn->setAlignment(Alignment);
5107 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005108 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005109 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005110 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005111 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005112 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005113 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005114
Chris Lattnerac161bf2009-01-02 07:01:27 +00005115 // Add all of the arguments we parsed to the function.
5116 Function::arg_iterator ArgIt = Fn->arg_begin();
5117 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5118 // If the argument has a name, insert it into the argument symbol table.
5119 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005120
Chris Lattnerac161bf2009-01-02 07:01:27 +00005121 // Set the name, if it conflicted, it will be auto-renamed.
5122 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005123
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005124 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005125 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5126 ArgList[i].Name + "'");
5127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005128
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005129 if (isDefine)
5130 return false;
5131
Robin Morisset039781e2014-08-29 21:53:01 +00005132 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005133 ValID ID;
5134 if (FunctionName.empty()) {
5135 ID.Kind = ValID::t_GlobalID;
5136 ID.UIntVal = NumberedVals.size() - 1;
5137 } else {
5138 ID.Kind = ValID::t_GlobalName;
5139 ID.StrVal = FunctionName;
5140 }
5141 auto Blocks = ForwardRefBlockAddresses.find(ID);
5142 if (Blocks != ForwardRefBlockAddresses.end())
5143 return Error(Blocks->first.Loc,
5144 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005145 return false;
5146}
5147
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005148bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5149 ValID ID;
5150 if (FunctionNumber == -1) {
5151 ID.Kind = ValID::t_GlobalName;
5152 ID.StrVal = F.getName();
5153 } else {
5154 ID.Kind = ValID::t_GlobalID;
5155 ID.UIntVal = FunctionNumber;
5156 }
5157
5158 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5159 if (Blocks == P.ForwardRefBlockAddresses.end())
5160 return false;
5161
5162 for (const auto &I : Blocks->second) {
5163 const ValID &BBID = I.first;
5164 GlobalValue *GV = I.second;
5165
5166 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5167 "Expected local id or name");
5168 BasicBlock *BB;
5169 if (BBID.Kind == ValID::t_LocalName)
5170 BB = GetBB(BBID.StrVal, BBID.Loc);
5171 else
5172 BB = GetBB(BBID.UIntVal, BBID.Loc);
5173 if (!BB)
5174 return P.Error(BBID.Loc, "referenced value is not a basic block");
5175
5176 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5177 GV->eraseFromParent();
5178 }
5179
5180 P.ForwardRefBlockAddresses.erase(Blocks);
5181 return false;
5182}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005183
5184/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005185/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005187 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 return TokError("expected '{' in function body");
5189 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005190
Chris Lattner3432c622009-10-28 03:39:23 +00005191 int FunctionNumber = -1;
5192 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005193
Chris Lattner3432c622009-10-28 03:39:23 +00005194 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005195
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005196 // Resolve block addresses and allow basic blocks to be forward-declared
5197 // within this function.
5198 if (PFS.resolveForwardRefBlockAddresses())
5199 return true;
5200 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5201
Chris Lattnerbbddd962010-01-09 19:20:07 +00005202 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005203 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005204 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005205
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005206 while (Lex.getKind() != lltok::rbrace &&
5207 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005209
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005210 while (Lex.getKind() != lltok::rbrace)
5211 if (ParseUseListOrder(&PFS))
5212 return true;
5213
Chris Lattnerac161bf2009-01-02 07:01:27 +00005214 // Eat the }.
5215 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005216
Chris Lattnerac161bf2009-01-02 07:01:27 +00005217 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005218 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005219}
5220
5221/// ParseBasicBlock
5222/// ::= LabelStr? Instruction*
5223bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5224 // If this basic block starts out with a name, remember it.
5225 std::string Name;
5226 LocTy NameLoc = Lex.getLoc();
5227 if (Lex.getKind() == lltok::LabelStr) {
5228 Name = Lex.getStrVal();
5229 Lex.Lex();
5230 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005231
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005233 if (!BB)
5234 return Error(NameLoc,
5235 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005236
Chris Lattnerac161bf2009-01-02 07:01:27 +00005237 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005238
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239 // Parse the instructions in this block until we get a terminator.
5240 Instruction *Inst;
5241 do {
5242 // This instruction may have three possibilities for a name: a) none
5243 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5244 LocTy NameLoc = Lex.getLoc();
5245 int NameID = -1;
5246 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005247
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 if (Lex.getKind() == lltok::LocalVarID) {
5249 NameID = Lex.getUIntVal();
5250 Lex.Lex();
5251 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5252 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005253 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 NameStr = Lex.getStrVal();
5255 Lex.Lex();
5256 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5257 return true;
5258 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005259
Chris Lattner77b89dc2009-12-30 05:23:43 +00005260 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005261 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005262 case InstError: return true;
5263 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005264 BB->getInstList().push_back(Inst);
5265
Chris Lattner77b89dc2009-12-30 05:23:43 +00005266 // With a normal result, we check to see if the instruction is followed by
5267 // a comma and metadata.
5268 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005269 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005270 return true;
5271 break;
5272 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005273 BB->getInstList().push_back(Inst);
5274
Chris Lattner77b89dc2009-12-30 05:23:43 +00005275 // If the instruction parser ate an extra comma at the end of it, it
5276 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005277 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005278 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005279 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005280 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005281
Chris Lattnerac161bf2009-01-02 07:01:27 +00005282 // Set the name on the instruction.
5283 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5284 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005285
Chris Lattnerac161bf2009-01-02 07:01:27 +00005286 return false;
5287}
5288
5289//===----------------------------------------------------------------------===//
5290// Instruction Parsing.
5291//===----------------------------------------------------------------------===//
5292
5293/// ParseInstruction - Parse one of the many different instructions.
5294///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005295int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5296 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005297 lltok::Kind Token = Lex.getKind();
5298 if (Token == lltok::Eof)
5299 return TokError("found end of file when expecting more instructions");
5300 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005301 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005302 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005303
Chris Lattnerac161bf2009-01-02 07:01:27 +00005304 switch (Token) {
5305 default: return Error(Loc, "expected instruction opcode");
5306 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005307 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5309 case lltok::kw_br: return ParseBr(Inst, PFS);
5310 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005311 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005312 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005313 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005314 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5315 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005316 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5317 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005318 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005319 // Binary Operators.
5320 case lltok::kw_add:
5321 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005322 case lltok::kw_mul:
5323 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005324 bool NUW = EatIfPresent(lltok::kw_nuw);
5325 bool NSW = EatIfPresent(lltok::kw_nsw);
5326 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005327
Chris Lattnera676c0f2011-02-07 16:40:21 +00005328 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005329
Chris Lattnera676c0f2011-02-07 16:40:21 +00005330 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5331 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5332 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005333 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005334 case lltok::kw_fadd:
5335 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005336 case lltok::kw_fmul:
5337 case lltok::kw_fdiv:
5338 case lltok::kw_frem: {
5339 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5340 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5341 if (Res != 0)
5342 return Res;
5343 if (FMF.any())
5344 Inst->setFastMathFlags(FMF);
5345 return 0;
5346 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005347
Chris Lattner35315d02011-02-06 21:44:57 +00005348 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005349 case lltok::kw_udiv:
5350 case lltok::kw_lshr:
5351 case lltok::kw_ashr: {
5352 bool Exact = EatIfPresent(lltok::kw_exact);
5353
5354 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5355 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5356 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005357 }
5358
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005360 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005361 case lltok::kw_and:
5362 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005363 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005364 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5365 case lltok::kw_fcmp: {
5366 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5367 int Res = ParseCompare(Inst, PFS, KeywordVal);
5368 if (Res != 0)
5369 return Res;
5370 if (FMF.any())
5371 Inst->setFastMathFlags(FMF);
5372 return 0;
5373 }
5374
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 // Casts.
5376 case lltok::kw_trunc:
5377 case lltok::kw_zext:
5378 case lltok::kw_sext:
5379 case lltok::kw_fptrunc:
5380 case lltok::kw_fpext:
5381 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005382 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005383 case lltok::kw_uitofp:
5384 case lltok::kw_sitofp:
5385 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005386 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005388 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005389 // Other.
5390 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005391 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005392 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5393 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5394 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5395 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005396 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005397 // Call.
5398 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5399 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5400 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005401 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005402 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005403 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005404 case lltok::kw_load: return ParseLoad(Inst, PFS);
5405 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005406 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5407 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005408 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005409 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5410 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5411 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5412 }
5413}
5414
5415/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5416bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005417 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005418 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005419 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5421 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5422 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5423 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5424 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5425 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5426 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5427 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5428 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5429 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5430 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5431 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5432 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5433 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5434 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5435 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5436 }
5437 } else {
5438 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005439 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005440 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5441 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5442 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5443 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5444 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5445 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5446 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5447 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5448 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5449 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5450 }
5451 }
5452 Lex.Lex();
5453 return false;
5454}
5455
5456//===----------------------------------------------------------------------===//
5457// Terminator Instructions.
5458//===----------------------------------------------------------------------===//
5459
5460/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005461/// ::= 'ret' void (',' !dbg, !1)*
5462/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005463bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005464 PerFunctionState &PFS) {
5465 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005466 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005467 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005469 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005470
Chris Lattnerfdd87902009-10-05 05:54:46 +00005471 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005472 if (!ResType->isVoidTy())
5473 return Error(TypeLoc, "value doesn't match function result type '" +
5474 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005475
Owen Anderson55f1c092009-08-13 21:58:54 +00005476 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477 return false;
5478 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005479
Chris Lattnerac161bf2009-01-02 07:01:27 +00005480 Value *RV;
5481 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005482
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005483 if (ResType != RV->getType())
5484 return Error(TypeLoc, "value doesn't match function result type '" +
5485 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005486
Owen Anderson55f1c092009-08-13 21:58:54 +00005487 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005488 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005489}
5490
Chris Lattnerac161bf2009-01-02 07:01:27 +00005491/// ParseBr
5492/// ::= 'br' TypeAndValue
5493/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5494bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5495 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005496 Value *Op0;
5497 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005498 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005499
Chris Lattnerac161bf2009-01-02 07:01:27 +00005500 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5501 Inst = BranchInst::Create(BB);
5502 return false;
5503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005504
Owen Anderson55f1c092009-08-13 21:58:54 +00005505 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005506 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005507
Chris Lattnerac161bf2009-01-02 07:01:27 +00005508 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005509 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005510 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005511 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005512 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005513
Chris Lattner3ed871f2009-10-27 19:13:16 +00005514 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005515 return false;
5516}
5517
5518/// ParseSwitch
5519/// Instruction
5520/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5521/// JumpTable
5522/// ::= (TypeAndValue ',' TypeAndValue)*
5523bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5524 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005525 Value *Cond;
5526 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005527 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5528 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005529 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005530 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5531 return true;
5532
Duncan Sands19d0b472010-02-16 11:11:14 +00005533 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005534 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
Chris Lattnerac161bf2009-01-02 07:01:27 +00005536 // Parse the jump table pairs.
5537 SmallPtrSet<Value*, 32> SeenCases;
5538 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5539 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005540 Value *Constant;
5541 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005542
Chris Lattnerac161bf2009-01-02 07:01:27 +00005543 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5544 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005545 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005546 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005547
David Blaikie70573dc2014-11-19 07:49:26 +00005548 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 return Error(CondLoc, "duplicate case value in switch");
5550 if (!isa<ConstantInt>(Constant))
5551 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005552
Chris Lattner3ed871f2009-10-27 19:13:16 +00005553 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005555
Chris Lattnerac161bf2009-01-02 07:01:27 +00005556 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005557
Chris Lattner3ed871f2009-10-27 19:13:16 +00005558 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005559 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5560 SI->addCase(Table[i].first, Table[i].second);
5561 Inst = SI;
5562 return false;
5563}
5564
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005565/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005566/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005567/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5568bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005569 LocTy AddrLoc;
5570 Value *Address;
5571 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005572 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5573 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005574 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005575
Duncan Sands19d0b472010-02-16 11:11:14 +00005576 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005577 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005578
Chris Lattner3ed871f2009-10-27 19:13:16 +00005579 // Parse the destination list.
5580 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005581
Chris Lattner3ed871f2009-10-27 19:13:16 +00005582 if (Lex.getKind() != lltok::rsquare) {
5583 BasicBlock *DestBB;
5584 if (ParseTypeAndBasicBlock(DestBB, PFS))
5585 return true;
5586 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005587
Chris Lattner3ed871f2009-10-27 19:13:16 +00005588 while (EatIfPresent(lltok::comma)) {
5589 if (ParseTypeAndBasicBlock(DestBB, PFS))
5590 return true;
5591 DestList.push_back(DestBB);
5592 }
5593 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005594
Chris Lattner3ed871f2009-10-27 19:13:16 +00005595 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5596 return true;
5597
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005598 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005599 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5600 IBI->addDestination(DestList[i]);
5601 Inst = IBI;
5602 return false;
5603}
5604
Chris Lattnerac161bf2009-01-02 07:01:27 +00005605/// ParseInvoke
5606/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5607/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5608bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5609 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005610 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005611 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005612 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005613 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005614 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005615 LocTy RetTypeLoc;
5616 ValID CalleeID;
5617 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005618 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619
Chris Lattner3ed871f2009-10-27 19:13:16 +00005620 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005621 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005622 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005623 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005624 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5625 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005626 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005627 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005628 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005629 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005630 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005631 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005632
Chris Lattnerac161bf2009-01-02 07:01:27 +00005633 // If RetType is a non-function pointer type, then this is the short syntax
5634 // for the call, which means that RetType is just the return type. Infer the
5635 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005636 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5637 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005638 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005639 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5641 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005642
Chris Lattnerac161bf2009-01-02 07:01:27 +00005643 if (!FunctionType::isValidReturnType(RetType))
5644 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005645
Owen Anderson4056ca92009-07-29 22:17:13 +00005646 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005648
David Blaikie41ba2b42015-07-27 23:32:19 +00005649 CalleeID.FTy = Ty;
5650
Chris Lattnerac161bf2009-01-02 07:01:27 +00005651 // Look up the callee.
5652 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005653 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
5654 /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005655 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005656
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005657 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005658 SmallVector<Value *, 8> Args;
5659 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005660
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 // Loop through FunctionType's arguments and ensure they are specified
5662 // correctly. Also, gather any parameter attributes.
5663 FunctionType::param_iterator I = Ty->param_begin();
5664 FunctionType::param_iterator E = Ty->param_end();
5665 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005666 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667 if (I != E) {
5668 ExpectedTy = *I++;
5669 } else if (!Ty->isVarArg()) {
5670 return Error(ArgList[i].Loc, "too many arguments specified");
5671 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005672
Chris Lattnerac161bf2009-01-02 07:01:27 +00005673 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5674 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005675 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005676 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005677 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005679
Chris Lattnerac161bf2009-01-02 07:01:27 +00005680 if (I != E)
5681 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005682
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005683 if (FnAttrs.hasAlignmentAttr())
5684 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005685
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005686 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005687 AttributeList PAL =
5688 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5689 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005690
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005691 InvokeInst *II =
5692 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 II->setCallingConv(CC);
5694 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005695 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005696 Inst = II;
5697 return false;
5698}
5699
Bill Wendlingf891bf82011-07-31 06:30:59 +00005700/// ParseResume
5701/// ::= 'resume' TypeAndValue
5702bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5703 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005704 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5705 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005706
Bill Wendlingf891bf82011-07-31 06:30:59 +00005707 ResumeInst *RI = ResumeInst::Create(Exn);
5708 Inst = RI;
5709 return false;
5710}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005711
David Majnemer654e1302015-07-31 17:58:14 +00005712bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5713 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005714 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005715 return true;
5716
5717 while (Lex.getKind() != lltok::rsquare) {
5718 // If this isn't the first argument, we need a comma.
5719 if (!Args.empty() &&
5720 ParseToken(lltok::comma, "expected ',' in argument list"))
5721 return true;
5722
5723 // Parse the argument.
5724 LocTy ArgLoc;
5725 Type *ArgTy = nullptr;
5726 if (ParseType(ArgTy, ArgLoc))
5727 return true;
5728
5729 Value *V;
5730 if (ArgTy->isMetadataTy()) {
5731 if (ParseMetadataAsValue(V, PFS))
5732 return true;
5733 } else {
5734 if (ParseValue(ArgTy, V, PFS))
5735 return true;
5736 }
5737 Args.push_back(V);
5738 }
5739
5740 Lex.Lex(); // Lex the ']'.
5741 return false;
5742}
5743
5744/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005745/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005746bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005747 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005748
David Majnemer8a1c45d2015-12-12 05:38:55 +00005749 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5750 return true;
5751
5752 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005753 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005754
5755 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5756 return true;
5757
5758 BasicBlock *UnwindBB = nullptr;
5759 if (Lex.getKind() == lltok::kw_to) {
5760 Lex.Lex();
5761 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5762 return true;
5763 } else {
5764 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5765 return true;
5766 }
5767 }
5768
David Majnemer8a1c45d2015-12-12 05:38:55 +00005769 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005770 return false;
5771}
5772
5773/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005774/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005775bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005776 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005777
David Majnemer8a1c45d2015-12-12 05:38:55 +00005778 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5779 return true;
5780
5781 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005782 return true;
5783
David Majnemer0bc0eef2015-08-15 02:46:08 +00005784 BasicBlock *BB;
5785 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5786 ParseTypeAndBasicBlock(BB, PFS))
5787 return true;
5788
David Majnemer8a1c45d2015-12-12 05:38:55 +00005789 Inst = CatchReturnInst::Create(CatchPad, BB);
5790 return false;
5791}
5792
5793/// ParseCatchSwitch
5794/// ::= 'catchswitch' within Parent
5795bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5796 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005797
5798 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5799 return true;
5800
5801 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5802 Lex.getKind() != lltok::LocalVarID)
5803 return TokError("expected scope value for catchswitch");
5804
5805 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5806 return true;
5807
5808 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5809 return true;
5810
5811 SmallVector<BasicBlock *, 32> Table;
5812 do {
5813 BasicBlock *DestBB;
5814 if (ParseTypeAndBasicBlock(DestBB, PFS))
5815 return true;
5816 Table.push_back(DestBB);
5817 } while (EatIfPresent(lltok::comma));
5818
5819 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5820 return true;
5821
5822 if (ParseToken(lltok::kw_unwind,
5823 "expected 'unwind' after catchswitch scope"))
5824 return true;
5825
5826 BasicBlock *UnwindBB = nullptr;
5827 if (EatIfPresent(lltok::kw_to)) {
5828 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5829 return true;
5830 } else {
5831 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5832 return true;
5833 }
5834
5835 auto *CatchSwitch =
5836 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5837 for (BasicBlock *DestBB : Table)
5838 CatchSwitch->addHandler(DestBB);
5839 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005840 return false;
5841}
5842
5843/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005844/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005845bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005846 Value *CatchSwitch = nullptr;
5847
5848 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5849 return true;
5850
5851 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5852 return TokError("expected scope value for catchpad");
5853
5854 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5855 return true;
5856
David Majnemer654e1302015-07-31 17:58:14 +00005857 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005858 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005859 return true;
5860
David Majnemer8a1c45d2015-12-12 05:38:55 +00005861 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005862 return false;
5863}
5864
David Majnemer654e1302015-07-31 17:58:14 +00005865/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005866/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005867bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005868 Value *ParentPad = nullptr;
5869
5870 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5871 return true;
5872
5873 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5874 Lex.getKind() != lltok::LocalVarID)
5875 return TokError("expected scope value for cleanuppad");
5876
5877 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5878 return true;
5879
David Majnemer654e1302015-07-31 17:58:14 +00005880 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005881 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005882 return true;
5883
David Majnemer8a1c45d2015-12-12 05:38:55 +00005884 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005885 return false;
5886}
5887
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888//===----------------------------------------------------------------------===//
5889// Binary Operators.
5890//===----------------------------------------------------------------------===//
5891
5892/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005893/// ::= ArithmeticOps TypeAndValue ',' Value
5894///
5895/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5896/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005897bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005898 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005899 LocTy Loc; Value *LHS, *RHS;
5900 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5901 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5902 ParseValue(LHS->getType(), RHS, PFS))
5903 return true;
5904
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005905 bool Valid;
5906 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005907 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005908 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005909 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5910 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005911 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005912 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5913 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005914 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005915
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005916 if (!Valid)
5917 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005918
Chris Lattnerac161bf2009-01-02 07:01:27 +00005919 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5920 return false;
5921}
5922
5923/// ParseLogical
5924/// ::= ArithmeticOps TypeAndValue ',' Value {
5925bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5926 unsigned Opc) {
5927 LocTy Loc; Value *LHS, *RHS;
5928 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5929 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5930 ParseValue(LHS->getType(), RHS, PFS))
5931 return true;
5932
Duncan Sands9dff9be2010-02-15 16:12:20 +00005933 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005934 return Error(Loc,"instruction requires integer or integer vector operands");
5935
5936 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5937 return false;
5938}
5939
Chris Lattnerac161bf2009-01-02 07:01:27 +00005940/// ParseCompare
5941/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5942/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005943bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5944 unsigned Opc) {
5945 // Parse the integer/fp comparison predicate.
5946 LocTy Loc;
5947 unsigned Pred;
5948 Value *LHS, *RHS;
5949 if (ParseCmpPredicate(Pred, Opc) ||
5950 ParseTypeAndValue(LHS, Loc, PFS) ||
5951 ParseToken(lltok::comma, "expected ',' after compare value") ||
5952 ParseValue(LHS->getType(), RHS, PFS))
5953 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005954
Chris Lattnerac161bf2009-01-02 07:01:27 +00005955 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005956 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005957 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005958 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005959 } else {
5960 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005961 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00005962 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005963 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005964 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005965 }
5966 return false;
5967}
5968
5969//===----------------------------------------------------------------------===//
5970// Other Instructions.
5971//===----------------------------------------------------------------------===//
5972
5973
5974/// ParseCast
5975/// ::= CastOpc TypeAndValue 'to' Type
5976bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5977 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005978 LocTy Loc;
5979 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005980 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005981 if (ParseTypeAndValue(Op, Loc, PFS) ||
5982 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5983 ParseType(DestTy))
5984 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005985
Chris Lattner89d856e2009-03-01 00:53:13 +00005986 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5987 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005988 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005989 getTypeString(Op->getType()) + "' to '" +
5990 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005991 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5993 return false;
5994}
5995
5996/// ParseSelect
5997/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5998bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5999 LocTy Loc;
6000 Value *Op0, *Op1, *Op2;
6001 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6002 ParseToken(lltok::comma, "expected ',' after select condition") ||
6003 ParseTypeAndValue(Op1, PFS) ||
6004 ParseToken(lltok::comma, "expected ',' after select value") ||
6005 ParseTypeAndValue(Op2, PFS))
6006 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006007
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6009 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006010
Chris Lattnerac161bf2009-01-02 07:01:27 +00006011 Inst = SelectInst::Create(Op0, Op1, Op2);
6012 return false;
6013}
6014
Chris Lattnerb55ab542009-01-05 08:18:44 +00006015/// ParseVA_Arg
6016/// ::= 'va_arg' TypeAndValue ',' Type
6017bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006018 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006019 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006020 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006021 if (ParseTypeAndValue(Op, PFS) ||
6022 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006023 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006024 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006025
Chris Lattnerb55ab542009-01-05 08:18:44 +00006026 if (!EltTy->isFirstClassType())
6027 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028
6029 Inst = new VAArgInst(Op, EltTy);
6030 return false;
6031}
6032
6033/// ParseExtractElement
6034/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6035bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6036 LocTy Loc;
6037 Value *Op0, *Op1;
6038 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6039 ParseToken(lltok::comma, "expected ',' after extract value") ||
6040 ParseTypeAndValue(Op1, PFS))
6041 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006042
Chris Lattnerac161bf2009-01-02 07:01:27 +00006043 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6044 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006045
Eric Christopherc9742252009-07-25 02:28:41 +00006046 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006047 return false;
6048}
6049
6050/// ParseInsertElement
6051/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6052bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6053 LocTy Loc;
6054 Value *Op0, *Op1, *Op2;
6055 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6056 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6057 ParseTypeAndValue(Op1, PFS) ||
6058 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6059 ParseTypeAndValue(Op2, PFS))
6060 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006061
Chris Lattnerac161bf2009-01-02 07:01:27 +00006062 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006063 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006064
Chris Lattnerac161bf2009-01-02 07:01:27 +00006065 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6066 return false;
6067}
6068
6069/// ParseShuffleVector
6070/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6071bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6072 LocTy Loc;
6073 Value *Op0, *Op1, *Op2;
6074 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6075 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6076 ParseTypeAndValue(Op1, PFS) ||
6077 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6078 ParseTypeAndValue(Op2, PFS))
6079 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006080
Chris Lattnerac161bf2009-01-02 07:01:27 +00006081 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006082 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006083
Chris Lattnerac161bf2009-01-02 07:01:27 +00006084 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6085 return false;
6086}
6087
6088/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006089/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006090int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006091 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006092 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006093
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006094 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006095 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6096 ParseValue(Ty, Op0, PFS) ||
6097 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006098 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006099 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6100 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006101
Chris Lattnerf4f03422009-12-30 05:27:33 +00006102 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006103 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006104
6105 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006106 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006107
Chris Lattner3822f632009-01-02 08:05:26 +00006108 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006109 break;
6110
Chris Lattnerf4f03422009-12-30 05:27:33 +00006111 if (Lex.getKind() == lltok::MetadataVar) {
6112 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006113 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006114 }
Devang Patel8f842d32009-10-16 18:45:49 +00006115
Chris Lattner3822f632009-01-02 08:05:26 +00006116 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006117 ParseValue(Ty, Op0, PFS) ||
6118 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006119 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006120 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6121 return true;
6122 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006123
Chris Lattnerac161bf2009-01-02 07:01:27 +00006124 if (!Ty->isFirstClassType())
6125 return Error(TypeLoc, "phi node must have first class type");
6126
Jay Foad52131342011-03-30 11:28:46 +00006127 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006128 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6129 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6130 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006131 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132}
6133
Bill Wendlingfae14752011-08-12 20:24:12 +00006134/// ParseLandingPad
6135/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6136/// Clause
6137/// ::= 'catch' TypeAndValue
6138/// ::= 'filter'
6139/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6140bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006141 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006142
David Majnemer7fddecc2015-06-17 20:52:32 +00006143 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006144 return true;
6145
David Majnemer7fddecc2015-06-17 20:52:32 +00006146 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006147 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6148
6149 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6150 LandingPadInst::ClauseType CT;
6151 if (EatIfPresent(lltok::kw_catch))
6152 CT = LandingPadInst::Catch;
6153 else if (EatIfPresent(lltok::kw_filter))
6154 CT = LandingPadInst::Filter;
6155 else
6156 return TokError("expected 'catch' or 'filter' clause type");
6157
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006158 Value *V;
6159 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006160 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006161 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006162
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006163 // A 'catch' type expects a non-array constant. A filter clause expects an
6164 // array constant.
6165 if (CT == LandingPadInst::Catch) {
6166 if (isa<ArrayType>(V->getType()))
6167 Error(VLoc, "'catch' clause has an invalid type");
6168 } else {
6169 if (!isa<ArrayType>(V->getType()))
6170 Error(VLoc, "'filter' clause has an invalid type");
6171 }
6172
Owen Andersonf8f259d2015-03-09 07:13:42 +00006173 Constant *CV = dyn_cast<Constant>(V);
6174 if (!CV)
6175 return Error(VLoc, "clause argument must be a constant");
6176 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006177 }
6178
Owen Andersonf8f259d2015-03-09 07:13:42 +00006179 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006180 return false;
6181}
6182
Chris Lattnerac161bf2009-01-02 07:01:27 +00006183/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006184/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6185/// OptionalAttrs Type Value ParameterList OptionalAttrs
6186/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6187/// OptionalAttrs Type Value ParameterList OptionalAttrs
6188/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6189/// OptionalAttrs Type Value ParameterList OptionalAttrs
6190/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6191/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006192bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006193 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006194 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006195 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006196 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006197 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006198 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006199 LocTy RetTypeLoc;
6200 ValID CalleeID;
6201 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006202 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006203 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006204
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006205 if (TCK != CallInst::TCK_None &&
6206 ParseToken(lltok::kw_call,
6207 "expected 'tail call', 'musttail call', or 'notail call'"))
6208 return true;
6209
6210 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6211
6212 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006213 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006214 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006215 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6216 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006217 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6218 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006219 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006220
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006221 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6222 return Error(CallLoc, "fast-math-flags specified for call without "
6223 "floating-point scalar or vector return type");
6224
Chris Lattnerac161bf2009-01-02 07:01:27 +00006225 // If RetType is a non-function pointer type, then this is the short syntax
6226 // for the call, which means that RetType is just the return type. Infer the
6227 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006228 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6229 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006230 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006231 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006232 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6233 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006234
Chris Lattnerac161bf2009-01-02 07:01:27 +00006235 if (!FunctionType::isValidReturnType(RetType))
6236 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006237
Owen Anderson4056ca92009-07-29 22:17:13 +00006238 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006239 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006240
David Blaikie41ba2b42015-07-27 23:32:19 +00006241 CalleeID.FTy = Ty;
6242
Chris Lattnerac161bf2009-01-02 07:01:27 +00006243 // Look up the callee.
6244 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00006245 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6246 /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006247 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006248
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006249 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006250 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006251
Chris Lattnerac161bf2009-01-02 07:01:27 +00006252 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006253
Chris Lattnerac161bf2009-01-02 07:01:27 +00006254 // Loop through FunctionType's arguments and ensure they are specified
6255 // correctly. Also, gather any parameter attributes.
6256 FunctionType::param_iterator I = Ty->param_begin();
6257 FunctionType::param_iterator E = Ty->param_end();
6258 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006259 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006260 if (I != E) {
6261 ExpectedTy = *I++;
6262 } else if (!Ty->isVarArg()) {
6263 return Error(ArgList[i].Loc, "too many arguments specified");
6264 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006265
Chris Lattnerac161bf2009-01-02 07:01:27 +00006266 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6267 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006268 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006269 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006270 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006271 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006272
Chris Lattnerac161bf2009-01-02 07:01:27 +00006273 if (I != E)
6274 return Error(CallLoc, "not enough parameters specified for call");
6275
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006276 if (FnAttrs.hasAlignmentAttr())
6277 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006278
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006279 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006280 AttributeList PAL =
6281 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6282 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006283
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006284 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006285 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006286 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006287 if (FMF.any())
6288 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006289 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006290 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006291 Inst = CI;
6292 return false;
6293}
6294
6295//===----------------------------------------------------------------------===//
6296// Memory Instructions.
6297//===----------------------------------------------------------------------===//
6298
6299/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006300/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006301/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006302int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006303 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006304 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006305 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006306 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006307 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006308
6309 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006310 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006311
David Majnemera3b0eb22015-02-16 08:38:03 +00006312 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006313
David Majnemera3b0eb22015-02-16 08:38:03 +00006314 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6315 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006316
Chris Lattnerb2f39502009-12-30 05:44:30 +00006317 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006318 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006319 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006320 if (ParseOptionalAlignment(Alignment))
6321 return true;
6322 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6323 return true;
6324 } else if (Lex.getKind() == lltok::kw_addrspace) {
6325 ASLoc = Lex.getLoc();
6326 if (ParseOptionalAddrSpace(AddrSpace))
6327 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006328 } else if (Lex.getKind() == lltok::MetadataVar) {
6329 AteExtraComma = true;
6330 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006331 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006332 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006333 if (EatIfPresent(lltok::comma)) {
6334 if (Lex.getKind() == lltok::kw_align) {
6335 if (ParseOptionalAlignment(Alignment))
6336 return true;
6337 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6338 return true;
6339 } else if (Lex.getKind() == lltok::kw_addrspace) {
6340 ASLoc = Lex.getLoc();
6341 if (ParseOptionalAddrSpace(AddrSpace))
6342 return true;
6343 } else if (Lex.getKind() == lltok::MetadataVar) {
6344 AteExtraComma = true;
6345 }
6346 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006347 }
6348 }
6349
Dan Gohman2140a742010-05-28 01:14:11 +00006350 if (Size && !Size->getType()->isIntegerTy())
6351 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006352
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006353 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006354 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006355 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006356 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006357 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006358}
6359
6360/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006361/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006362/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006363/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006364int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006365 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006366 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006367 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006368 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006369 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006370 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006371
6372 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006373 isAtomic = true;
6374 Lex.Lex();
6375 }
6376
Chris Lattnerbc639292011-11-27 06:56:53 +00006377 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006378 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006379 isVolatile = true;
6380 Lex.Lex();
6381 }
6382
David Blaikie15d9a4c2015-04-06 20:59:48 +00006383 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006384 LocTy ExplicitTypeLoc = Lex.getLoc();
6385 if (ParseType(Ty) ||
6386 ParseToken(lltok::comma, "expected comma after load's type") ||
6387 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006388 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006389 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6390 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391
David Blaikie15d9a4c2015-04-06 20:59:48 +00006392 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006393 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006394 if (isAtomic && !Alignment)
6395 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006396 if (Ordering == AtomicOrdering::Release ||
6397 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006398 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006399
David Blaikiea79ac142015-02-27 21:17:42 +00006400 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6401 return Error(ExplicitTypeLoc,
6402 "explicit pointee type doesn't match operand's pointee type");
6403
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006404 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006405 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006406}
6407
6408/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006409
6410/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6411/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006412/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006413int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006414 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006415 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006416 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006417 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006418 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006419 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006420
6421 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006422 isAtomic = true;
6423 Lex.Lex();
6424 }
6425
Chris Lattnerbc639292011-11-27 06:56:53 +00006426 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006427 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006428 isVolatile = true;
6429 Lex.Lex();
6430 }
6431
Chris Lattnerac161bf2009-01-02 07:01:27 +00006432 if (ParseTypeAndValue(Val, Loc, PFS) ||
6433 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006434 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006435 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006436 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006437 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006438
Duncan Sands19d0b472010-02-16 11:11:14 +00006439 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006440 return Error(PtrLoc, "store operand must be a pointer");
6441 if (!Val->getType()->isFirstClassType())
6442 return Error(Loc, "store operand must be a first class value");
6443 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6444 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006445 if (isAtomic && !Alignment)
6446 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006447 if (Ordering == AtomicOrdering::Acquire ||
6448 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006449 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006450
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006451 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006452 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006453}
6454
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006455/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006456/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6457/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006458int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006459 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6460 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006461 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6462 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006463 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006464 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006465 bool isWeak = false;
6466
6467 if (EatIfPresent(lltok::kw_weak))
6468 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006469
6470 if (EatIfPresent(lltok::kw_volatile))
6471 isVolatile = true;
6472
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006473 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6474 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6475 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6476 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6477 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006478 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006479 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006480 return true;
6481
JF Bastien800f87a2016-04-06 21:19:33 +00006482 if (SuccessOrdering == AtomicOrdering::Unordered ||
6483 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006484 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006485 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6486 return TokError("cmpxchg failure argument shall be no stronger than the "
6487 "success argument");
6488 if (FailureOrdering == AtomicOrdering::Release ||
6489 FailureOrdering == AtomicOrdering::AcquireRelease)
6490 return TokError(
6491 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006492 if (!Ptr->getType()->isPointerTy())
6493 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6494 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6495 return Error(CmpLoc, "compare value and pointer type do not match");
6496 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6497 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006498 if (!New->getType()->isFirstClassType())
6499 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006500 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006501 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006502 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006503 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006504 Inst = CXI;
6505 return AteExtraComma ? InstExtraComma : InstNormal;
6506}
6507
6508/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006509/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6510/// 'singlethread'? AtomicOrdering
6511int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006512 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6513 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006514 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006515 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006516 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006517 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006518
6519 if (EatIfPresent(lltok::kw_volatile))
6520 isVolatile = true;
6521
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006522 switch (Lex.getKind()) {
6523 default: return TokError("expected binary operation in atomicrmw");
6524 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6525 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6526 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6527 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6528 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6529 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6530 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6531 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6532 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6533 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6534 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6535 }
6536 Lex.Lex(); // Eat the operation.
6537
6538 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6539 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6540 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006541 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006542 return true;
6543
JF Bastien800f87a2016-04-06 21:19:33 +00006544 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006545 return TokError("atomicrmw cannot be unordered");
6546 if (!Ptr->getType()->isPointerTy())
6547 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6548 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6549 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6550 if (!Val->getType()->isIntegerTy())
6551 return Error(ValLoc, "atomicrmw operand must be an integer");
6552 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6553 if (Size < 8 || (Size & (Size - 1)))
6554 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6555 " integer");
6556
6557 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006558 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006559 RMWI->setVolatile(isVolatile);
6560 Inst = RMWI;
6561 return AteExtraComma ? InstExtraComma : InstNormal;
6562}
6563
Eli Friedmanfee02c62011-07-25 23:16:38 +00006564/// ParseFence
6565/// ::= 'fence' 'singlethread'? AtomicOrdering
6566int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006567 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006568 SyncScope::ID SSID = SyncScope::System;
6569 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006570 return true;
6571
JF Bastien800f87a2016-04-06 21:19:33 +00006572 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006573 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006574 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006575 return TokError("fence cannot be monotonic");
6576
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006577 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006578 return InstNormal;
6579}
6580
Chris Lattnerac161bf2009-01-02 07:01:27 +00006581/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006582/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006583int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006584 Value *Ptr = nullptr;
6585 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006586 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006587
Dan Gohman16cbbe42009-07-29 15:58:36 +00006588 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006589
David Blaikie79e6c742015-02-27 19:29:02 +00006590 Type *Ty = nullptr;
6591 LocTy ExplicitTypeLoc = Lex.getLoc();
6592 if (ParseType(Ty) ||
6593 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6594 ParseTypeAndValue(Ptr, Loc, PFS))
6595 return true;
6596
Eli Benderskyd9806682013-04-22 17:03:42 +00006597 Type *BaseType = Ptr->getType();
6598 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6599 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006600 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006601
David Blaikie8d757942015-03-09 23:08:44 +00006602 if (Ty != BasePointerType->getElementType())
6603 return Error(ExplicitTypeLoc,
6604 "explicit pointee type doesn't match operand's pointee type");
6605
Chris Lattnerac161bf2009-01-02 07:01:27 +00006606 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006607 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006608 // GEP returns a vector of pointers if at least one of parameters is a vector.
6609 // All vector parameters should have the same vector width.
6610 unsigned GEPWidth = BaseType->isVectorTy() ?
6611 BaseType->getVectorNumElements() : 0;
6612
Chris Lattner3822f632009-01-02 08:05:26 +00006613 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006614 if (Lex.getKind() == lltok::MetadataVar) {
6615 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006616 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006617 }
Chris Lattner3822f632009-01-02 08:05:26 +00006618 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006619 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006620 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006621
Nadav Rotem3924cb02011-12-05 06:29:09 +00006622 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006623 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6624 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006625 return Error(EltLoc,
6626 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006627 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006628 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006629 Indices.push_back(Val);
6630 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006631
Craig Toppere3dcce92015-08-01 22:20:21 +00006632 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006633 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006634 return Error(Loc, "base element of getelementptr must be sized");
6635
David Blaikied33bad32015-04-17 22:32:13 +00006636 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006637 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006638 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006639 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006640 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006641 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006642}
6643
6644/// ParseExtractValue
6645/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006646int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006647 Value *Val; LocTy Loc;
6648 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006649 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006650 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006651 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006652 return true;
6653
Chris Lattner392be582010-02-12 20:49:41 +00006654 if (!Val->getType()->isAggregateType())
6655 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006656
Jay Foad57aa6362011-07-13 10:26:04 +00006657 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006658 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006659 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006660 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006661}
6662
6663/// ParseInsertValue
6664/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006665int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006666 Value *Val0, *Val1; LocTy Loc0, Loc1;
6667 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006668 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006669 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6670 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6671 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006672 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006673 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006674
Chris Lattner392be582010-02-12 20:49:41 +00006675 if (!Val0->getType()->isAggregateType())
6676 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006677
David Majnemer30074532015-02-11 07:43:58 +00006678 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6679 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006680 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006681 if (IndexedType != Val1->getType())
6682 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6683 getTypeString(Val1->getType()) + "' instead of '" +
6684 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006685 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006686 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006687}
Nick Lewycky49f89192009-04-04 07:22:01 +00006688
6689//===----------------------------------------------------------------------===//
6690// Embedded metadata.
6691//===----------------------------------------------------------------------===//
6692
6693/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006694/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006695/// Element
6696/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006697bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006698 if (ParseToken(lltok::lbrace, "expected '{' here"))
6699 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006700
Dan Gohman1e0213a2010-07-13 19:33:27 +00006701 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006702 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006703 return false;
6704
Nick Lewycky49f89192009-04-04 07:22:01 +00006705 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006706 // Null is a special case since it is typeless.
6707 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006708 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006709 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006710 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006711
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006712 Metadata *MD;
6713 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006714 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006715 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006716 } while (EatIfPresent(lltok::comma));
6717
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006718 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006719}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006720
6721//===----------------------------------------------------------------------===//
6722// Use-list order directives.
6723//===----------------------------------------------------------------------===//
6724bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6725 SMLoc Loc) {
6726 if (V->use_empty())
6727 return Error(Loc, "value has no uses");
6728
6729 unsigned NumUses = 0;
6730 SmallDenseMap<const Use *, unsigned, 16> Order;
6731 for (const Use &U : V->uses()) {
6732 if (++NumUses > Indexes.size())
6733 break;
6734 Order[&U] = Indexes[NumUses - 1];
6735 }
6736 if (NumUses < 2)
6737 return Error(Loc, "value only has one use");
6738 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6739 return Error(Loc, "wrong number of indexes, expected " +
6740 Twine(std::distance(V->use_begin(), V->use_end())));
6741
6742 V->sortUseList([&](const Use &L, const Use &R) {
6743 return Order.lookup(&L) < Order.lookup(&R);
6744 });
6745 return false;
6746}
6747
6748/// ParseUseListOrderIndexes
6749/// ::= '{' uint32 (',' uint32)+ '}'
6750bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6751 SMLoc Loc = Lex.getLoc();
6752 if (ParseToken(lltok::lbrace, "expected '{' here"))
6753 return true;
6754 if (Lex.getKind() == lltok::rbrace)
6755 return Lex.Error("expected non-empty list of uselistorder indexes");
6756
6757 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6758 // indexes should be distinct numbers in the range [0, size-1], and should
6759 // not be in order.
6760 unsigned Offset = 0;
6761 unsigned Max = 0;
6762 bool IsOrdered = true;
6763 assert(Indexes.empty() && "Expected empty order vector");
6764 do {
6765 unsigned Index;
6766 if (ParseUInt32(Index))
6767 return true;
6768
6769 // Update consistency checks.
6770 Offset += Index - Indexes.size();
6771 Max = std::max(Max, Index);
6772 IsOrdered &= Index == Indexes.size();
6773
6774 Indexes.push_back(Index);
6775 } while (EatIfPresent(lltok::comma));
6776
6777 if (ParseToken(lltok::rbrace, "expected '}' here"))
6778 return true;
6779
6780 if (Indexes.size() < 2)
6781 return Error(Loc, "expected >= 2 uselistorder indexes");
6782 if (Offset != 0 || Max >= Indexes.size())
6783 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6784 if (IsOrdered)
6785 return Error(Loc, "expected uselistorder indexes to change the order");
6786
6787 return false;
6788}
6789
6790/// ParseUseListOrder
6791/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6792bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6793 SMLoc Loc = Lex.getLoc();
6794 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6795 return true;
6796
6797 Value *V;
6798 SmallVector<unsigned, 16> Indexes;
6799 if (ParseTypeAndValue(V, PFS) ||
6800 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6801 ParseUseListOrderIndexes(Indexes))
6802 return true;
6803
6804 return sortUseListOrder(V, Indexes, Loc);
6805}
6806
6807/// ParseUseListOrderBB
6808/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6809bool LLParser::ParseUseListOrderBB() {
6810 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6811 SMLoc Loc = Lex.getLoc();
6812 Lex.Lex();
6813
6814 ValID Fn, Label;
6815 SmallVector<unsigned, 16> Indexes;
6816 if (ParseValID(Fn) ||
6817 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6818 ParseValID(Label) ||
6819 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6820 ParseUseListOrderIndexes(Indexes))
6821 return true;
6822
6823 // Check the function.
6824 GlobalValue *GV;
6825 if (Fn.Kind == ValID::t_GlobalName)
6826 GV = M->getNamedValue(Fn.StrVal);
6827 else if (Fn.Kind == ValID::t_GlobalID)
6828 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6829 else
6830 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6831 if (!GV)
6832 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6833 auto *F = dyn_cast<Function>(GV);
6834 if (!F)
6835 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6836 if (F->isDeclaration())
6837 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6838
6839 // Check the basic block.
6840 if (Label.Kind == ValID::t_LocalID)
6841 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6842 if (Label.Kind != ValID::t_LocalName)
6843 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006844 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006845 if (!V)
6846 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6847 if (!isa<BasicBlock>(V))
6848 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6849
6850 return sortUseListOrder(V, Indexes, Loc);
6851}