blob: 52c5b9fb29a557619d057572eb03c58472d77195 [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;
Chris Lattner3822f632009-01-02 08:05:26 +0000330 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000331 return false;
332 }
333}
334
Bill Wendling706d3d62012-11-28 08:41:48 +0000335/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000336/// ::= 'source_filename' '=' STRINGCONSTANT
337bool LLParser::ParseSourceFileName() {
338 assert(Lex.getKind() == lltok::kw_source_filename);
339 std::string Str;
340 Lex.Lex();
341 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
342 ParseStringConstant(Str))
343 return true;
344 M->setSourceFileName(Str);
345 return false;
346}
347
348/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000349/// ::= 'deplibs' '=' '[' ']'
350/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
351/// FIXME: Remove in 4.0. Currently parse, but ignore.
352bool LLParser::ParseDepLibs() {
353 assert(Lex.getKind() == lltok::kw_deplibs);
354 Lex.Lex();
355 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
356 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
357 return true;
358
359 if (EatIfPresent(lltok::rsquare))
360 return false;
361
362 do {
363 std::string Str;
364 if (ParseStringConstant(Str)) return true;
365 } while (EatIfPresent(lltok::comma));
366
367 return ParseToken(lltok::rsquare, "expected ']' at end of list");
368}
369
Dan Gohman466876b2009-08-12 23:32:33 +0000370/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000371/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000372bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000373 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000374 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000375 Lex.Lex(); // eat LocalVarID;
376
377 if (ParseToken(lltok::equal, "expected '=' after name") ||
378 ParseToken(lltok::kw_type, "expected 'type' after '='"))
379 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380
Craig Topper2617dcc2014-04-15 06:32:26 +0000381 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382 if (ParseStructDefinition(TypeLoc, "",
383 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000385 if (!isa<StructType>(Result)) {
386 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
387 if (Entry.first)
388 return Error(TypeLoc, "non-struct types may not be recursive");
389 Entry.first = Result;
390 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000392
Chris Lattnerac161bf2009-01-02 07:01:27 +0000393 return false;
394}
395
396/// toplevelentity
397/// ::= LocalVar '=' 'type' type
398bool LLParser::ParseNamedType() {
399 std::string Name = Lex.getStrVal();
400 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000401 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000402
Chris Lattner3822f632009-01-02 08:05:26 +0000403 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000404 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000405 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000406
Craig Topper2617dcc2014-04-15 06:32:26 +0000407 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000408 if (ParseStructDefinition(NameLoc, Name,
409 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000411 if (!isa<StructType>(Result)) {
412 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
413 if (Entry.first)
414 return Error(NameLoc, "non-struct types may not be recursive");
415 Entry.first = Result;
416 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000417 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420}
421
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422/// toplevelentity
423/// ::= 'declare' FunctionHeader
424bool LLParser::ParseDeclare() {
425 assert(Lex.getKind() == lltok::kw_declare);
426 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000427
Peter Collingbourne21521892016-06-21 23:42:48 +0000428 std::vector<std::pair<unsigned, MDNode *>> MDs;
429 while (Lex.getKind() == lltok::MetadataVar) {
430 unsigned MDK;
431 MDNode *N;
432 if (ParseMetadataAttachment(MDK, N))
433 return true;
434 MDs.push_back({MDK, N});
435 }
436
Chris Lattnerac161bf2009-01-02 07:01:27 +0000437 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000438 if (ParseFunctionHeader(F, false))
439 return true;
440 for (auto &MD : MDs)
441 F->addMetadata(MD.first, *MD.second);
442 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443}
444
445/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000446/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000447bool LLParser::ParseDefine() {
448 assert(Lex.getKind() == lltok::kw_define);
449 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000450
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000452 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000453 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000454 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000455}
456
Chris Lattner3822f632009-01-02 08:05:26 +0000457/// ParseGlobalType
458/// ::= 'constant'
459/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000460bool LLParser::ParseGlobalType(bool &IsConstant) {
461 if (Lex.getKind() == lltok::kw_constant)
462 IsConstant = true;
463 else if (Lex.getKind() == lltok::kw_global)
464 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000465 else {
466 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000468 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000469 Lex.Lex();
470 return false;
471}
472
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000473bool LLParser::ParseOptionalUnnamedAddr(
474 GlobalVariable::UnnamedAddr &UnnamedAddr) {
475 if (EatIfPresent(lltok::kw_unnamed_addr))
476 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
477 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
478 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
479 else
480 UnnamedAddr = GlobalValue::UnnamedAddr::None;
481 return false;
482}
483
Dan Gohman466876b2009-08-12 23:32:33 +0000484/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000485/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000486/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000488/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000489/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
490/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000491bool LLParser::ParseUnnamedGlobal() {
492 unsigned VarID = NumberedVals.size();
493 std::string Name;
494 LocTy NameLoc = Lex.getLoc();
495
496 // Handle the GlobalID form.
497 if (Lex.getKind() == lltok::GlobalID) {
498 if (Lex.getUIntVal() != VarID)
499 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000500 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000501 Lex.Lex(); // eat GlobalID;
502
503 if (ParseToken(lltok::equal, "expected '=' after name"))
504 return true;
505 }
506
507 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000508 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000509 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000510 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000511 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000512 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000513 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000514
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000515 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000516 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000517 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000518
519 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
520 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000521}
522
Chris Lattnerac161bf2009-01-02 07:01:27 +0000523/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000524/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000525/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
526/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000527bool LLParser::ParseNamedGlobal() {
528 assert(Lex.getKind() == lltok::GlobalVar);
529 LocTy NameLoc = Lex.getLoc();
530 std::string Name = Lex.getStrVal();
531 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000532
Chris Lattnerac161bf2009-01-02 07:01:27 +0000533 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000534 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000535 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000536 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000537 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000538 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000539 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000540 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000541
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000542 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000543 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000544 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000545
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000546 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
547 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000548}
549
David Majnemerdad0a642014-06-27 18:19:56 +0000550bool LLParser::parseComdat() {
551 assert(Lex.getKind() == lltok::ComdatVar);
552 std::string Name = Lex.getStrVal();
553 LocTy NameLoc = Lex.getLoc();
554 Lex.Lex();
555
556 if (ParseToken(lltok::equal, "expected '=' here"))
557 return true;
558
559 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
560 return TokError("expected comdat type");
561
562 Comdat::SelectionKind SK;
563 switch (Lex.getKind()) {
564 default:
565 return TokError("unknown selection kind");
566 case lltok::kw_any:
567 SK = Comdat::Any;
568 break;
569 case lltok::kw_exactmatch:
570 SK = Comdat::ExactMatch;
571 break;
572 case lltok::kw_largest:
573 SK = Comdat::Largest;
574 break;
575 case lltok::kw_noduplicates:
576 SK = Comdat::NoDuplicates;
577 break;
578 case lltok::kw_samesize:
579 SK = Comdat::SameSize;
580 break;
581 }
582 Lex.Lex();
583
584 // See if the comdat was forward referenced, if so, use the comdat.
585 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
586 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
587 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
588 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
589
590 Comdat *C;
591 if (I != ComdatSymTab.end())
592 C = &I->second;
593 else
594 C = M->getOrInsertComdat(Name);
595 C->setSelectionKind(SK);
596
597 return false;
598}
599
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000600// MDString:
601// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000602bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603 std::string Str;
604 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000605 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000606 return false;
607}
608
609// MDNode:
610// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000611bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000613 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000614 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000615 if (ParseUInt32(MID))
616 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000617
Chris Lattner8eff0152010-04-01 05:14:45 +0000618 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000619 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000620 Result = NumberedMetadata[MID];
621 return false;
622 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000623
Chris Lattner8eff0152010-04-01 05:14:45 +0000624 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000625 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000626 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000627
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000628 Result = FwdRef.first.get();
629 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000630 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000631}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000632
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000633/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000634/// !foo = !{ !1, !2 }
635bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000636 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000637 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000638 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000639
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000640 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000641 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000642 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000643 return true;
644
Dan Gohman2637cc12010-07-21 23:38:33 +0000645 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 if (Lex.getKind() != lltok::rbrace)
647 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000648 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000649 // Parse DIExpressions inline as a special case. They are still MDNodes,
650 // so they can still appear in named metadata. Remove this logic if they
651 // become plain Metadata.
652 if (Lex.getKind() == lltok::MetadataVar &&
653 Lex.getStrVal() == "DIExpression") {
654 if (ParseDIExpression(N, /*IsDistinct=*/false))
655 return true;
656 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
657 ParseMDNodeID(N)) {
658 return true;
659 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000660 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000661 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000662
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000663 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000664}
665
Devang Patel39e64d42009-07-01 19:21:12 +0000666/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000667/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000668bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000669 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000670 Lex.Lex();
671 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000672
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000673 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000674 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000675 ParseToken(lltok::equal, "expected '=' here"))
676 return true;
677
678 // Detect common error, from old metadata syntax.
679 if (Lex.getKind() == lltok::Type)
680 return TokError("unexpected type in metadata definition");
681
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000682 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000683 if (Lex.getKind() == lltok::MetadataVar) {
684 if (ParseSpecializedMDNode(Init, IsDistinct))
685 return true;
686 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
687 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000688 return true;
689
Chris Lattnerfc58af22009-12-30 04:51:58 +0000690 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000691 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000692 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000693 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000694 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000695
Chris Lattnerfc58af22009-12-30 04:51:58 +0000696 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
697 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000698 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000699 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000700 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000701 }
702
Devang Patel39e64d42009-07-01 19:21:12 +0000703 return false;
704}
705
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000706static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
707 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
708 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
709}
710
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000711/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000712/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
713/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000714/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000715///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000716/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000717/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000718///
Eric Christopher536f0a92015-05-28 23:07:39 +0000719/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000721bool LLParser::parseIndirectSymbol(
722 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
723 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
724 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000725 bool IsAlias;
726 if (Lex.getKind() == lltok::kw_alias)
727 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000728 else if (Lex.getKind() == lltok::kw_ifunc)
729 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000730 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000731 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000732 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000733
Rafael Espindola78527052013-10-06 15:10:43 +0000734 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
735
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000736 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000737 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000738
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000739 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000740 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000741 "symbol with local linkage must have default visibility");
742
David Blaikie2f408302015-09-11 03:22:04 +0000743 Type *Ty;
744 LocTy ExplicitTypeLoc = Lex.getLoc();
745 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000746 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000747 return true;
748
Rafael Espindola64c1e182014-06-03 02:41:57 +0000749 Constant *Aliasee;
750 LocTy AliaseeLoc = Lex.getLoc();
751 if (Lex.getKind() != lltok::kw_bitcast &&
752 Lex.getKind() != lltok::kw_getelementptr &&
753 Lex.getKind() != lltok::kw_addrspacecast &&
754 Lex.getKind() != lltok::kw_inttoptr) {
755 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000756 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000757 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000758 // The bitcast dest type is not present, it is implied by the dest type.
759 ValID ID;
760 if (ParseValID(ID))
761 return true;
762 if (ID.Kind != ValID::t_Constant)
763 return Error(AliaseeLoc, "invalid aliasee");
764 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000766
Rafael Espindola64c1e182014-06-03 02:41:57 +0000767 Type *AliaseeType = Aliasee->getType();
768 auto *PTy = dyn_cast<PointerType>(AliaseeType);
769 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000770 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000771 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000772
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000773 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000774 return Error(
775 ExplicitTypeLoc,
776 "explicit pointee type doesn't match operand's pointee type");
777
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000778 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
779 return Error(
780 ExplicitTypeLoc,
781 "explicit pointee type should be a function type");
782
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000783 GlobalValue *GVal = nullptr;
784
785 // See if the alias was forward referenced, if so, prepare to replace the
786 // forward reference.
787 if (!Name.empty()) {
788 GVal = M->getNamedValue(Name);
789 if (GVal) {
790 if (!ForwardRefVals.erase(Name))
791 return Error(NameLoc, "redefinition of global '@" + Name + "'");
792 }
793 } else {
794 auto I = ForwardRefValIDs.find(NumberedVals.size());
795 if (I != ForwardRefValIDs.end()) {
796 GVal = I->second.first;
797 ForwardRefValIDs.erase(I);
798 }
799 }
800
Chris Lattnerac161bf2009-01-02 07:01:27 +0000801 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000802 std::unique_ptr<GlobalIndirectSymbol> GA;
803 if (IsAlias)
804 GA.reset(GlobalAlias::create(Ty, AddrSpace,
805 (GlobalValue::LinkageTypes)Linkage, Name,
806 Aliasee, /*Parent*/ nullptr));
807 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000808 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
809 (GlobalValue::LinkageTypes)Linkage, Name,
810 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000811 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000813 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000814 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
Rafael Espindola54fc2982015-06-17 17:53:31 +0000816 if (Name.empty())
817 NumberedVals.push_back(GA.get());
818
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000819 if (GVal) {
820 // Verify that types agree.
821 if (GVal->getType() != GA->getType())
822 return Error(
823 ExplicitTypeLoc,
824 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000825
Chris Lattnerac161bf2009-01-02 07:01:27 +0000826 // If they agree, just RAUW the old value with the alias and remove the
827 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000828 GVal->replaceAllUsesWith(GA.get());
829 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
Chris Lattnerac161bf2009-01-02 07:01:27 +0000832 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000833 if (IsAlias)
834 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
835 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000836 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000837 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000838
Rafael Espindolaaa273822014-05-09 21:49:17 +0000839 // The module owns this now
840 GA.release();
841
Chris Lattnerac161bf2009-01-02 07:01:27 +0000842 return false;
843}
844
845/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000846/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000847/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000848/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Nico Rieck7157bb72014-01-14 15:22:47 +0000849/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000850/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000851/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000852///
Eric Christopher536f0a92015-05-28 23:07:39 +0000853/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000854/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000855///
856bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
857 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000858 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000859 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000860 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000861 if (!isValidVisibilityForLinkage(Visibility, Linkage))
862 return Error(NameLoc,
863 "symbol with local linkage must have default visibility");
864
Chris Lattnerac161bf2009-01-02 07:01:27 +0000865 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000866 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000867 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
Craig Topper2617dcc2014-04-15 06:32:26 +0000870 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000871 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000872 ParseOptionalToken(lltok::kw_externally_initialized,
873 IsExternallyInitialized,
874 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000875 ParseGlobalType(IsConstant) ||
876 ParseType(Ty, TyLoc))
877 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000878
Chris Lattnerac161bf2009-01-02 07:01:27 +0000879 // If the linkage is specified and is external, then no initializer is
880 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000881 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000882 if (!HasLinkage ||
883 !GlobalValue::isValidDeclarationLinkage(
884 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000885 if (ParseGlobalValue(Ty, Init))
886 return true;
887 }
888
David Majnemer49b3d9b2015-02-16 08:41:08 +0000889 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000890 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000891
David Majnemer598bd052014-12-09 05:56:09 +0000892 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000893
894 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000895 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000896 GVal = M->getNamedValue(Name);
897 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000898 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000899 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000900 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000901 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000902 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000903 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000904 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 ForwardRefValIDs.erase(I);
906 }
907 }
908
David Majnemer598bd052014-12-09 05:56:09 +0000909 GlobalVariable *GV;
910 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000911 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
912 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000913 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000914 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000915 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000916 return Error(TyLoc,
917 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000918
David Majnemer598bd052014-12-09 05:56:09 +0000919 GV = cast<GlobalVariable>(GVal);
920
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 // Move the forward-reference to the correct spot in the module.
922 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
923 }
924
925 if (Name.empty())
926 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000927
Chris Lattnerac161bf2009-01-02 07:01:27 +0000928 // Set the parsed properties on the global.
929 if (Init)
930 GV->setInitializer(Init);
931 GV->setConstant(IsConstant);
932 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
933 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000934 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000935 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000936 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000937 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
Chris Lattnerac161bf2009-01-02 07:01:27 +0000939 // Parse attributes on the global.
940 while (Lex.getKind() == lltok::comma) {
941 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000942
Chris Lattnerac161bf2009-01-02 07:01:27 +0000943 if (Lex.getKind() == lltok::kw_section) {
944 Lex.Lex();
945 GV->setSection(Lex.getStrVal());
946 if (ParseToken(lltok::StringConstant, "expected global section string"))
947 return true;
948 } else if (Lex.getKind() == lltok::kw_align) {
949 unsigned Alignment;
950 if (ParseOptionalAlignment(Alignment)) return true;
951 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000952 } else if (Lex.getKind() == lltok::MetadataVar) {
953 if (ParseGlobalObjectMetadataAttachment(*GV))
954 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000955 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000956 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000957 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000958 return true;
959 if (C)
960 GV->setComdat(C);
961 else
962 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000963 }
964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000965
Javed Absarf3d79042017-05-11 12:28:08 +0000966 AttrBuilder Attrs;
967 LocTy BuiltinLoc;
968 std::vector<unsigned> FwdRefAttrGrps;
969 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
970 return true;
971 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
972 GV->setAttributes(AttributeSet::get(Context, Attrs));
973 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
974 }
975
Chris Lattnerac161bf2009-01-02 07:01:27 +0000976 return false;
977}
978
Bill Wendling63b88192013-02-06 06:52:58 +0000979/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000980/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000981bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000982 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000983 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000984 Lex.Lex();
985
David Majnemerb39e22b2014-12-09 18:33:57 +0000986 if (Lex.getKind() != lltok::AttrGrpID)
987 return TokError("expected attribute group id");
988
Bill Wendling63b88192013-02-06 06:52:58 +0000989 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000990 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000991 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000992 Lex.Lex();
993
994 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000995 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000996 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000997 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000998 ParseToken(lltok::rbrace, "expected end of attribute group"))
999 return true;
1000
Bill Wendlingb32b0412013-02-08 06:32:06 +00001001 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001002 return Error(AttrGrpLoc, "attribute group has no attributes");
1003
1004 return false;
1005}
1006
Bill Wendling8b0321d2013-02-08 00:52:31 +00001007/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001008/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001009bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1010 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001011 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001012 bool HaveError = false;
1013
1014 B.clear();
1015
Bill Wendling63b88192013-02-06 06:52:58 +00001016 while (true) {
1017 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001018 if (Token == lltok::kw_builtin)
1019 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001020 switch (Token) {
1021 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001022 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001023 return Error(Lex.getLoc(), "unterminated attribute group");
1024 case lltok::rbrace:
1025 // Finished.
1026 return false;
1027
Bill Wendlingb32b0412013-02-08 06:32:06 +00001028 case lltok::AttrGrpID: {
1029 // Allow a function to reference an attribute group:
1030 //
1031 // define void @foo() #1 { ... }
1032 if (inAttrGrp)
1033 HaveError |=
1034 Error(Lex.getLoc(),
1035 "cannot have an attribute group reference in an attribute group");
1036
1037 unsigned AttrGrpNum = Lex.getUIntVal();
1038 if (inAttrGrp) break;
1039
1040 // Save the reference to the attribute group. We'll fill it in later.
1041 FwdRefAttrGrps.push_back(AttrGrpNum);
1042 break;
1043 }
Bill Wendling63b88192013-02-06 06:52:58 +00001044 // Target-dependent attributes:
1045 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001046 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001047 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001048 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001049 }
1050
1051 // Target-independent attributes:
1052 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001053 // As a hack, we allow function alignment to be initially parsed as an
1054 // attribute on a function declaration/definition or added to an attribute
1055 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001056 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001057 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001058 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001059 if (ParseToken(lltok::equal, "expected '=' here") ||
1060 ParseUInt32(Alignment))
1061 return true;
1062 } else {
1063 if (ParseOptionalAlignment(Alignment))
1064 return true;
1065 }
Bill Wendling63b88192013-02-06 06:52:58 +00001066 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001067 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001068 }
1069 case lltok::kw_alignstack: {
1070 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001071 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001072 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001073 if (ParseToken(lltok::equal, "expected '=' here") ||
1074 ParseUInt32(Alignment))
1075 return true;
1076 } else {
1077 if (ParseOptionalStackAlignment(Alignment))
1078 return true;
1079 }
Bill Wendling63b88192013-02-06 06:52:58 +00001080 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001081 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001082 }
George Burgess IV278199f2016-04-12 01:05:35 +00001083 case lltok::kw_allocsize: {
1084 unsigned ElemSizeArg;
1085 Optional<unsigned> NumElemsArg;
1086 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1087 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1088 return true;
1089 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1090 continue;
1091 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001092 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1093 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1094 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1095 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1096 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001097 case lltok::kw_inaccessiblememonly:
1098 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1099 case lltok::kw_inaccessiblemem_or_argmemonly:
1100 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001101 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1102 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1103 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1104 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1105 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1106 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1107 case lltok::kw_noimplicitfloat:
1108 B.addAttribute(Attribute::NoImplicitFloat); break;
1109 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1110 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1111 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1112 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001113 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001114 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1115 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1116 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1117 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1118 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1119 case lltok::kw_returns_twice:
1120 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001121 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001122 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1123 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1124 case lltok::kw_sspstrong:
1125 B.addAttribute(Attribute::StackProtectStrong); break;
1126 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1127 case lltok::kw_sanitize_address:
1128 B.addAttribute(Attribute::SanitizeAddress); break;
1129 case lltok::kw_sanitize_thread:
1130 B.addAttribute(Attribute::SanitizeThread); break;
1131 case lltok::kw_sanitize_memory:
1132 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001133 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001134 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001135 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001136
1137 // Error handling.
1138 case lltok::kw_inreg:
1139 case lltok::kw_signext:
1140 case lltok::kw_zeroext:
1141 HaveError |=
1142 Error(Lex.getLoc(),
1143 "invalid use of attribute on a function");
1144 break;
1145 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001146 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001147 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001148 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001149 case lltok::kw_nest:
1150 case lltok::kw_noalias:
1151 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001152 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001153 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001154 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001155 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001156 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001157 HaveError |=
1158 Error(Lex.getLoc(),
1159 "invalid use of parameter-only attribute on a function");
1160 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001161 }
1162
1163 Lex.Lex();
1164 }
1165}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166
1167//===----------------------------------------------------------------------===//
1168// GlobalValue Reference/Resolution Routines.
1169//===----------------------------------------------------------------------===//
1170
Karl Schimpf77729782015-09-03 18:06:44 +00001171static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1172 const std::string &Name) {
1173 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1174 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1175 else
1176 return new GlobalVariable(*M, PTy->getElementType(), false,
1177 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1178 nullptr, GlobalVariable::NotThreadLocal,
1179 PTy->getAddressSpace());
1180}
1181
Chris Lattnerac161bf2009-01-02 07:01:27 +00001182/// GetGlobalVal - Get a value with the specified name or ID, creating a
1183/// forward reference record if needed. This can return null if the value
1184/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001185GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001186 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001187 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001188 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001189 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001190 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001192
Chris Lattnerac161bf2009-01-02 07:01:27 +00001193 // Look this name up in the normal function symbol table.
1194 GlobalValue *Val =
1195 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001196
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 // If this is a forward reference for the value, see if we already created a
1198 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001199 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001200 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 if (I != ForwardRefVals.end())
1202 Val = I->second.first;
1203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001204
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 // If we have the value in the symbol table or fwd-ref table, return it.
1206 if (Val) {
1207 if (Val->getType() == Ty) return Val;
1208 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001209 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001210 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001211 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001212
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001214 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001215 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1216 return FwdVal;
1217}
1218
Chris Lattner229907c2011-07-18 04:54:35 +00001219GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1220 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001221 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001223 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001225
Craig Topper2617dcc2014-04-15 06:32:26 +00001226 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001227
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 // If this is a forward reference for the value, see if we already created a
1229 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001230 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001231 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232 if (I != ForwardRefValIDs.end())
1233 Val = I->second.first;
1234 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001235
Chris Lattnerac161bf2009-01-02 07:01:27 +00001236 // If we have the value in the symbol table or fwd-ref table, return it.
1237 if (Val) {
1238 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001239 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001240 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001241 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001243
Chris Lattnerac161bf2009-01-02 07:01:27 +00001244 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001245 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001246 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1247 return FwdVal;
1248}
1249
Chris Lattnerac161bf2009-01-02 07:01:27 +00001250//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001251// Comdat Reference/Resolution Routines.
1252//===----------------------------------------------------------------------===//
1253
1254Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1255 // Look this name up in the comdat symbol table.
1256 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1257 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1258 if (I != ComdatSymTab.end())
1259 return &I->second;
1260
1261 // Otherwise, create a new forward reference for this value and remember it.
1262 Comdat *C = M->getOrInsertComdat(Name);
1263 ForwardRefComdats[Name] = Loc;
1264 return C;
1265}
1266
David Majnemerdad0a642014-06-27 18:19:56 +00001267//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001268// Helper Routines.
1269//===----------------------------------------------------------------------===//
1270
1271/// ParseToken - If the current token has the specified kind, eat it and return
1272/// success. Otherwise, emit the specified error and return failure.
1273bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1274 if (Lex.getKind() != T)
1275 return TokError(ErrMsg);
1276 Lex.Lex();
1277 return false;
1278}
1279
Chris Lattner3822f632009-01-02 08:05:26 +00001280/// ParseStringConstant
1281/// ::= StringConstant
1282bool LLParser::ParseStringConstant(std::string &Result) {
1283 if (Lex.getKind() != lltok::StringConstant)
1284 return TokError("expected string constant");
1285 Result = Lex.getStrVal();
1286 Lex.Lex();
1287 return false;
1288}
1289
1290/// ParseUInt32
1291/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001292bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001293 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1294 return TokError("expected integer");
1295 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1296 if (Val64 != unsigned(Val64))
1297 return TokError("expected 32-bit integer (too large)");
1298 Val = Val64;
1299 Lex.Lex();
1300 return false;
1301}
1302
Hal Finkelb0407ba2014-07-18 15:51:28 +00001303/// ParseUInt64
1304/// ::= uint64
1305bool LLParser::ParseUInt64(uint64_t &Val) {
1306 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1307 return TokError("expected integer");
1308 Val = Lex.getAPSIntVal().getLimitedValue();
1309 Lex.Lex();
1310 return false;
1311}
1312
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001313/// ParseTLSModel
1314/// := 'localdynamic'
1315/// := 'initialexec'
1316/// := 'localexec'
1317bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1318 switch (Lex.getKind()) {
1319 default:
1320 return TokError("expected localdynamic, initialexec or localexec");
1321 case lltok::kw_localdynamic:
1322 TLM = GlobalVariable::LocalDynamicTLSModel;
1323 break;
1324 case lltok::kw_initialexec:
1325 TLM = GlobalVariable::InitialExecTLSModel;
1326 break;
1327 case lltok::kw_localexec:
1328 TLM = GlobalVariable::LocalExecTLSModel;
1329 break;
1330 }
1331
1332 Lex.Lex();
1333 return false;
1334}
1335
1336/// ParseOptionalThreadLocal
1337/// := /*empty*/
1338/// := 'thread_local'
1339/// := 'thread_local' '(' tlsmodel ')'
1340bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1341 TLM = GlobalVariable::NotThreadLocal;
1342 if (!EatIfPresent(lltok::kw_thread_local))
1343 return false;
1344
1345 TLM = GlobalVariable::GeneralDynamicTLSModel;
1346 if (Lex.getKind() == lltok::lparen) {
1347 Lex.Lex();
1348 return ParseTLSModel(TLM) ||
1349 ParseToken(lltok::rparen, "expected ')' after thread local model");
1350 }
1351 return false;
1352}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001353
1354/// ParseOptionalAddrSpace
1355/// := /*empty*/
1356/// := 'addrspace' '(' uint32 ')'
1357bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1358 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001359 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001360 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001362 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001363 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001364}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001365
Artur Pilipenko17376c42015-08-03 14:31:49 +00001366/// ParseStringAttribute
1367/// := StringConstant
1368/// := StringConstant '=' StringConstant
1369bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1370 std::string Attr = Lex.getStrVal();
1371 Lex.Lex();
1372 std::string Val;
1373 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1374 return true;
1375 B.addAttribute(Attr, Val);
1376 return false;
1377}
1378
Bill Wendling34c2eb22012-12-04 23:40:58 +00001379/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1380bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1381 bool HaveError = false;
1382
1383 B.clear();
1384
Eugene Zelenko1804a772016-08-25 00:45:04 +00001385 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001386 lltok::Kind Token = Lex.getKind();
1387 switch (Token) {
1388 default: // End of attributes.
1389 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001390 case lltok::StringConstant: {
1391 if (ParseStringAttribute(B))
1392 return true;
1393 continue;
1394 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001395 case lltok::kw_align: {
1396 unsigned Alignment;
1397 if (ParseOptionalAlignment(Alignment))
1398 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001399 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001400 continue;
1401 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001402 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001403 case lltok::kw_dereferenceable: {
1404 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001405 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001406 return true;
1407 B.addDereferenceableAttr(Bytes);
1408 continue;
1409 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001410 case lltok::kw_dereferenceable_or_null: {
1411 uint64_t Bytes;
1412 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1413 return true;
1414 B.addDereferenceableOrNullAttr(Bytes);
1415 continue;
1416 }
Reid Klecknera534a382013-12-19 02:14:12 +00001417 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001418 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1419 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1420 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1421 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001422 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001423 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1424 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001425 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001426 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1427 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001428 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001429 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001430 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001431 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001432
Stephen Lin7577ed52013-04-20 13:16:13 +00001433 case lltok::kw_alignstack:
1434 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001435 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001436 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001437 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001438 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001439 case lltok::kw_minsize:
1440 case lltok::kw_naked:
1441 case lltok::kw_nobuiltin:
1442 case lltok::kw_noduplicate:
1443 case lltok::kw_noimplicitfloat:
1444 case lltok::kw_noinline:
1445 case lltok::kw_nonlazybind:
1446 case lltok::kw_noredzone:
1447 case lltok::kw_noreturn:
1448 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001449 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001450 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001451 case lltok::kw_returns_twice:
1452 case lltok::kw_sanitize_address:
1453 case lltok::kw_sanitize_memory:
1454 case lltok::kw_sanitize_thread:
1455 case lltok::kw_ssp:
1456 case lltok::kw_sspreq:
1457 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001458 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001459 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001460 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001461 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1462 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001463 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001464
Bill Wendling34c2eb22012-12-04 23:40:58 +00001465 Lex.Lex();
1466 }
1467}
1468
1469/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1470bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1471 bool HaveError = false;
1472
1473 B.clear();
1474
Eugene Zelenko1804a772016-08-25 00:45:04 +00001475 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001476 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001477 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001478 default: // End of attributes.
1479 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001480 case lltok::StringConstant: {
1481 if (ParseStringAttribute(B))
1482 return true;
1483 continue;
1484 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001485 case lltok::kw_dereferenceable: {
1486 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001487 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001488 return true;
1489 B.addDereferenceableAttr(Bytes);
1490 continue;
1491 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001492 case lltok::kw_dereferenceable_or_null: {
1493 uint64_t Bytes;
1494 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1495 return true;
1496 B.addDereferenceableOrNullAttr(Bytes);
1497 continue;
1498 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001499 case lltok::kw_align: {
1500 unsigned Alignment;
1501 if (ParseOptionalAlignment(Alignment))
1502 return true;
1503 B.addAlignmentAttr(Alignment);
1504 continue;
1505 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001506 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1507 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001508 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001509 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1510 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001511
Bill Wendling34c2eb22012-12-04 23:40:58 +00001512 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001513 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001514 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001515 case lltok::kw_nest:
1516 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001517 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001518 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001519 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001520 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001521 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001522 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001523
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001524 case lltok::kw_alignstack:
1525 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001526 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001527 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001528 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001529 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001530 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001531 case lltok::kw_minsize:
1532 case lltok::kw_naked:
1533 case lltok::kw_nobuiltin:
1534 case lltok::kw_noduplicate:
1535 case lltok::kw_noimplicitfloat:
1536 case lltok::kw_noinline:
1537 case lltok::kw_nonlazybind:
1538 case lltok::kw_noredzone:
1539 case lltok::kw_noreturn:
1540 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001541 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001542 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001543 case lltok::kw_returns_twice:
1544 case lltok::kw_sanitize_address:
1545 case lltok::kw_sanitize_memory:
1546 case lltok::kw_sanitize_thread:
1547 case lltok::kw_ssp:
1548 case lltok::kw_sspreq:
1549 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001550 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001551 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001552 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001553 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001554 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001555
1556 case lltok::kw_readnone:
1557 case lltok::kw_readonly:
1558 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001559 }
1560
Chris Lattnerac161bf2009-01-02 07:01:27 +00001561 Lex.Lex();
1562 }
1563}
1564
Rafael Espindolac6269912016-05-10 17:16:45 +00001565static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1566 HasLinkage = true;
1567 switch (Kind) {
1568 default:
1569 HasLinkage = false;
1570 return GlobalValue::ExternalLinkage;
1571 case lltok::kw_private:
1572 return GlobalValue::PrivateLinkage;
1573 case lltok::kw_internal:
1574 return GlobalValue::InternalLinkage;
1575 case lltok::kw_weak:
1576 return GlobalValue::WeakAnyLinkage;
1577 case lltok::kw_weak_odr:
1578 return GlobalValue::WeakODRLinkage;
1579 case lltok::kw_linkonce:
1580 return GlobalValue::LinkOnceAnyLinkage;
1581 case lltok::kw_linkonce_odr:
1582 return GlobalValue::LinkOnceODRLinkage;
1583 case lltok::kw_available_externally:
1584 return GlobalValue::AvailableExternallyLinkage;
1585 case lltok::kw_appending:
1586 return GlobalValue::AppendingLinkage;
1587 case lltok::kw_common:
1588 return GlobalValue::CommonLinkage;
1589 case lltok::kw_extern_weak:
1590 return GlobalValue::ExternalWeakLinkage;
1591 case lltok::kw_external:
1592 return GlobalValue::ExternalLinkage;
1593 }
1594}
1595
Chris Lattnerac161bf2009-01-02 07:01:27 +00001596/// ParseOptionalLinkage
1597/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001598/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001599/// ::= 'internal'
1600/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001601/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001602/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001603/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001604/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001605/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001607/// ::= 'extern_weak'
1608/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001609bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1610 unsigned &Visibility,
1611 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001612 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1613 if (HasLinkage)
1614 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001615 ParseOptionalVisibility(Visibility);
1616 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001617 return false;
1618}
1619
1620/// ParseOptionalVisibility
1621/// ::= /*empty*/
1622/// ::= 'default'
1623/// ::= 'hidden'
1624/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001625///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001626void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001627 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001628 default:
1629 Res = GlobalValue::DefaultVisibility;
1630 return;
1631 case lltok::kw_default:
1632 Res = GlobalValue::DefaultVisibility;
1633 break;
1634 case lltok::kw_hidden:
1635 Res = GlobalValue::HiddenVisibility;
1636 break;
1637 case lltok::kw_protected:
1638 Res = GlobalValue::ProtectedVisibility;
1639 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001640 }
1641 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001642}
1643
Nico Rieck7157bb72014-01-14 15:22:47 +00001644/// ParseOptionalDLLStorageClass
1645/// ::= /*empty*/
1646/// ::= 'dllimport'
1647/// ::= 'dllexport'
1648///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001649void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001650 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001651 default:
1652 Res = GlobalValue::DefaultStorageClass;
1653 return;
1654 case lltok::kw_dllimport:
1655 Res = GlobalValue::DLLImportStorageClass;
1656 break;
1657 case lltok::kw_dllexport:
1658 Res = GlobalValue::DLLExportStorageClass;
1659 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001660 }
1661 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001662}
1663
Chris Lattnerac161bf2009-01-02 07:01:27 +00001664/// ParseOptionalCallingConv
1665/// ::= /*empty*/
1666/// ::= 'ccc'
1667/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001668/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001669/// ::= 'coldcc'
1670/// ::= 'x86_stdcallcc'
1671/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001672/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001673/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001674/// ::= 'arm_apcscc'
1675/// ::= 'arm_aapcscc'
1676/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001677/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001678/// ::= 'avr_intrcc'
1679/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001680/// ::= 'ptx_kernel'
1681/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001682/// ::= 'spir_func'
1683/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001684/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001685/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001686/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001687/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001688/// ::= 'preserve_mostcc'
1689/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001690/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001691/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001692/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001693/// ::= 'hhvmcc'
1694/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001695/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001696/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001697/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001698/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001699/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001700/// ::= 'amdgpu_gs'
1701/// ::= 'amdgpu_ps'
1702/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001703/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001704/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001705///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001706bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001707 switch (Lex.getKind()) {
1708 default: CC = CallingConv::C; return false;
1709 case lltok::kw_ccc: CC = CallingConv::C; break;
1710 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1711 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1712 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1713 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001714 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001715 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001716 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001717 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1718 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1719 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001720 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001721 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1722 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001723 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1724 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001725 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1726 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001727 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001728 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001729 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001730 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001731 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001732 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1733 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001734 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001735 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001736 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001737 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1738 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001739 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001740 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001741 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001742 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001743 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001744 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1745 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1746 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001747 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001748 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001749 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001750 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001751 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001753
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754 Lex.Lex();
1755 return false;
1756}
1757
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001758/// ParseMetadataAttachment
1759/// ::= !dbg !42
1760bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1761 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1762
1763 std::string Name = Lex.getStrVal();
1764 Kind = M->getMDKindID(Name);
1765 Lex.Lex();
1766
1767 return ParseMDNode(MD);
1768}
1769
Chris Lattner5c427632009-12-30 05:31:19 +00001770/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001771/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001772bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001773 do {
1774 if (Lex.getKind() != lltok::MetadataVar)
1775 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001776
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001777 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001778 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001779 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001780 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001781
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001782 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001783 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001784 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001785
Chris Lattner596760d2009-12-29 21:25:40 +00001786 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001787 } while (EatIfPresent(lltok::comma));
1788 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001789}
1790
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001791/// ParseGlobalObjectMetadataAttachment
1792/// ::= !dbg !57
1793bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1794 unsigned MDK;
1795 MDNode *N;
1796 if (ParseMetadataAttachment(MDK, N))
1797 return true;
1798
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001799 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001800 return false;
1801}
1802
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001803/// ParseOptionalFunctionMetadata
1804/// ::= (!dbg !57)*
1805bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001806 while (Lex.getKind() == lltok::MetadataVar)
1807 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001808 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001809 return false;
1810}
1811
Chris Lattnerac161bf2009-01-02 07:01:27 +00001812/// ParseOptionalAlignment
1813/// ::= /* empty */
1814/// ::= 'align' 4
1815bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1816 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001817 if (!EatIfPresent(lltok::kw_align))
1818 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001819 LocTy AlignLoc = Lex.getLoc();
1820 if (ParseUInt32(Alignment)) return true;
1821 if (!isPowerOf2_32(Alignment))
1822 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001823 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001824 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001825 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001826}
1827
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001828/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001829/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001830/// ::= AttrKind '(' 4 ')'
1831///
1832/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1833bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1834 uint64_t &Bytes) {
1835 assert((AttrKind == lltok::kw_dereferenceable ||
1836 AttrKind == lltok::kw_dereferenceable_or_null) &&
1837 "contract!");
1838
Hal Finkelb0407ba2014-07-18 15:51:28 +00001839 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001840 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001841 return false;
1842 LocTy ParenLoc = Lex.getLoc();
1843 if (!EatIfPresent(lltok::lparen))
1844 return Error(ParenLoc, "expected '('");
1845 LocTy DerefLoc = Lex.getLoc();
1846 if (ParseUInt64(Bytes)) return true;
1847 ParenLoc = Lex.getLoc();
1848 if (!EatIfPresent(lltok::rparen))
1849 return Error(ParenLoc, "expected ')'");
1850 if (!Bytes)
1851 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1852 return false;
1853}
1854
Chris Lattnerb2f39502009-12-30 05:44:30 +00001855/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001856/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001857/// ::= ',' align 4
1858///
1859/// This returns with AteExtraComma set to true if it ate an excess comma at the
1860/// end.
1861bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1862 bool &AteExtraComma) {
1863 AteExtraComma = false;
1864 while (EatIfPresent(lltok::comma)) {
1865 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001866 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001867 AteExtraComma = true;
1868 return false;
1869 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001870
Chris Lattner95b0ff42010-04-23 00:50:50 +00001871 if (Lex.getKind() != lltok::kw_align)
1872 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001873
Chris Lattner95b0ff42010-04-23 00:50:50 +00001874 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001875 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001876
Devang Patelea8a4b92009-09-17 23:04:48 +00001877 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001878}
1879
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001880/// ParseOptionalCommaAddrSpace
1881/// ::=
1882/// ::= ',' addrspace(1)
1883///
1884/// This returns with AteExtraComma set to true if it ate an excess comma at the
1885/// end.
1886bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1887 LocTy &Loc,
1888 bool &AteExtraComma) {
1889 AteExtraComma = false;
1890 while (EatIfPresent(lltok::comma)) {
1891 // Metadata at the end is an early exit.
1892 if (Lex.getKind() == lltok::MetadataVar) {
1893 AteExtraComma = true;
1894 return false;
1895 }
1896
1897 Loc = Lex.getLoc();
1898 if (Lex.getKind() != lltok::kw_addrspace)
1899 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1900
1901 if (ParseOptionalAddrSpace(AddrSpace))
1902 return true;
1903 }
1904
1905 return false;
1906}
1907
George Burgess IV278199f2016-04-12 01:05:35 +00001908bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1909 Optional<unsigned> &HowManyArg) {
1910 Lex.Lex();
1911
1912 auto StartParen = Lex.getLoc();
1913 if (!EatIfPresent(lltok::lparen))
1914 return Error(StartParen, "expected '('");
1915
1916 if (ParseUInt32(BaseSizeArg))
1917 return true;
1918
1919 if (EatIfPresent(lltok::comma)) {
1920 auto HowManyAt = Lex.getLoc();
1921 unsigned HowMany;
1922 if (ParseUInt32(HowMany))
1923 return true;
1924 if (HowMany == BaseSizeArg)
1925 return Error(HowManyAt,
1926 "'allocsize' indices can't refer to the same parameter");
1927 HowManyArg = HowMany;
1928 } else
1929 HowManyArg = None;
1930
1931 auto EndParen = Lex.getLoc();
1932 if (!EatIfPresent(lltok::rparen))
1933 return Error(EndParen, "expected ')'");
1934 return false;
1935}
1936
Eli Friedmanfee02c62011-07-25 23:16:38 +00001937/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001938/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00001939/// else: ::=
1940///
1941/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001942bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00001943 AtomicOrdering &Ordering) {
1944 if (!isAtomic)
1945 return false;
1946
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001947 return ParseScope(SSID) || ParseOrdering(Ordering);
1948}
Tim Northovere94a5182014-03-11 10:48:52 +00001949
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001950/// ParseScope
1951/// ::= syncscope("singlethread" | "<target scope>")?
1952///
1953/// This sets synchronization scope ID to the ID of the parsed value.
1954bool LLParser::ParseScope(SyncScope::ID &SSID) {
1955 SSID = SyncScope::System;
1956 if (EatIfPresent(lltok::kw_syncscope)) {
1957 auto StartParenAt = Lex.getLoc();
1958 if (!EatIfPresent(lltok::lparen))
1959 return Error(StartParenAt, "Expected '(' in syncscope");
1960
1961 std::string SSN;
1962 auto SSNAt = Lex.getLoc();
1963 if (ParseStringConstant(SSN))
1964 return Error(SSNAt, "Expected synchronization scope name");
1965
1966 auto EndParenAt = Lex.getLoc();
1967 if (!EatIfPresent(lltok::rparen))
1968 return Error(EndParenAt, "Expected ')' in syncscope");
1969
1970 SSID = Context.getOrInsertSyncScopeID(SSN);
1971 }
1972
1973 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00001974}
1975
1976/// ParseOrdering
1977/// ::= AtomicOrdering
1978///
1979/// This sets Ordering to the parsed value.
1980bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001981 switch (Lex.getKind()) {
1982 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001983 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1984 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1985 // Not specified yet:
1986 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1987 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1988 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1989 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1990 case lltok::kw_seq_cst:
1991 Ordering = AtomicOrdering::SequentiallyConsistent;
1992 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001993 }
1994 Lex.Lex();
1995 return false;
1996}
1997
Charles Davisbe5557e2010-02-12 00:31:15 +00001998/// ParseOptionalStackAlignment
1999/// ::= /* empty */
2000/// ::= 'alignstack' '(' 4 ')'
2001bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2002 Alignment = 0;
2003 if (!EatIfPresent(lltok::kw_alignstack))
2004 return false;
2005 LocTy ParenLoc = Lex.getLoc();
2006 if (!EatIfPresent(lltok::lparen))
2007 return Error(ParenLoc, "expected '('");
2008 LocTy AlignLoc = Lex.getLoc();
2009 if (ParseUInt32(Alignment)) return true;
2010 ParenLoc = Lex.getLoc();
2011 if (!EatIfPresent(lltok::rparen))
2012 return Error(ParenLoc, "expected ')'");
2013 if (!isPowerOf2_32(Alignment))
2014 return Error(AlignLoc, "stack alignment is not a power of two");
2015 return false;
2016}
Devang Patelea8a4b92009-09-17 23:04:48 +00002017
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002018/// ParseIndexList - This parses the index list for an insert/extractvalue
2019/// instruction. This sets AteExtraComma in the case where we eat an extra
2020/// comma at the end of the line and find that it is followed by metadata.
2021/// Clients that don't allow metadata can call the version of this function that
2022/// only takes one argument.
2023///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002024/// ParseIndexList
2025/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002026///
2027bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2028 bool &AteExtraComma) {
2029 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002030
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031 if (Lex.getKind() != lltok::comma)
2032 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002033
Chris Lattner3822f632009-01-02 08:05:26 +00002034 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002035 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002036 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002037 AteExtraComma = true;
2038 return false;
2039 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002040 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002041 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 Indices.push_back(Idx);
2043 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002044
Chris Lattnerac161bf2009-01-02 07:01:27 +00002045 return false;
2046}
2047
2048//===----------------------------------------------------------------------===//
2049// Type Parsing.
2050//===----------------------------------------------------------------------===//
2051
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002053bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002054 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055 switch (Lex.getKind()) {
2056 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002057 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002060 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002061 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002063 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002064 // Type ::= StructType
2065 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 return true;
2067 break;
2068 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002070 Lex.Lex(); // eat the lsquare.
2071 if (ParseArrayVectorType(Result, false))
2072 return true;
2073 break;
2074 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002075 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002076 Lex.Lex();
2077 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002079 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081 } else if (ParseArrayVectorType(Result, true))
2082 return true;
2083 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002084 case lltok::LocalVar: {
2085 // Type ::= %foo
2086 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 // If the type hasn't been defined yet, create a forward definition and
2089 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002090 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002091 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002092 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002094 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 Lex.Lex();
2096 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002099 case lltok::LocalVarID: {
2100 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002101 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002102
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002103 // If the type hasn't been defined yet, create a forward definition and
2104 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002105 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002106 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002107 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002108 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002109 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002110 Lex.Lex();
2111 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002112 }
2113 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002114
2115 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002116 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 switch (Lex.getKind()) {
2118 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002119 default:
2120 if (!AllowVoid && Result->isVoidTy())
2121 return Error(TypeLoc, "void type only allowed for function results");
2122 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002124 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002126 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002128 if (Result->isVoidTy())
2129 return TokError("pointers to void are invalid - use i8* instead");
2130 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002131 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002132 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002133 Lex.Lex();
2134 break;
2135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002136 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002138 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002140 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002141 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002142 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002143 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 unsigned AddrSpace;
2145 if (ParseOptionalAddrSpace(AddrSpace) ||
2146 ParseToken(lltok::star, "expected '*' in address space"))
2147 return true;
2148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002149 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 break;
2151 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002152
Chris Lattnerac161bf2009-01-02 07:01:27 +00002153 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2154 case lltok::lparen:
2155 if (ParseFunctionType(Result))
2156 return true;
2157 break;
2158 }
2159 }
2160}
2161
2162/// ParseParameterList
2163/// ::= '(' ')'
2164/// ::= '(' Arg (',' Arg)* ')'
2165/// Arg
2166/// ::= Type OptionalAttributes Value OptionalAttributes
2167bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002168 PerFunctionState &PFS, bool IsMustTailCall,
2169 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 if (ParseToken(lltok::lparen, "expected '(' in call"))
2171 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002172
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 while (Lex.getKind() != lltok::rparen) {
2174 // If this isn't the first argument, we need a comma.
2175 if (!ArgList.empty() &&
2176 ParseToken(lltok::comma, "expected ',' in argument list"))
2177 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002178
Reid Kleckner83498642014-08-26 00:33:28 +00002179 // Parse an ellipsis if this is a musttail call in a variadic function.
2180 if (Lex.getKind() == lltok::dotdotdot) {
2181 const char *Msg = "unexpected ellipsis in argument list for ";
2182 if (!IsMustTailCall)
2183 return TokError(Twine(Msg) + "non-musttail call");
2184 if (!InVarArgsFunc)
2185 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2186 Lex.Lex(); // Lex the '...', it is purely for readability.
2187 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2188 }
2189
Chris Lattnerac161bf2009-01-02 07:01:27 +00002190 // Parse the argument.
2191 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002192 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002193 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002195 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002197
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002198 if (ArgTy->isMetadataTy()) {
2199 if (ParseMetadataAsValue(V, PFS))
2200 return true;
2201 } else {
2202 // Otherwise, handle normal operands.
2203 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2204 return true;
2205 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002206 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002207 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 }
2209
Reid Kleckner83498642014-08-26 00:33:28 +00002210 if (IsMustTailCall && InVarArgsFunc)
2211 return TokError("expected '...' at end of argument list for musttail call "
2212 "in varargs function");
2213
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 Lex.Lex(); // Lex the ')'.
2215 return false;
2216}
2217
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002218/// ParseOptionalOperandBundles
2219/// ::= /*empty*/
2220/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2221///
2222/// OperandBundle
2223/// ::= bundle-tag '(' ')'
2224/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2225///
2226/// bundle-tag ::= String Constant
2227bool LLParser::ParseOptionalOperandBundles(
2228 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2229 LocTy BeginLoc = Lex.getLoc();
2230 if (!EatIfPresent(lltok::lsquare))
2231 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002233 while (Lex.getKind() != lltok::rsquare) {
2234 // If this isn't the first operand bundle, we need a comma.
2235 if (!BundleList.empty() &&
2236 ParseToken(lltok::comma, "expected ',' in input list"))
2237 return true;
2238
2239 std::string Tag;
2240 if (ParseStringConstant(Tag))
2241 return true;
2242
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002243 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2244 return true;
2245
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002246 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002247 while (Lex.getKind() != lltok::rparen) {
2248 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002249 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002250 ParseToken(lltok::comma, "expected ',' in input list"))
2251 return true;
2252
2253 Type *Ty = nullptr;
2254 Value *Input = nullptr;
2255 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2256 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002257 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002258 }
2259
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002260 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2261
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002262 Lex.Lex(); // Lex the ')'.
2263 }
2264
2265 if (BundleList.empty())
2266 return Error(BeginLoc, "operand bundle set must not be empty");
2267
2268 Lex.Lex(); // Lex the ']'.
2269 return false;
2270}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271
Chris Lattner2ed06b42009-01-05 18:34:07 +00002272/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002273/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274/// ::= '(' ArgTypeListI ')'
2275/// ArgTypeListI
2276/// ::= /*empty*/
2277/// ::= '...'
2278/// ::= ArgTypeList ',' '...'
2279/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002280///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002281bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2282 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283 isVarArg = false;
2284 assert(Lex.getKind() == lltok::lparen);
2285 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002286
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287 if (Lex.getKind() == lltok::rparen) {
2288 // empty
2289 } else if (Lex.getKind() == lltok::dotdotdot) {
2290 isVarArg = true;
2291 Lex.Lex();
2292 } else {
2293 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002294 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002295 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002296 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002297
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002298 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002299 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002300
Chris Lattnerfdd87902009-10-05 05:54:46 +00002301 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002302 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002303
Chris Lattnerdef19492011-06-17 06:36:20 +00002304 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 Name = Lex.getStrVal();
2306 Lex.Lex();
2307 }
Chris Lattner3822f632009-01-02 08:05:26 +00002308
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002309 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002310 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002311
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002312 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002313 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002314 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
Chris Lattner3822f632009-01-02 08:05:26 +00002316 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002318 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002319 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 break;
2321 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323 // Otherwise must be an argument type.
2324 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002325 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002326
Chris Lattnerfdd87902009-10-05 05:54:46 +00002327 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002328 return Error(TypeLoc, "argument can not have void type");
2329
Chris Lattnerdef19492011-06-17 06:36:20 +00002330 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331 Name = Lex.getStrVal();
2332 Lex.Lex();
2333 } else {
2334 Name = "";
2335 }
Chris Lattner3822f632009-01-02 08:05:26 +00002336
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002337 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002338 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002339
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002340 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002341 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002342 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002343 }
2344 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattner3822f632009-01-02 08:05:26 +00002346 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002347}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349/// ParseFunctionType
2350/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002351bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 assert(Lex.getKind() == lltok::lparen);
2353
Chris Lattnerce473c72009-01-05 08:04:33 +00002354 if (!FunctionType::isValidReturnType(Result))
2355 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002356
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002359 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002360 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002361
Chris Lattnerac161bf2009-01-02 07:01:27 +00002362 // Reject names on the arguments lists.
2363 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2364 if (!ArgList[i].Name.empty())
2365 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002366 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002367 return Error(ArgList[i].Loc,
2368 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002369 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370
Jay Foadb804a2b2011-07-12 14:06:48 +00002371 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002373 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002374
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002375 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 return false;
2377}
2378
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002379/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2380/// other structs.
2381bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2382 SmallVector<Type*, 8> Elts;
2383 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 Result = StructType::get(Context, Elts, Packed);
2386 return false;
2387}
2388
2389/// ParseStructDefinition - Parse a struct in a 'type' definition.
2390bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2391 std::pair<Type*, LocTy> &Entry,
2392 Type *&ResultTy) {
2393 // If the type was already defined, diagnose the redefinition.
2394 if (Entry.first && !Entry.second.isValid())
2395 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002396
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002397 // If we have opaque, just return without filling in the definition for the
2398 // struct. This counts as a definition as far as the .ll file goes.
2399 if (EatIfPresent(lltok::kw_opaque)) {
2400 // This type is being defined, so clear the location to indicate this.
2401 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002403 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002404 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002405 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406 ResultTy = Entry.first;
2407 return false;
2408 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002410 // If the type starts with '<', then it is either a packed struct or a vector.
2411 bool isPacked = EatIfPresent(lltok::less);
2412
2413 // If we don't have a struct, then we have a random type alias, which we
2414 // accept for compatibility with old files. These types are not allowed to be
2415 // forward referenced and not allowed to be recursive.
2416 if (Lex.getKind() != lltok::lbrace) {
2417 if (Entry.first)
2418 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002419
Craig Topper2617dcc2014-04-15 06:32:26 +00002420 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002421 if (isPacked)
2422 return ParseArrayVectorType(ResultTy, true);
2423 return ParseType(ResultTy);
2424 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002425
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002426 // This type is being defined, so clear the location to indicate this.
2427 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002428
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002429 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002430 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002431 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002432
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002433 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002434
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002435 SmallVector<Type*, 8> Body;
2436 if (ParseStructBody(Body) ||
2437 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2438 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002439
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002440 STy->setBody(Body, isPacked);
2441 ResultTy = STy;
2442 return false;
2443}
2444
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002446/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002448/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002450/// ::= '<' '{' Type (',' Type)* '}' '>'
2451bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 assert(Lex.getKind() == lltok::lbrace);
2453 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002454
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002455 // Handle the empty struct.
2456 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458
Chris Lattnerf880ca22009-03-09 04:49:14 +00002459 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002460 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002461 if (ParseType(Ty)) return true;
2462 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002464 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002465 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002466
Chris Lattner3822f632009-01-02 08:05:26 +00002467 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002468 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002469 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002470
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002471 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002472 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002473
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002474 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002476
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002477 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478}
2479
2480/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2481/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002482/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483/// ::= '[' APSINTVAL 'x' Types ']'
2484/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002485bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002486 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2487 Lex.getAPSIntVal().getBitWidth() > 64)
2488 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002489
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 LocTy SizeLoc = Lex.getLoc();
2491 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002492 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002493
Chris Lattner3822f632009-01-02 08:05:26 +00002494 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2495 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496
2497 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002498 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002499 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002500
Chris Lattner3822f632009-01-02 08:05:26 +00002501 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2502 "expected end of sequential type"))
2503 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002506 if (Size == 0)
2507 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 if ((unsigned)Size != Size)
2509 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002510 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002511 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002512 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002513 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002514 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002516 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 }
2518 return false;
2519}
2520
2521//===----------------------------------------------------------------------===//
2522// Function Semantic Analysis.
2523//===----------------------------------------------------------------------===//
2524
Chris Lattner3432c622009-10-28 03:39:23 +00002525LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2526 int functionNumber)
2527 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528
2529 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002530 for (Argument &A : F.args())
2531 if (!A.hasName())
2532 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533}
2534
2535LLParser::PerFunctionState::~PerFunctionState() {
2536 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002537
David Blaikie9ebdc692015-09-21 21:07:50 +00002538 for (const auto &P : ForwardRefVals) {
2539 if (isa<BasicBlock>(P.second.first))
2540 continue;
2541 P.second.first->replaceAllUsesWith(
2542 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002543 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002544 }
2545
2546 for (const auto &P : ForwardRefValIDs) {
2547 if (isa<BasicBlock>(P.second.first))
2548 continue;
2549 P.second.first->replaceAllUsesWith(
2550 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002551 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002552 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553}
2554
Chris Lattner3432c622009-10-28 03:39:23 +00002555bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 if (!ForwardRefVals.empty())
2557 return P.Error(ForwardRefVals.begin()->second.second,
2558 "use of undefined value '%" + ForwardRefVals.begin()->first +
2559 "'");
2560 if (!ForwardRefValIDs.empty())
2561 return P.Error(ForwardRefValIDs.begin()->second.second,
2562 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002563 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 return false;
2565}
2566
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567/// GetVal - Get a value with the specified name or ID, creating a
2568/// forward reference record if needed. This can return null if the value
2569/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002570Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002571 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002573 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002574
Chris Lattnerac161bf2009-01-02 07:01:27 +00002575 // If this is a forward reference for the value, see if we already created a
2576 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002577 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002578 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 if (I != ForwardRefVals.end())
2580 Val = I->second.first;
2581 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002582
Chris Lattnerac161bf2009-01-02 07:01:27 +00002583 // If we have the value in the symbol table or fwd-ref table, return it.
2584 if (Val) {
2585 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002586 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 P.Error(Loc, "'%" + Name + "' is not a basic block");
2588 else
2589 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002590 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002591 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002593
Chris Lattnerac161bf2009-01-02 07:01:27 +00002594 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002595 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002596 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002597 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002598 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002599
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 // Otherwise, create a new forward reference for this value and remember it.
2601 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002602 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002603 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002604 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002605 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002606 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002607
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2609 return FwdVal;
2610}
2611
David Majnemer8a1c45d2015-12-12 05:38:55 +00002612Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002614 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002615
Chris Lattnerac161bf2009-01-02 07:01:27 +00002616 // If this is a forward reference for the value, see if we already created a
2617 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002618 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002619 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 if (I != ForwardRefValIDs.end())
2621 Val = I->second.first;
2622 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002623
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 // If we have the value in the symbol table or fwd-ref table, return it.
2625 if (Val) {
2626 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002627 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002628 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002629 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002630 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002631 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002632 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002635 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002636 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002637 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002638 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002639
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640 // Otherwise, create a new forward reference for this value and remember it.
2641 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002642 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002643 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002644 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002645 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002647
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2649 return FwdVal;
2650}
2651
2652/// SetInstName - After an instruction is parsed and inserted into its
2653/// basic block, this installs its name.
2654bool LLParser::PerFunctionState::SetInstName(int NameID,
2655 const std::string &NameStr,
2656 LocTy NameLoc, Instruction *Inst) {
2657 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002658 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 if (NameID != -1 || !NameStr.empty())
2660 return P.Error(NameLoc, "instructions returning void cannot have a name");
2661 return false;
2662 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663
Chris Lattnerac161bf2009-01-02 07:01:27 +00002664 // If this was a numbered instruction, verify that the instruction is the
2665 // expected value and resolve any forward references.
2666 if (NameStr.empty()) {
2667 // If neither a name nor an ID was specified, just use the next ID.
2668 if (NameID == -1)
2669 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 if (unsigned(NameID) != NumberedVals.size())
2672 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002673 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002674
David Blaikie9ebdc692015-09-21 21:07:50 +00002675 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002676 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002677 Value *Sentinel = FI->second.first;
2678 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002679 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002680 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002681
2682 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002683 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002684 ForwardRefValIDs.erase(FI);
2685 }
2686
2687 NumberedVals.push_back(Inst);
2688 return false;
2689 }
2690
2691 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002692 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002694 Value *Sentinel = FI->second.first;
2695 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002696 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002697 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002698
2699 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002700 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701 ForwardRefVals.erase(FI);
2702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002703
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 // Set the name on the instruction.
2705 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002706
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002707 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 NameStr + "'");
2710 return false;
2711}
2712
2713/// GetBB - Get a basic block with the specified name or ID, creating a
2714/// forward reference record if needed.
2715BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2716 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002717 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2718 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719}
2720
2721BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002722 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2723 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002724}
2725
2726/// DefineBB - Define the specified basic block, which is either named or
2727/// unnamed. If there is an error, this returns null otherwise it returns
2728/// the block being defined.
2729BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2730 LocTy Loc) {
2731 BasicBlock *BB;
2732 if (Name.empty())
2733 BB = GetBB(NumberedVals.size(), Loc);
2734 else
2735 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002736 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002737
Chris Lattnerac161bf2009-01-02 07:01:27 +00002738 // Move the block to the end of the function. Forward ref'd blocks are
2739 // inserted wherever they happen to be referenced.
2740 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 // Remove the block from forward ref sets.
2743 if (Name.empty()) {
2744 ForwardRefValIDs.erase(NumberedVals.size());
2745 NumberedVals.push_back(BB);
2746 } else {
2747 // BB forward references are already in the function symbol table.
2748 ForwardRefVals.erase(Name);
2749 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750
Chris Lattnerac161bf2009-01-02 07:01:27 +00002751 return BB;
2752}
2753
2754//===----------------------------------------------------------------------===//
2755// Constants.
2756//===----------------------------------------------------------------------===//
2757
2758/// ParseValID - Parse an abstract value that doesn't necessarily have a
2759/// type implied. For example, if we parse "4" we don't know what integer type
2760/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002761/// sanity. PFS is used to convert function-local operands of metadata (since
2762/// metadata operands are not just parsed here but also converted to values).
2763/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002764bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 ID.Loc = Lex.getLoc();
2766 switch (Lex.getKind()) {
2767 default: return TokError("expected value token");
2768 case lltok::GlobalID: // @42
2769 ID.UIntVal = Lex.getUIntVal();
2770 ID.Kind = ValID::t_GlobalID;
2771 break;
2772 case lltok::GlobalVar: // @foo
2773 ID.StrVal = Lex.getStrVal();
2774 ID.Kind = ValID::t_GlobalName;
2775 break;
2776 case lltok::LocalVarID: // %42
2777 ID.UIntVal = Lex.getUIntVal();
2778 ID.Kind = ValID::t_LocalID;
2779 break;
2780 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 ID.StrVal = Lex.getStrVal();
2782 ID.Kind = ValID::t_LocalName;
2783 break;
2784 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002785 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002786 ID.Kind = ValID::t_APSInt;
2787 break;
2788 case lltok::APFloat:
2789 ID.APFloatVal = Lex.getAPFloatVal();
2790 ID.Kind = ValID::t_APFloat;
2791 break;
2792 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002793 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794 ID.Kind = ValID::t_Constant;
2795 break;
2796 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002797 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002798 ID.Kind = ValID::t_Constant;
2799 break;
2800 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2801 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2802 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002803 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002804
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 case lltok::lbrace: {
2806 // ValID ::= '{' ConstVector '}'
2807 Lex.Lex();
2808 SmallVector<Constant*, 16> Elts;
2809 if (ParseGlobalValueVector(Elts) ||
2810 ParseToken(lltok::rbrace, "expected end of struct constant"))
2811 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812
David Blaikieadbda4b2015-08-03 20:08:41 +00002813 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002814 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002815 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2816 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002817 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002818 return false;
2819 }
2820 case lltok::less: {
2821 // ValID ::= '<' ConstVector '>' --> Vector.
2822 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2823 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002824 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002825
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 SmallVector<Constant*, 16> Elts;
2827 LocTy FirstEltLoc = Lex.getLoc();
2828 if (ParseGlobalValueVector(Elts) ||
2829 (isPackedStruct &&
2830 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2831 ParseToken(lltok::greater, "expected end of constant"))
2832 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002833
Chris Lattnerac161bf2009-01-02 07:01:27 +00002834 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002835 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2836 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2837 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002838 ID.UIntVal = Elts.size();
2839 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002840 return false;
2841 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002842
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 if (Elts.empty())
2844 return Error(ID.Loc, "constant vector must not be empty");
2845
Duncan Sands9dff9be2010-02-15 16:12:20 +00002846 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002847 !Elts[0]->getType()->isFloatingPointTy() &&
2848 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002850 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002851
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 // Verify that all the vector elements have the same type.
2853 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2854 if (Elts[i]->getType() != Elts[0]->getType())
2855 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002856 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002857 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002858
Chris Lattner69229312011-02-15 00:14:00 +00002859 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 ID.Kind = ValID::t_Constant;
2861 return false;
2862 }
2863 case lltok::lsquare: { // Array Constant
2864 Lex.Lex();
2865 SmallVector<Constant*, 16> Elts;
2866 LocTy FirstEltLoc = Lex.getLoc();
2867 if (ParseGlobalValueVector(Elts) ||
2868 ParseToken(lltok::rsquare, "expected end of array constant"))
2869 return true;
2870
2871 // Handle empty element.
2872 if (Elts.empty()) {
2873 // Use undef instead of an array because it's inconvenient to determine
2874 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002875 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 return false;
2877 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002880 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002881 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002882
Owen Anderson4056ca92009-07-29 22:17:13 +00002883 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002884
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002886 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887 if (Elts[i]->getType() != Elts[0]->getType())
2888 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002889 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002890 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002892
Jay Foad83be3612011-06-22 09:24:39 +00002893 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 ID.Kind = ValID::t_Constant;
2895 return false;
2896 }
2897 case lltok::kw_c: // c "foo"
2898 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002899 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2900 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002901 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2902 ID.Kind = ValID::t_Constant;
2903 return false;
2904
2905 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002906 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2907 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002908 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002909 Lex.Lex();
2910 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002911 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002912 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002913 ParseStringConstant(ID.StrVal) ||
2914 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002915 ParseToken(lltok::StringConstant, "expected constraint string"))
2916 return true;
2917 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002918 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002919 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002920 ID.Kind = ValID::t_InlineAsm;
2921 return false;
2922 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002923
Chris Lattner3432c622009-10-28 03:39:23 +00002924 case lltok::kw_blockaddress: {
2925 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2926 Lex.Lex();
2927
2928 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002929
Chris Lattner3432c622009-10-28 03:39:23 +00002930 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2931 ParseValID(Fn) ||
2932 ParseToken(lltok::comma, "expected comma in block address expression")||
2933 ParseValID(Label) ||
2934 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2935 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002936
Chris Lattner3432c622009-10-28 03:39:23 +00002937 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2938 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002939 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002940 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002941
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002942 // Try to find the function (but skip it if it's forward-referenced).
2943 GlobalValue *GV = nullptr;
2944 if (Fn.Kind == ValID::t_GlobalID) {
2945 if (Fn.UIntVal < NumberedVals.size())
2946 GV = NumberedVals[Fn.UIntVal];
2947 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2948 GV = M->getNamedValue(Fn.StrVal);
2949 }
2950 Function *F = nullptr;
2951 if (GV) {
2952 // Confirm that it's actually a function with a definition.
2953 if (!isa<Function>(GV))
2954 return Error(Fn.Loc, "expected function name in blockaddress");
2955 F = cast<Function>(GV);
2956 if (F->isDeclaration())
2957 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2958 }
2959
2960 if (!F) {
2961 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002962 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002963 ForwardRefBlockAddresses.insert(std::make_pair(
2964 std::move(Fn),
2965 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002966 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2967 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002968 if (!FwdRef)
2969 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2970 GlobalValue::InternalLinkage, nullptr, "");
2971 ID.ConstantVal = FwdRef;
2972 ID.Kind = ValID::t_Constant;
2973 return false;
2974 }
2975
2976 // We found the function; now find the basic block. Don't use PFS, since we
2977 // might be inside a constant expression.
2978 BasicBlock *BB;
2979 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2980 if (Label.Kind == ValID::t_LocalID)
2981 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2982 else
2983 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2984 if (!BB)
2985 return Error(Label.Loc, "referenced value is not a basic block");
2986 } else {
2987 if (Label.Kind == ValID::t_LocalID)
2988 return Error(Label.Loc, "cannot take address of numeric label after "
2989 "the function is defined");
2990 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002991 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002992 if (!BB)
2993 return Error(Label.Loc, "referenced value is not a basic block");
2994 }
2995
2996 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002997 ID.Kind = ValID::t_Constant;
2998 return false;
2999 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003000
Chris Lattnerac161bf2009-01-02 07:01:27 +00003001 case lltok::kw_trunc:
3002 case lltok::kw_zext:
3003 case lltok::kw_sext:
3004 case lltok::kw_fptrunc:
3005 case lltok::kw_fpext:
3006 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003007 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 case lltok::kw_uitofp:
3009 case lltok::kw_sitofp:
3010 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003011 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003012 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003013 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003014 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003015 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003016 Constant *SrcVal;
3017 Lex.Lex();
3018 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3019 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003020 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003021 ParseType(DestTy) ||
3022 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3023 return true;
3024 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3025 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003026 getTypeString(SrcVal->getType()) + "' to '" +
3027 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003028 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003029 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 ID.Kind = ValID::t_Constant;
3031 return false;
3032 }
3033 case lltok::kw_extractvalue: {
3034 Lex.Lex();
3035 Constant *Val;
3036 SmallVector<unsigned, 4> Indices;
3037 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3038 ParseGlobalTypeAndValue(Val) ||
3039 ParseIndexList(Indices) ||
3040 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3041 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003042
Chris Lattner392be582010-02-12 20:49:41 +00003043 if (!Val->getType()->isAggregateType())
3044 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003045 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003047 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003048 ID.Kind = ValID::t_Constant;
3049 return false;
3050 }
3051 case lltok::kw_insertvalue: {
3052 Lex.Lex();
3053 Constant *Val0, *Val1;
3054 SmallVector<unsigned, 4> Indices;
3055 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3056 ParseGlobalTypeAndValue(Val0) ||
3057 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3058 ParseGlobalTypeAndValue(Val1) ||
3059 ParseIndexList(Indices) ||
3060 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3061 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003062 if (!Val0->getType()->isAggregateType())
3063 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003064 Type *IndexedType =
3065 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3066 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003067 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003068 if (IndexedType != Val1->getType())
3069 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3070 getTypeString(Val1->getType()) +
3071 "' instead of '" + getTypeString(IndexedType) +
3072 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003073 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003074 ID.Kind = ValID::t_Constant;
3075 return false;
3076 }
3077 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003078 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 unsigned PredVal, Opc = Lex.getUIntVal();
3080 Constant *Val0, *Val1;
3081 Lex.Lex();
3082 if (ParseCmpPredicate(PredVal, Opc) ||
3083 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3084 ParseGlobalTypeAndValue(Val0) ||
3085 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3086 ParseGlobalTypeAndValue(Val1) ||
3087 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3088 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003089
Chris Lattnerac161bf2009-01-02 07:01:27 +00003090 if (Val0->getType() != Val1->getType())
3091 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003092
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003094
Chris Lattnerac161bf2009-01-02 07:01:27 +00003095 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003096 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003098 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003099 } else {
3100 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003101 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003102 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003103 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003104 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003105 }
3106 ID.Kind = ValID::t_Constant;
3107 return false;
3108 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003109
Chris Lattnerac161bf2009-01-02 07:01:27 +00003110 // Binary Operators.
3111 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003112 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003113 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003114 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003115 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003116 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003117 case lltok::kw_udiv:
3118 case lltok::kw_sdiv:
3119 case lltok::kw_fdiv:
3120 case lltok::kw_urem:
3121 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003122 case lltok::kw_frem:
3123 case lltok::kw_shl:
3124 case lltok::kw_lshr:
3125 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003126 bool NUW = false;
3127 bool NSW = false;
3128 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129 unsigned Opc = Lex.getUIntVal();
3130 Constant *Val0, *Val1;
3131 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003132 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003133 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3134 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003135 if (EatIfPresent(lltok::kw_nuw))
3136 NUW = true;
3137 if (EatIfPresent(lltok::kw_nsw)) {
3138 NSW = true;
3139 if (EatIfPresent(lltok::kw_nuw))
3140 NUW = true;
3141 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003142 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3143 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003144 if (EatIfPresent(lltok::kw_exact))
3145 Exact = true;
3146 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3148 ParseGlobalTypeAndValue(Val0) ||
3149 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3150 ParseGlobalTypeAndValue(Val1) ||
3151 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3152 return true;
3153 if (Val0->getType() != Val1->getType())
3154 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003155 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003156 if (NUW)
3157 return Error(ModifierLoc, "nuw only applies to integer operations");
3158 if (NSW)
3159 return Error(ModifierLoc, "nsw only applies to integer operations");
3160 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003161 // Check that the type is valid for the operator.
3162 switch (Opc) {
3163 case Instruction::Add:
3164 case Instruction::Sub:
3165 case Instruction::Mul:
3166 case Instruction::UDiv:
3167 case Instruction::SDiv:
3168 case Instruction::URem:
3169 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003170 case Instruction::Shl:
3171 case Instruction::AShr:
3172 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003173 if (!Val0->getType()->isIntOrIntVectorTy())
3174 return Error(ID.Loc, "constexpr requires integer operands");
3175 break;
3176 case Instruction::FAdd:
3177 case Instruction::FSub:
3178 case Instruction::FMul:
3179 case Instruction::FDiv:
3180 case Instruction::FRem:
3181 if (!Val0->getType()->isFPOrFPVectorTy())
3182 return Error(ID.Loc, "constexpr requires fp operands");
3183 break;
3184 default: llvm_unreachable("Unknown binary operator!");
3185 }
Dan Gohman1b849082009-09-07 23:54:19 +00003186 unsigned Flags = 0;
3187 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3188 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003189 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003190 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003191 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003192 ID.Kind = ValID::t_Constant;
3193 return false;
3194 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003195
Chris Lattnerac161bf2009-01-02 07:01:27 +00003196 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003197 case lltok::kw_and:
3198 case lltok::kw_or:
3199 case lltok::kw_xor: {
3200 unsigned Opc = Lex.getUIntVal();
3201 Constant *Val0, *Val1;
3202 Lex.Lex();
3203 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3204 ParseGlobalTypeAndValue(Val0) ||
3205 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3206 ParseGlobalTypeAndValue(Val1) ||
3207 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3208 return true;
3209 if (Val0->getType() != Val1->getType())
3210 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003211 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003212 return Error(ID.Loc,
3213 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003214 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003215 ID.Kind = ValID::t_Constant;
3216 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003217 }
3218
Chris Lattnerac161bf2009-01-02 07:01:27 +00003219 case lltok::kw_getelementptr:
3220 case lltok::kw_shufflevector:
3221 case lltok::kw_insertelement:
3222 case lltok::kw_extractelement:
3223 case lltok::kw_select: {
3224 unsigned Opc = Lex.getUIntVal();
3225 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003226 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003227 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003228 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003229
Dan Gohman1639c392009-07-27 21:53:46 +00003230 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003231 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003232
3233 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3234 return true;
3235
3236 LocTy ExplicitTypeLoc = Lex.getLoc();
3237 if (Opc == Instruction::GetElementPtr) {
3238 if (ParseType(Ty) ||
3239 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3240 return true;
3241 }
3242
Peter Collingbourned93620b2016-11-10 22:34:55 +00003243 Optional<unsigned> InRangeOp;
3244 if (ParseGlobalValueVector(
3245 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003246 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3247 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003248
Chris Lattnerac161bf2009-01-02 07:01:27 +00003249 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003250 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003251 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003252 return Error(ID.Loc, "base of getelementptr must be a pointer");
3253
3254 Type *BaseType = Elts[0]->getType();
3255 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003256 if (Ty != BasePointerType->getElementType())
3257 return Error(
3258 ExplicitTypeLoc,
3259 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003260
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003261 unsigned GEPWidth =
3262 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3263
Jay Foaded8db7d2011-07-21 14:31:17 +00003264 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003265 for (Constant *Val : Indices) {
3266 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003267 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003268 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003269 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003270 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003271 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003272 return Error(
3273 ID.Loc,
3274 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003275 // GEPWidth may have been unknown because the base is a scalar,
3276 // but it is known now.
3277 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003278 }
3279 }
3280
Craig Toppere3dcce92015-08-01 22:20:21 +00003281 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003282 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003283 return Error(ID.Loc, "base element of getelementptr must be sized");
3284
David Blaikie4a2e73b2015-04-02 18:55:32 +00003285 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003286 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003287
3288 if (InRangeOp) {
3289 if (*InRangeOp == 0)
3290 return Error(ID.Loc,
3291 "inrange keyword may not appear on pointer operand");
3292 --*InRangeOp;
3293 }
3294
3295 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3296 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003297 } else if (Opc == Instruction::Select) {
3298 if (Elts.size() != 3)
3299 return Error(ID.Loc, "expected three operands to select");
3300 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3301 Elts[2]))
3302 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003303 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003304 } else if (Opc == Instruction::ShuffleVector) {
3305 if (Elts.size() != 3)
3306 return Error(ID.Loc, "expected three operands to shufflevector");
3307 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3308 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003309 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003310 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003311 } else if (Opc == Instruction::ExtractElement) {
3312 if (Elts.size() != 2)
3313 return Error(ID.Loc, "expected two operands to extractelement");
3314 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3315 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003316 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003317 } else {
3318 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3319 if (Elts.size() != 3)
3320 return Error(ID.Loc, "expected three operands to insertelement");
3321 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3322 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003323 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003324 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003325 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003326
Chris Lattnerac161bf2009-01-02 07:01:27 +00003327 ID.Kind = ValID::t_Constant;
3328 return false;
3329 }
3330 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003331
Chris Lattnerac161bf2009-01-02 07:01:27 +00003332 Lex.Lex();
3333 return false;
3334}
3335
3336/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003337bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003338 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003339 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003340 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003341 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003342 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003343 if (V && !(C = dyn_cast<Constant>(V)))
3344 return Error(ID.Loc, "global values must be constants");
3345 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003346}
3347
Victor Hernandez9d75c962010-01-11 22:31:58 +00003348bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003349 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003350 return ParseType(Ty) ||
3351 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003352}
3353
Rafael Espindola83a362c2015-01-06 22:55:16 +00003354bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003355 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003356
3357 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003358 if (!EatIfPresent(lltok::kw_comdat))
3359 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003360
3361 if (EatIfPresent(lltok::lparen)) {
3362 if (Lex.getKind() != lltok::ComdatVar)
3363 return TokError("expected comdat variable");
3364 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3365 Lex.Lex();
3366 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3367 return true;
3368 } else {
3369 if (GlobalName.empty())
3370 return TokError("comdat cannot be unnamed");
3371 C = getComdat(GlobalName, KwLoc);
3372 }
3373
David Majnemerdad0a642014-06-27 18:19:56 +00003374 return false;
3375}
3376
Victor Hernandez9d75c962010-01-11 22:31:58 +00003377/// ParseGlobalValueVector
3378/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003379/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3380bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3381 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003382 // Empty list.
3383 if (Lex.getKind() == lltok::rbrace ||
3384 Lex.getKind() == lltok::rsquare ||
3385 Lex.getKind() == lltok::greater ||
3386 Lex.getKind() == lltok::rparen)
3387 return false;
3388
Peter Collingbourned93620b2016-11-10 22:34:55 +00003389 do {
3390 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3391 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003392
Peter Collingbourned93620b2016-11-10 22:34:55 +00003393 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003394 if (ParseGlobalTypeAndValue(C)) return true;
3395 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003396 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003397
3398 return false;
3399}
3400
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003401bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003402 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003403 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003404 return true;
3405
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003406 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003407 return false;
3408}
3409
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003410/// MDNode:
3411/// ::= !{ ... }
3412/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003413/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003414bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003415 if (Lex.getKind() == lltok::MetadataVar)
3416 return ParseSpecializedMDNode(N);
3417
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003418 return ParseToken(lltok::exclaim, "expected '!' here") ||
3419 ParseMDNodeTail(N);
3420}
3421
3422bool LLParser::ParseMDNodeTail(MDNode *&N) {
3423 // !{ ... }
3424 if (Lex.getKind() == lltok::lbrace)
3425 return ParseMDTuple(N);
3426
3427 // !42
3428 return ParseMDNodeID(N);
3429}
3430
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003431namespace {
3432
3433/// Structure to represent an optional metadata field.
3434template <class FieldTy> struct MDFieldImpl {
3435 typedef MDFieldImpl ImplTy;
3436 FieldTy Val;
3437 bool Seen;
3438
3439 void assign(FieldTy Val) {
3440 Seen = true;
3441 this->Val = std::move(Val);
3442 }
3443
3444 explicit MDFieldImpl(FieldTy Default)
3445 : Val(std::move(Default)), Seen(false) {}
3446};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003447
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003448struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3449 uint64_t Max;
3450
3451 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3452 : ImplTy(Default), Max(Max) {}
3453};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003454
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003455struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003456 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003457};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003458
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003459struct ColumnField : public MDUnsignedField {
3460 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3461};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003462
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003463struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003464 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003465 DwarfTagField(dwarf::Tag DefaultTag)
3466 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003467};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003468
Amjad Abouda9bcf162015-12-10 12:56:35 +00003469struct DwarfMacinfoTypeField : public MDUnsignedField {
3470 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3471 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3472 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3473};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003474
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003475struct DwarfAttEncodingField : public MDUnsignedField {
3476 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3477};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003478
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003479struct DwarfVirtualityField : public MDUnsignedField {
3480 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3481};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003482
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003483struct DwarfLangField : public MDUnsignedField {
3484 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3485};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003486
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003487struct DwarfCCField : public MDUnsignedField {
3488 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3489};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003490
Adrian Prantlb939a252016-03-31 23:56:58 +00003491struct EmissionKindField : public MDUnsignedField {
3492 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3493};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003494
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003495struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3496 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003497};
3498
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003499struct MDSignedField : public MDFieldImpl<int64_t> {
3500 int64_t Min;
3501 int64_t Max;
3502
3503 MDSignedField(int64_t Default = 0)
3504 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3505 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3506 : ImplTy(Default), Min(Min), Max(Max) {}
3507};
3508
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003509struct MDBoolField : public MDFieldImpl<bool> {
3510 MDBoolField(bool Default = false) : ImplTy(Default) {}
3511};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003512
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003513struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003514 bool AllowNull;
3515
3516 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003517};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003518
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003519struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3520 MDConstant() : ImplTy(nullptr) {}
3521};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003522
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003523struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003524 bool AllowEmpty;
3525 MDStringField(bool AllowEmpty = true)
3526 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003527};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003528
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003529struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3530 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3531};
3532
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003533struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3534 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3535 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3536};
3537
Eugene Zelenko1804a772016-08-25 00:45:04 +00003538} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003539
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003540namespace llvm {
3541
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003542template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003543bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003544 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003545 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3546 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003547
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003548 auto &U = Lex.getAPSIntVal();
3549 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003550 return TokError("value for '" + Name + "' too large, limit is " +
3551 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003552 Result.assign(U.getZExtValue());
3553 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003554 Lex.Lex();
3555 return false;
3556}
3557
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003558template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003559bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3560 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3561}
3562template <>
3563bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3564 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3565}
3566
3567template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003568bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3569 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003570 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003571
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003572 if (Lex.getKind() != lltok::DwarfTag)
3573 return TokError("expected DWARF tag");
3574
3575 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3576 if (Tag == dwarf::DW_TAG_invalid)
3577 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003578 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003579
3580 Result.assign(Tag);
3581 Lex.Lex();
3582 return false;
3583}
3584
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003585template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003586bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003587 DwarfMacinfoTypeField &Result) {
3588 if (Lex.getKind() == lltok::APSInt)
3589 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3590
3591 if (Lex.getKind() != lltok::DwarfMacinfo)
3592 return TokError("expected DWARF macinfo type");
3593
3594 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3595 if (Macinfo == dwarf::DW_MACINFO_invalid)
3596 return TokError(
3597 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3598 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3599
3600 Result.assign(Macinfo);
3601 Lex.Lex();
3602 return false;
3603}
3604
3605template <>
3606bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003607 DwarfVirtualityField &Result) {
3608 if (Lex.getKind() == lltok::APSInt)
3609 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3610
3611 if (Lex.getKind() != lltok::DwarfVirtuality)
3612 return TokError("expected DWARF virtuality code");
3613
3614 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003615 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003616 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3617 Lex.getStrVal() + "'");
3618 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3619 Result.assign(Virtuality);
3620 Lex.Lex();
3621 return false;
3622}
3623
3624template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003625bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3626 if (Lex.getKind() == lltok::APSInt)
3627 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3628
3629 if (Lex.getKind() != lltok::DwarfLang)
3630 return TokError("expected DWARF language");
3631
3632 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3633 if (!Lang)
3634 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3635 "'");
3636 assert(Lang <= Result.Max && "Expected valid DWARF language");
3637 Result.assign(Lang);
3638 Lex.Lex();
3639 return false;
3640}
3641
3642template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003643bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3644 if (Lex.getKind() == lltok::APSInt)
3645 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3646
3647 if (Lex.getKind() != lltok::DwarfCC)
3648 return TokError("expected DWARF calling convention");
3649
3650 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3651 if (!CC)
3652 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3653 "'");
3654 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3655 Result.assign(CC);
3656 Lex.Lex();
3657 return false;
3658}
3659
3660template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003661bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3662 if (Lex.getKind() == lltok::APSInt)
3663 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3664
3665 if (Lex.getKind() != lltok::EmissionKind)
3666 return TokError("expected emission kind");
3667
3668 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3669 if (!Kind)
3670 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3671 "'");
3672 assert(*Kind <= Result.Max && "Expected valid emission kind");
3673 Result.assign(*Kind);
3674 Lex.Lex();
3675 return false;
3676}
3677
3678template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003679bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003680 DwarfAttEncodingField &Result) {
3681 if (Lex.getKind() == lltok::APSInt)
3682 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3683
3684 if (Lex.getKind() != lltok::DwarfAttEncoding)
3685 return TokError("expected DWARF type attribute encoding");
3686
3687 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3688 if (!Encoding)
3689 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3690 Lex.getStrVal() + "'");
3691 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3692 Result.assign(Encoding);
3693 Lex.Lex();
3694 return false;
3695}
3696
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003697/// DIFlagField
3698/// ::= uint32
3699/// ::= DIFlagVector
3700/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3701template <>
3702bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003703
3704 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003705 auto parseFlag = [&](DINode::DIFlags &Val) {
3706 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3707 uint32_t TempVal = static_cast<uint32_t>(Val);
3708 bool Res = ParseUInt32(TempVal);
3709 Val = static_cast<DINode::DIFlags>(TempVal);
3710 return Res;
3711 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003712
3713 if (Lex.getKind() != lltok::DIFlag)
3714 return TokError("expected debug info flag");
3715
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003716 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003717 if (!Val)
3718 return TokError(Twine("invalid debug info flag flag '") +
3719 Lex.getStrVal() + "'");
3720 Lex.Lex();
3721 return false;
3722 };
3723
3724 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003725 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003726 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003727 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003728 if (parseFlag(Val))
3729 return true;
3730 Combined |= Val;
3731 } while (EatIfPresent(lltok::bar));
3732
3733 Result.assign(Combined);
3734 return false;
3735}
3736
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003737template <>
3738bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003739 MDSignedField &Result) {
3740 if (Lex.getKind() != lltok::APSInt)
3741 return TokError("expected signed integer");
3742
3743 auto &S = Lex.getAPSIntVal();
3744 if (S < Result.Min)
3745 return TokError("value for '" + Name + "' too small, limit is " +
3746 Twine(Result.Min));
3747 if (S > Result.Max)
3748 return TokError("value for '" + Name + "' too large, limit is " +
3749 Twine(Result.Max));
3750 Result.assign(S.getExtValue());
3751 assert(Result.Val >= Result.Min && "Expected value in range");
3752 assert(Result.Val <= Result.Max && "Expected value in range");
3753 Lex.Lex();
3754 return false;
3755}
3756
3757template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003758bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3759 switch (Lex.getKind()) {
3760 default:
3761 return TokError("expected 'true' or 'false'");
3762 case lltok::kw_true:
3763 Result.assign(true);
3764 break;
3765 case lltok::kw_false:
3766 Result.assign(false);
3767 break;
3768 }
3769 Lex.Lex();
3770 return false;
3771}
3772
3773template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003774bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003775 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003776 if (!Result.AllowNull)
3777 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003778 Lex.Lex();
3779 Result.assign(nullptr);
3780 return false;
3781 }
3782
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003783 Metadata *MD;
3784 if (ParseMetadata(MD, nullptr))
3785 return true;
3786
3787 Result.assign(MD);
3788 return false;
3789}
3790
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003791template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003792bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003793 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003794 std::string S;
3795 if (ParseStringConstant(S))
3796 return true;
3797
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003798 if (!Result.AllowEmpty && S.empty())
3799 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3800
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003801 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003802 return false;
3803}
3804
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003805template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003806bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3807 SmallVector<Metadata *, 4> MDs;
3808 if (ParseMDNodeVector(MDs))
3809 return true;
3810
3811 Result.assign(std::move(MDs));
3812 return false;
3813}
3814
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003815template <>
3816bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3817 ChecksumKindField &Result) {
3818 if (Lex.getKind() != lltok::ChecksumKind)
3819 return TokError(
3820 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3821
3822 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3823
3824 Result.assign(CSKind);
3825 Lex.Lex();
3826 return false;
3827}
3828
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003829} // end namespace llvm
3830
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003831template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003832bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003833 do {
3834 if (Lex.getKind() != lltok::LabelStr)
3835 return TokError("expected field label here");
3836
3837 if (parseField())
3838 return true;
3839 } while (EatIfPresent(lltok::comma));
3840
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003841 return false;
3842}
3843
3844template <class ParserTy>
3845bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3846 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3847 Lex.Lex();
3848
3849 if (ParseToken(lltok::lparen, "expected '(' here"))
3850 return true;
3851 if (Lex.getKind() != lltok::rparen)
3852 if (ParseMDFieldsImplBody(parseField))
3853 return true;
3854
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003855 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003856 return ParseToken(lltok::rparen, "expected ')' here");
3857}
3858
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003859template <class FieldTy>
3860bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3861 if (Result.Seen)
3862 return TokError("field '" + Name + "' cannot be specified more than once");
3863
3864 LocTy Loc = Lex.getLoc();
3865 Lex.Lex();
3866 return ParseMDField(Loc, Name, Result);
3867}
3868
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003869bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3870 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003871
3872#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003873 if (Lex.getStrVal() == #CLASS) \
3874 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003875#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003876
3877 return TokError("expected metadata type");
3878}
3879
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003880#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3881#define NOP_FIELD(NAME, TYPE, INIT)
3882#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3883 if (!NAME.Seen) \
3884 return Error(ClosingLoc, "missing required field '" #NAME "'");
3885#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003886 if (Lex.getStrVal() == #NAME) \
3887 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003888#define PARSE_MD_FIELDS() \
3889 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3890 do { \
3891 LocTy ClosingLoc; \
3892 if (ParseMDFieldsImpl([&]() -> bool { \
3893 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3894 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3895 }, ClosingLoc)) \
3896 return true; \
3897 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3898 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003899#define GET_OR_DISTINCT(CLASS, ARGS) \
3900 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003901
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003902/// ParseDILocationFields:
3903/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3904bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003905#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003906 OPTIONAL(line, LineField, ); \
3907 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003908 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003909 OPTIONAL(inlinedAt, MDField, );
3910 PARSE_MD_FIELDS();
3911#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003912
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003913 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003914 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003915 return false;
3916}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003917
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003918/// ParseGenericDINode:
3919/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3920bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003921#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003922 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003923 OPTIONAL(header, MDStringField, ); \
3924 OPTIONAL(operands, MDFieldList, );
3925 PARSE_MD_FIELDS();
3926#undef VISIT_MD_FIELDS
3927
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003928 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003929 (Context, tag.Val, header.Val, operands.Val));
3930 return false;
3931}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003932
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003933/// ParseDISubrange:
3934/// ::= !DISubrange(count: 30, lowerBound: 2)
3935bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003937 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003938 OPTIONAL(lowerBound, MDSignedField, );
3939 PARSE_MD_FIELDS();
3940#undef VISIT_MD_FIELDS
3941
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003942 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003943 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003944}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003945
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003946/// ParseDIEnumerator:
3947/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3948bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003949#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003950 REQUIRED(name, MDStringField, ); \
3951 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003952 PARSE_MD_FIELDS();
3953#undef VISIT_MD_FIELDS
3954
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003955 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003956 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003957}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003958
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003959/// ParseDIBasicType:
3960/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3961bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003962#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003963 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003964 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003965 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003966 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003967 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003968 PARSE_MD_FIELDS();
3969#undef VISIT_MD_FIELDS
3970
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003971 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003972 align.Val, encoding.Val));
3973 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003974}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003975
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003976/// ParseDIDerivedType:
3977/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003978/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003979/// align: 32, offset: 0, flags: 0, extraData: !3,
3980/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003981bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003982#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3983 REQUIRED(tag, DwarfTagField, ); \
3984 OPTIONAL(name, MDStringField, ); \
3985 OPTIONAL(file, MDField, ); \
3986 OPTIONAL(line, LineField, ); \
3987 OPTIONAL(scope, MDField, ); \
3988 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003989 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003990 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003991 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003992 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003993 OPTIONAL(extraData, MDField, ); \
3994 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003995 PARSE_MD_FIELDS();
3996#undef VISIT_MD_FIELDS
3997
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003998 Optional<unsigned> DWARFAddressSpace;
3999 if (dwarfAddressSpace.Val != UINT32_MAX)
4000 DWARFAddressSpace = dwarfAddressSpace.Val;
4001
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004002 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004003 (Context, tag.Val, name.Val, file.Val, line.Val,
4004 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004005 offset.Val, DWARFAddressSpace, flags.Val,
4006 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004007 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004008}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004009
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004010bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004011#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4012 REQUIRED(tag, DwarfTagField, ); \
4013 OPTIONAL(name, MDStringField, ); \
4014 OPTIONAL(file, MDField, ); \
4015 OPTIONAL(line, LineField, ); \
4016 OPTIONAL(scope, MDField, ); \
4017 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004018 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004019 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004020 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004021 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004022 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004023 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004024 OPTIONAL(vtableHolder, MDField, ); \
4025 OPTIONAL(templateParams, MDField, ); \
4026 OPTIONAL(identifier, MDStringField, );
4027 PARSE_MD_FIELDS();
4028#undef VISIT_MD_FIELDS
4029
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004030 // If this has an identifier try to build an ODR type.
4031 if (identifier.Val)
4032 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004033 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4034 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4035 elements.Val, runtimeLang.Val, vtableHolder.Val,
4036 templateParams.Val)) {
4037 Result = CT;
4038 return false;
4039 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004040
4041 // Create a new node, and save it in the context if it belongs in the type
4042 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004043 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004044 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004045 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4046 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4047 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4048 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004049}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004050
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004051bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004052#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004053 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004054 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004055 REQUIRED(types, MDField, );
4056 PARSE_MD_FIELDS();
4057#undef VISIT_MD_FIELDS
4058
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004059 Result = GET_OR_DISTINCT(DISubroutineType,
4060 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004061 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004062}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004063
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004064/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004065/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4066/// checksumkind: CSK_MD5,
4067/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004068bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004069#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4070 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004071 REQUIRED(directory, MDStringField, ); \
4072 OPTIONAL(checksumkind, ChecksumKindField, ); \
4073 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004074 PARSE_MD_FIELDS();
4075#undef VISIT_MD_FIELDS
4076
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004077 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4078 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004079 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004080}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004081
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004082/// ParseDICompileUnit:
4083/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004084/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004085/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004086/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004087/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004088bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004089 if (!IsDistinct)
4090 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4091
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004092#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4093 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004094 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004095 OPTIONAL(producer, MDStringField, ); \
4096 OPTIONAL(isOptimized, MDBoolField, ); \
4097 OPTIONAL(flags, MDStringField, ); \
4098 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4099 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004100 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004101 OPTIONAL(enums, MDField, ); \
4102 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004103 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004104 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004105 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004106 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004107 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004108 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4109 OPTIONAL(gnuPubnames, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004110 PARSE_MD_FIELDS();
4111#undef VISIT_MD_FIELDS
4112
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004113 Result = DICompileUnit::getDistinct(
4114 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4115 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004116 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004117 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004118 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004119}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004120
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004121/// ParseDISubprogram:
4122/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004123/// file: !1, line: 7, type: !2, isLocal: false,
4124/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004125/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004126/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004127/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004128/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004129bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004130 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004131#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4132 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004133 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004134 OPTIONAL(linkageName, MDStringField, ); \
4135 OPTIONAL(file, MDField, ); \
4136 OPTIONAL(line, LineField, ); \
4137 OPTIONAL(type, MDField, ); \
4138 OPTIONAL(isLocal, MDBoolField, ); \
4139 OPTIONAL(isDefinition, MDBoolField, (true)); \
4140 OPTIONAL(scopeLine, LineField, ); \
4141 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004142 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004143 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004144 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004145 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004146 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004147 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004148 OPTIONAL(templateParams, MDField, ); \
4149 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004150 OPTIONAL(variables, MDField, ); \
4151 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004152 PARSE_MD_FIELDS();
4153#undef VISIT_MD_FIELDS
4154
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004155 if (isDefinition.Val && !IsDistinct)
4156 return Lex.Error(
4157 Loc,
4158 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4159
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004160 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004161 DISubprogram,
4162 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4163 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4164 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4165 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4166 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004167 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004168}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004169
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004170/// ParseDILexicalBlock:
4171/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4172bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004173#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004174 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004175 OPTIONAL(file, MDField, ); \
4176 OPTIONAL(line, LineField, ); \
4177 OPTIONAL(column, ColumnField, );
4178 PARSE_MD_FIELDS();
4179#undef VISIT_MD_FIELDS
4180
4181 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004182 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004183 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004184}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004185
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004186/// ParseDILexicalBlockFile:
4187/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4188bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004189#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004190 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004191 OPTIONAL(file, MDField, ); \
4192 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4193 PARSE_MD_FIELDS();
4194#undef VISIT_MD_FIELDS
4195
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004196 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004197 (Context, scope.Val, file.Val, discriminator.Val));
4198 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004199}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004200
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004201/// ParseDINamespace:
4202/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4203bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004204#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4205 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004206 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004207 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004208 PARSE_MD_FIELDS();
4209#undef VISIT_MD_FIELDS
4210
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004211 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004212 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004213 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004214}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004215
Amjad Abouda9bcf162015-12-10 12:56:35 +00004216/// ParseDIMacro:
4217/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4218bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4219#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4220 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004221 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004222 REQUIRED(name, MDStringField, ); \
4223 OPTIONAL(value, MDStringField, );
4224 PARSE_MD_FIELDS();
4225#undef VISIT_MD_FIELDS
4226
4227 Result = GET_OR_DISTINCT(DIMacro,
4228 (Context, type.Val, line.Val, name.Val, value.Val));
4229 return false;
4230}
4231
4232/// ParseDIMacroFile:
4233/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4234bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4235#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4236 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004237 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004238 REQUIRED(file, MDField, ); \
4239 OPTIONAL(nodes, MDField, );
4240 PARSE_MD_FIELDS();
4241#undef VISIT_MD_FIELDS
4242
4243 Result = GET_OR_DISTINCT(DIMacroFile,
4244 (Context, type.Val, line.Val, file.Val, nodes.Val));
4245 return false;
4246}
4247
Adrian Prantlab1243f2015-06-29 23:03:47 +00004248/// ParseDIModule:
4249/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4250/// includePath: "/usr/include", isysroot: "/")
4251bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4252#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4253 REQUIRED(scope, MDField, ); \
4254 REQUIRED(name, MDStringField, ); \
4255 OPTIONAL(configMacros, MDStringField, ); \
4256 OPTIONAL(includePath, MDStringField, ); \
4257 OPTIONAL(isysroot, MDStringField, );
4258 PARSE_MD_FIELDS();
4259#undef VISIT_MD_FIELDS
4260
4261 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4262 configMacros.Val, includePath.Val, isysroot.Val));
4263 return false;
4264}
4265
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004266/// ParseDITemplateTypeParameter:
4267/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4268bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004269#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004270 OPTIONAL(name, MDStringField, ); \
4271 REQUIRED(type, MDField, );
4272 PARSE_MD_FIELDS();
4273#undef VISIT_MD_FIELDS
4274
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004275 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004276 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004277 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004278}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004279
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004280/// ParseDITemplateValueParameter:
4281/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004282/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004283bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004284#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004285 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004286 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004287 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004288 REQUIRED(value, MDField, );
4289 PARSE_MD_FIELDS();
4290#undef VISIT_MD_FIELDS
4291
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004292 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004293 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004294 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004295}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004296
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004297/// ParseDIGlobalVariable:
4298/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004299/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004300/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004301bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004302#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004303 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004304 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004305 OPTIONAL(linkageName, MDStringField, ); \
4306 OPTIONAL(file, MDField, ); \
4307 OPTIONAL(line, LineField, ); \
4308 OPTIONAL(type, MDField, ); \
4309 OPTIONAL(isLocal, MDBoolField, ); \
4310 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004311 OPTIONAL(declaration, MDField, ); \
4312 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004313 PARSE_MD_FIELDS();
4314#undef VISIT_MD_FIELDS
4315
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004316 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004317 (Context, scope.Val, name.Val, linkageName.Val,
4318 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004319 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004320 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004321}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004322
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004323/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004324/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004325/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4326/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004327/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004328/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4329/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004330bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004331#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004332 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004333 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004334 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004335 OPTIONAL(file, MDField, ); \
4336 OPTIONAL(line, LineField, ); \
4337 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004338 OPTIONAL(flags, DIFlagField, ); \
4339 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004340 PARSE_MD_FIELDS();
4341#undef VISIT_MD_FIELDS
4342
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004343 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004344 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004345 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004346 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004347}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004348
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004349/// ParseDIExpression:
4350/// ::= !DIExpression(0, 7, -1)
4351bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004352 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4353 Lex.Lex();
4354
4355 if (ParseToken(lltok::lparen, "expected '(' here"))
4356 return true;
4357
4358 SmallVector<uint64_t, 8> Elements;
4359 if (Lex.getKind() != lltok::rparen)
4360 do {
4361 if (Lex.getKind() == lltok::DwarfOp) {
4362 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4363 Lex.Lex();
4364 Elements.push_back(Op);
4365 continue;
4366 }
4367 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4368 }
4369
4370 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4371 return TokError("expected unsigned integer");
4372
4373 auto &U = Lex.getAPSIntVal();
4374 if (U.ugt(UINT64_MAX))
4375 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4376 Elements.push_back(U.getZExtValue());
4377 Lex.Lex();
4378 } while (EatIfPresent(lltok::comma));
4379
4380 if (ParseToken(lltok::rparen, "expected ')' here"))
4381 return true;
4382
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004383 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004384 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004385}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004386
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004387/// ParseDIGlobalVariableExpression:
4388/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4389bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4390 bool IsDistinct) {
4391#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4392 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004393 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004394 PARSE_MD_FIELDS();
4395#undef VISIT_MD_FIELDS
4396
4397 Result =
4398 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4399 return false;
4400}
4401
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004402/// ParseDIObjCProperty:
4403/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004404/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004405bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004406#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004407 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004408 OPTIONAL(file, MDField, ); \
4409 OPTIONAL(line, LineField, ); \
4410 OPTIONAL(setter, MDStringField, ); \
4411 OPTIONAL(getter, MDStringField, ); \
4412 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4413 OPTIONAL(type, MDField, );
4414 PARSE_MD_FIELDS();
4415#undef VISIT_MD_FIELDS
4416
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004417 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004418 (Context, name.Val, file.Val, line.Val, setter.Val,
4419 getter.Val, attributes.Val, type.Val));
4420 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004421}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004422
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004423/// ParseDIImportedEntity:
4424/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004425/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004426bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004427#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4428 REQUIRED(tag, DwarfTagField, ); \
4429 REQUIRED(scope, MDField, ); \
4430 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004431 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004432 OPTIONAL(line, LineField, ); \
4433 OPTIONAL(name, MDStringField, );
4434 PARSE_MD_FIELDS();
4435#undef VISIT_MD_FIELDS
4436
Adrian Prantld63bfd22017-07-19 00:09:54 +00004437 Result = GET_OR_DISTINCT(
4438 DIImportedEntity,
4439 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004440 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004441}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004442
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004443#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004444#undef NOP_FIELD
4445#undef REQUIRE_FIELD
4446#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004447
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004448/// ParseMetadataAsValue
4449/// ::= metadata i32 %local
4450/// ::= metadata i32 @global
4451/// ::= metadata i32 7
4452/// ::= metadata !0
4453/// ::= metadata !{...}
4454/// ::= metadata !"string"
4455bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4456 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004457 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004458 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004459 return true;
4460
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004461 V = MetadataAsValue::get(Context, MD);
4462 return false;
4463}
4464
4465/// ParseValueAsMetadata
4466/// ::= i32 %local
4467/// ::= i32 @global
4468/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004469bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4470 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004471 Type *Ty;
4472 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004473 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004474 return true;
4475 if (Ty->isMetadataTy())
4476 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4477
4478 Value *V;
4479 if (ParseValue(Ty, V, PFS))
4480 return true;
4481
4482 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004483 return false;
4484}
4485
4486/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004487/// ::= i32 %local
4488/// ::= i32 @global
4489/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004490/// ::= !42
4491/// ::= !{...}
4492/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004493/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004494bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004495 if (Lex.getKind() == lltok::MetadataVar) {
4496 MDNode *N;
4497 if (ParseSpecializedMDNode(N))
4498 return true;
4499 MD = N;
4500 return false;
4501 }
4502
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004503 // ValueAsMetadata:
4504 // <type> <value>
4505 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004506 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004507
4508 // '!'.
4509 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4510 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004511
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004512 // MDString:
4513 // ::= '!' STRINGCONSTANT
4514 if (Lex.getKind() == lltok::StringConstant) {
4515 MDString *S;
4516 if (ParseMDString(S))
4517 return true;
4518 MD = S;
4519 return false;
4520 }
4521
Dan Gohman8939ba332010-07-14 18:26:50 +00004522 // MDNode:
4523 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004524 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004525 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004526 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004527 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004528 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004529 return false;
4530}
4531
Victor Hernandez9d75c962010-01-11 22:31:58 +00004532//===----------------------------------------------------------------------===//
4533// Function Parsing.
4534//===----------------------------------------------------------------------===//
4535
Chris Lattner229907c2011-07-18 04:54:35 +00004536bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004537 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004538 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004539 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004540
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004543 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004544 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004545 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004547 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004548 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004549 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004550 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004551 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004552 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004553 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4554 (ID.UIntVal >> 1) & 1,
4555 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004556 return false;
4557 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004558 case ValID::t_GlobalName:
4559 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004560 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004561 case ValID::t_GlobalID:
4562 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004563 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004564 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004565 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004566 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004567 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004568 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569 return false;
4570 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004571 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4573 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004574
Dan Gohman518cda42011-12-17 00:04:22 +00004575 // The lexer has no type info, so builds all half, float, and double FP
4576 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004577 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004579 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004580 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004581 &Ignored);
4582 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004583 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004584 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004586 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004587
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004588 if (V->getType() != Ty)
4589 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004590 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004591
Chris Lattnerac161bf2009-01-02 07:01:27 +00004592 return false;
4593 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004594 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004595 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004596 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597 return false;
4598 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004599 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004600 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004601 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004602 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004604 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004605 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004606 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004607 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004608 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004610 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004611 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004612 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004613 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004615 case ValID::t_None:
4616 if (!Ty->isTokenTy())
4617 return Error(ID.Loc, "invalid type for none constant");
4618 V = Constant::getNullValue(Ty);
4619 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004620 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004621 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004623
Chris Lattnerac161bf2009-01-02 07:01:27 +00004624 V = ID.ConstantVal;
4625 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004626 case ValID::t_ConstantStruct:
4627 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004628 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004629 if (ST->getNumElements() != ID.UIntVal)
4630 return Error(ID.Loc,
4631 "initializer with struct type has wrong # elements");
4632 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4633 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004634
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004635 // Verify that the elements are compatible with the structtype.
4636 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4637 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4638 return Error(ID.Loc, "element " + Twine(i) +
4639 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004640
David Blaikieadbda4b2015-08-03 20:08:41 +00004641 V = ConstantStruct::get(
4642 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004643 } else
4644 return Error(ID.Loc, "constant expression type mismatch");
4645 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004647 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004649
Alex Lorenzd2255952015-07-17 22:07:03 +00004650bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4651 C = nullptr;
4652 ValID ID;
4653 auto Loc = Lex.getLoc();
4654 if (ParseValID(ID, /*PFS=*/nullptr))
4655 return true;
4656 switch (ID.Kind) {
4657 case ValID::t_APSInt:
4658 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004659 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004660 case ValID::t_Constant:
4661 case ValID::t_ConstantStruct:
4662 case ValID::t_PackedConstantStruct: {
4663 Value *V;
4664 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4665 return true;
4666 assert(isa<Constant>(V) && "Expected a constant value");
4667 C = cast<Constant>(V);
4668 return false;
4669 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004670 case ValID::t_Null:
4671 C = Constant::getNullValue(Ty);
4672 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004673 default:
4674 return Error(Loc, "expected a constant value");
4675 }
4676}
4677
David Majnemer8a1c45d2015-12-12 05:38:55 +00004678bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004679 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004680 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004681 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004682}
4683
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004684bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004685 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004686 return ParseType(Ty) ||
4687 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004688}
4689
Chris Lattner3ed871f2009-10-27 19:13:16 +00004690bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4691 PerFunctionState &PFS) {
4692 Value *V;
4693 Loc = Lex.getLoc();
4694 if (ParseTypeAndValue(V, PFS)) return true;
4695 if (!isa<BasicBlock>(V))
4696 return Error(Loc, "expected a basic block");
4697 BB = cast<BasicBlock>(V);
4698 return false;
4699}
4700
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701/// FunctionHeader
4702/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004703/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004704/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4706 // Parse the linkage.
4707 LocTy LinkageLoc = Lex.getLoc();
4708 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004709
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004710 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004711 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004712 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004713 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004714 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004715 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004716 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004717 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4718 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004719 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004720 return true;
4721
4722 // Verify that the linkage is ok.
4723 switch ((GlobalValue::LinkageTypes)Linkage) {
4724 case GlobalValue::ExternalLinkage:
4725 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004726 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004727 if (isDefine)
4728 return Error(LinkageLoc, "invalid linkage for function definition");
4729 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004730 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004732 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004733 case GlobalValue::LinkOnceAnyLinkage:
4734 case GlobalValue::LinkOnceODRLinkage:
4735 case GlobalValue::WeakAnyLinkage:
4736 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 if (!isDefine)
4738 return Error(LinkageLoc, "invalid linkage for function declaration");
4739 break;
4740 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004741 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004742 return Error(LinkageLoc, "invalid function linkage type");
4743 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004744
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004745 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4746 return Error(LinkageLoc,
4747 "symbol with local linkage must have default visibility");
4748
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004749 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004750 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004751
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004753
4754 std::string FunctionName;
4755 if (Lex.getKind() == lltok::GlobalVar) {
4756 FunctionName = Lex.getStrVal();
4757 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4758 unsigned NameID = Lex.getUIntVal();
4759
4760 if (NameID != NumberedVals.size())
4761 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004762 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004763 } else {
4764 return TokError("expected function name");
4765 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004766
Chris Lattner3822f632009-01-02 08:05:26 +00004767 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004768
Chris Lattner3822f632009-01-02 08:05:26 +00004769 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004771
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004772 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004773 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004774 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004775 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004776 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004777 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004779 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004780 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004781 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004782 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004783 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004784 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004785 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004786
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004787 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004788 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004789 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004790 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004791 (EatIfPresent(lltok::kw_section) &&
4792 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004793 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004794 ParseOptionalAlignment(Alignment) ||
4795 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004796 ParseStringConstant(GC)) ||
4797 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004798 ParseGlobalTypeAndValue(Prefix)) ||
4799 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004800 ParseGlobalTypeAndValue(Prologue)) ||
4801 (EatIfPresent(lltok::kw_personality) &&
4802 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004803 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804
Michael Gottesman41748d72013-06-27 00:25:01 +00004805 if (FuncAttrs.contains(Attribute::Builtin))
4806 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004807
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004809 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004810 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004811 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004813
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 // Okay, if we got here, the function is syntactically valid. Convert types
4815 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004816 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004817 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004818
Chris Lattnerac161bf2009-01-02 07:01:27 +00004819 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004820 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004821 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822 }
4823
Reid Kleckner7f720332017-04-13 00:58:09 +00004824 AttributeList PAL =
4825 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4826 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004827
Bill Wendling749a43d2012-12-30 13:50:49 +00004828 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004829 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4830
Chris Lattner229907c2011-07-18 04:54:35 +00004831 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004832 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004833 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004834
Craig Topper2617dcc2014-04-15 06:32:26 +00004835 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004836 if (!FunctionName.empty()) {
4837 // If this was a definition of a forward reference, remove the definition
4838 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004839 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 if (FRVI != ForwardRefVals.end()) {
4841 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004842 if (!Fn)
4843 return Error(FRVI->second.second, "invalid forward reference to "
4844 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004845 if (Fn->getType() != PFT)
4846 return Error(FRVI->second.second, "invalid forward reference to "
4847 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004848
Chris Lattnerac161bf2009-01-02 07:01:27 +00004849 ForwardRefVals.erase(FRVI);
4850 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004851 // Reject redefinitions.
4852 return Error(NameLoc, "invalid redefinition of function '" +
4853 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004854 } else if (M->getNamedValue(FunctionName)) {
4855 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004857
Dan Gohman399d6ae2009-08-29 23:37:49 +00004858 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004859 // If this is a definition of a forward referenced function, make sure the
4860 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004861 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004862 if (I != ForwardRefValIDs.end()) {
4863 Fn = cast<Function>(I->second.first);
4864 if (Fn->getType() != PFT)
4865 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004866 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 ForwardRefValIDs.erase(I);
4868 }
4869 }
4870
Craig Topper2617dcc2014-04-15 06:32:26 +00004871 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004872 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4873 else // Move the forward-reference to the correct spot in the module.
4874 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4875
4876 if (FunctionName.empty())
4877 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004878
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4880 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004881 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004882 Fn->setCallingConv(CC);
4883 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004884 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 Fn->setAlignment(Alignment);
4886 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004887 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004888 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004889 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004890 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004891 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004892 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004893
Chris Lattnerac161bf2009-01-02 07:01:27 +00004894 // Add all of the arguments we parsed to the function.
4895 Function::arg_iterator ArgIt = Fn->arg_begin();
4896 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4897 // If the argument has a name, insert it into the argument symbol table.
4898 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004899
Chris Lattnerac161bf2009-01-02 07:01:27 +00004900 // Set the name, if it conflicted, it will be auto-renamed.
4901 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004902
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004903 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004904 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4905 ArgList[i].Name + "'");
4906 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004907
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004908 if (isDefine)
4909 return false;
4910
Robin Morisset039781e2014-08-29 21:53:01 +00004911 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004912 ValID ID;
4913 if (FunctionName.empty()) {
4914 ID.Kind = ValID::t_GlobalID;
4915 ID.UIntVal = NumberedVals.size() - 1;
4916 } else {
4917 ID.Kind = ValID::t_GlobalName;
4918 ID.StrVal = FunctionName;
4919 }
4920 auto Blocks = ForwardRefBlockAddresses.find(ID);
4921 if (Blocks != ForwardRefBlockAddresses.end())
4922 return Error(Blocks->first.Loc,
4923 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924 return false;
4925}
4926
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004927bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4928 ValID ID;
4929 if (FunctionNumber == -1) {
4930 ID.Kind = ValID::t_GlobalName;
4931 ID.StrVal = F.getName();
4932 } else {
4933 ID.Kind = ValID::t_GlobalID;
4934 ID.UIntVal = FunctionNumber;
4935 }
4936
4937 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4938 if (Blocks == P.ForwardRefBlockAddresses.end())
4939 return false;
4940
4941 for (const auto &I : Blocks->second) {
4942 const ValID &BBID = I.first;
4943 GlobalValue *GV = I.second;
4944
4945 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4946 "Expected local id or name");
4947 BasicBlock *BB;
4948 if (BBID.Kind == ValID::t_LocalName)
4949 BB = GetBB(BBID.StrVal, BBID.Loc);
4950 else
4951 BB = GetBB(BBID.UIntVal, BBID.Loc);
4952 if (!BB)
4953 return P.Error(BBID.Loc, "referenced value is not a basic block");
4954
4955 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4956 GV->eraseFromParent();
4957 }
4958
4959 P.ForwardRefBlockAddresses.erase(Blocks);
4960 return false;
4961}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962
4963/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004964/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004965bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004966 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004967 return TokError("expected '{' in function body");
4968 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004969
Chris Lattner3432c622009-10-28 03:39:23 +00004970 int FunctionNumber = -1;
4971 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004972
Chris Lattner3432c622009-10-28 03:39:23 +00004973 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004974
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004975 // Resolve block addresses and allow basic blocks to be forward-declared
4976 // within this function.
4977 if (PFS.resolveForwardRefBlockAddresses())
4978 return true;
4979 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4980
Chris Lattnerbbddd962010-01-09 19:20:07 +00004981 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004982 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004983 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004984
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004985 while (Lex.getKind() != lltok::rbrace &&
4986 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004987 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004988
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004989 while (Lex.getKind() != lltok::rbrace)
4990 if (ParseUseListOrder(&PFS))
4991 return true;
4992
Chris Lattnerac161bf2009-01-02 07:01:27 +00004993 // Eat the }.
4994 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004995
Chris Lattnerac161bf2009-01-02 07:01:27 +00004996 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004997 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998}
4999
5000/// ParseBasicBlock
5001/// ::= LabelStr? Instruction*
5002bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5003 // If this basic block starts out with a name, remember it.
5004 std::string Name;
5005 LocTy NameLoc = Lex.getLoc();
5006 if (Lex.getKind() == lltok::LabelStr) {
5007 Name = Lex.getStrVal();
5008 Lex.Lex();
5009 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005010
Chris Lattnerac161bf2009-01-02 07:01:27 +00005011 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005012 if (!BB)
5013 return Error(NameLoc,
5014 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005015
Chris Lattnerac161bf2009-01-02 07:01:27 +00005016 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005017
Chris Lattnerac161bf2009-01-02 07:01:27 +00005018 // Parse the instructions in this block until we get a terminator.
5019 Instruction *Inst;
5020 do {
5021 // This instruction may have three possibilities for a name: a) none
5022 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5023 LocTy NameLoc = Lex.getLoc();
5024 int NameID = -1;
5025 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005026
Chris Lattnerac161bf2009-01-02 07:01:27 +00005027 if (Lex.getKind() == lltok::LocalVarID) {
5028 NameID = Lex.getUIntVal();
5029 Lex.Lex();
5030 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5031 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005032 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005033 NameStr = Lex.getStrVal();
5034 Lex.Lex();
5035 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5036 return true;
5037 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005038
Chris Lattner77b89dc2009-12-30 05:23:43 +00005039 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005040 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005041 case InstError: return true;
5042 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005043 BB->getInstList().push_back(Inst);
5044
Chris Lattner77b89dc2009-12-30 05:23:43 +00005045 // With a normal result, we check to see if the instruction is followed by
5046 // a comma and metadata.
5047 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005048 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005049 return true;
5050 break;
5051 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005052 BB->getInstList().push_back(Inst);
5053
Chris Lattner77b89dc2009-12-30 05:23:43 +00005054 // If the instruction parser ate an extra comma at the end of it, it
5055 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005056 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005057 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005058 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005059 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005060
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 // Set the name on the instruction.
5062 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5063 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005064
Chris Lattnerac161bf2009-01-02 07:01:27 +00005065 return false;
5066}
5067
5068//===----------------------------------------------------------------------===//
5069// Instruction Parsing.
5070//===----------------------------------------------------------------------===//
5071
5072/// ParseInstruction - Parse one of the many different instructions.
5073///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005074int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5075 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005076 lltok::Kind Token = Lex.getKind();
5077 if (Token == lltok::Eof)
5078 return TokError("found end of file when expecting more instructions");
5079 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005080 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005081 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005082
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 switch (Token) {
5084 default: return Error(Loc, "expected instruction opcode");
5085 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005086 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005087 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5088 case lltok::kw_br: return ParseBr(Inst, PFS);
5089 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005090 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005091 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005092 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005093 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5094 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005095 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5096 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005097 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005098 // Binary Operators.
5099 case lltok::kw_add:
5100 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005101 case lltok::kw_mul:
5102 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005103 bool NUW = EatIfPresent(lltok::kw_nuw);
5104 bool NSW = EatIfPresent(lltok::kw_nsw);
5105 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005106
Chris Lattnera676c0f2011-02-07 16:40:21 +00005107 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005108
Chris Lattnera676c0f2011-02-07 16:40:21 +00005109 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5110 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5111 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005112 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005113 case lltok::kw_fadd:
5114 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005115 case lltok::kw_fmul:
5116 case lltok::kw_fdiv:
5117 case lltok::kw_frem: {
5118 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5119 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5120 if (Res != 0)
5121 return Res;
5122 if (FMF.any())
5123 Inst->setFastMathFlags(FMF);
5124 return 0;
5125 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005126
Chris Lattner35315d02011-02-06 21:44:57 +00005127 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005128 case lltok::kw_udiv:
5129 case lltok::kw_lshr:
5130 case lltok::kw_ashr: {
5131 bool Exact = EatIfPresent(lltok::kw_exact);
5132
5133 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5134 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5135 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005136 }
5137
Chris Lattnerac161bf2009-01-02 07:01:27 +00005138 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005139 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005140 case lltok::kw_and:
5141 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005142 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005143 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5144 case lltok::kw_fcmp: {
5145 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5146 int Res = ParseCompare(Inst, PFS, KeywordVal);
5147 if (Res != 0)
5148 return Res;
5149 if (FMF.any())
5150 Inst->setFastMathFlags(FMF);
5151 return 0;
5152 }
5153
Chris Lattnerac161bf2009-01-02 07:01:27 +00005154 // Casts.
5155 case lltok::kw_trunc:
5156 case lltok::kw_zext:
5157 case lltok::kw_sext:
5158 case lltok::kw_fptrunc:
5159 case lltok::kw_fpext:
5160 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005161 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162 case lltok::kw_uitofp:
5163 case lltok::kw_sitofp:
5164 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005165 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005167 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168 // Other.
5169 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005170 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005171 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5172 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5173 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5174 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005175 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005176 // Call.
5177 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5178 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5179 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005180 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005181 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005182 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005183 case lltok::kw_load: return ParseLoad(Inst, PFS);
5184 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005185 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5186 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005187 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5189 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5190 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5191 }
5192}
5193
5194/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5195bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005196 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005197 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005198 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005199 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5200 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5201 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5202 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5203 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5204 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5205 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5206 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5207 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5208 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5209 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5210 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5211 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5212 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5213 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5214 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5215 }
5216 } else {
5217 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005218 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005219 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5220 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5221 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5222 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5223 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5224 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5225 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5226 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5227 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5228 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5229 }
5230 }
5231 Lex.Lex();
5232 return false;
5233}
5234
5235//===----------------------------------------------------------------------===//
5236// Terminator Instructions.
5237//===----------------------------------------------------------------------===//
5238
5239/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005240/// ::= 'ret' void (',' !dbg, !1)*
5241/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005242bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005243 PerFunctionState &PFS) {
5244 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005245 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005246 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005248 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005249
Chris Lattnerfdd87902009-10-05 05:54:46 +00005250 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005251 if (!ResType->isVoidTy())
5252 return Error(TypeLoc, "value doesn't match function result type '" +
5253 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005254
Owen Anderson55f1c092009-08-13 21:58:54 +00005255 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256 return false;
5257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005258
Chris Lattnerac161bf2009-01-02 07:01:27 +00005259 Value *RV;
5260 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005261
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005262 if (ResType != RV->getType())
5263 return Error(TypeLoc, "value doesn't match function result type '" +
5264 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005265
Owen Anderson55f1c092009-08-13 21:58:54 +00005266 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005267 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268}
5269
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270/// ParseBr
5271/// ::= 'br' TypeAndValue
5272/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5273bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5274 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005275 Value *Op0;
5276 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005277 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005278
Chris Lattnerac161bf2009-01-02 07:01:27 +00005279 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5280 Inst = BranchInst::Create(BB);
5281 return false;
5282 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005283
Owen Anderson55f1c092009-08-13 21:58:54 +00005284 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005285 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005286
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005288 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005289 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005290 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005291 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005292
Chris Lattner3ed871f2009-10-27 19:13:16 +00005293 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294 return false;
5295}
5296
5297/// ParseSwitch
5298/// Instruction
5299/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5300/// JumpTable
5301/// ::= (TypeAndValue ',' TypeAndValue)*
5302bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5303 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005304 Value *Cond;
5305 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005306 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5307 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005308 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005309 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5310 return true;
5311
Duncan Sands19d0b472010-02-16 11:11:14 +00005312 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005313 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005314
Chris Lattnerac161bf2009-01-02 07:01:27 +00005315 // Parse the jump table pairs.
5316 SmallPtrSet<Value*, 32> SeenCases;
5317 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5318 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005319 Value *Constant;
5320 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005321
Chris Lattnerac161bf2009-01-02 07:01:27 +00005322 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5323 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005324 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005325 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005326
David Blaikie70573dc2014-11-19 07:49:26 +00005327 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005328 return Error(CondLoc, "duplicate case value in switch");
5329 if (!isa<ConstantInt>(Constant))
5330 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005331
Chris Lattner3ed871f2009-10-27 19:13:16 +00005332 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005333 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005334
Chris Lattnerac161bf2009-01-02 07:01:27 +00005335 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005336
Chris Lattner3ed871f2009-10-27 19:13:16 +00005337 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005338 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5339 SI->addCase(Table[i].first, Table[i].second);
5340 Inst = SI;
5341 return false;
5342}
5343
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005344/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005345/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005346/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5347bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005348 LocTy AddrLoc;
5349 Value *Address;
5350 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005351 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5352 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005353 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005354
Duncan Sands19d0b472010-02-16 11:11:14 +00005355 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005356 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005357
Chris Lattner3ed871f2009-10-27 19:13:16 +00005358 // Parse the destination list.
5359 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005360
Chris Lattner3ed871f2009-10-27 19:13:16 +00005361 if (Lex.getKind() != lltok::rsquare) {
5362 BasicBlock *DestBB;
5363 if (ParseTypeAndBasicBlock(DestBB, PFS))
5364 return true;
5365 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005366
Chris Lattner3ed871f2009-10-27 19:13:16 +00005367 while (EatIfPresent(lltok::comma)) {
5368 if (ParseTypeAndBasicBlock(DestBB, PFS))
5369 return true;
5370 DestList.push_back(DestBB);
5371 }
5372 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005373
Chris Lattner3ed871f2009-10-27 19:13:16 +00005374 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5375 return true;
5376
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005377 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005378 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5379 IBI->addDestination(DestList[i]);
5380 Inst = IBI;
5381 return false;
5382}
5383
Chris Lattnerac161bf2009-01-02 07:01:27 +00005384/// ParseInvoke
5385/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5386/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5387bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5388 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005389 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005390 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005391 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005392 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005393 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005394 LocTy RetTypeLoc;
5395 ValID CalleeID;
5396 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005397 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005398
Chris Lattner3ed871f2009-10-27 19:13:16 +00005399 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005400 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005401 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005402 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005403 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5404 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005405 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005406 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005407 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005408 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005409 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005410 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005411
Chris Lattnerac161bf2009-01-02 07:01:27 +00005412 // If RetType is a non-function pointer type, then this is the short syntax
5413 // for the call, which means that RetType is just the return type. Infer the
5414 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005415 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5416 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005417 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005418 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005419 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5420 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005421
Chris Lattnerac161bf2009-01-02 07:01:27 +00005422 if (!FunctionType::isValidReturnType(RetType))
5423 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005424
Owen Anderson4056ca92009-07-29 22:17:13 +00005425 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005426 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005427
David Blaikie41ba2b42015-07-27 23:32:19 +00005428 CalleeID.FTy = Ty;
5429
Chris Lattnerac161bf2009-01-02 07:01:27 +00005430 // Look up the callee.
5431 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005432 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5433 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005434
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005435 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005436 SmallVector<Value *, 8> Args;
5437 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005438
Chris Lattnerac161bf2009-01-02 07:01:27 +00005439 // Loop through FunctionType's arguments and ensure they are specified
5440 // correctly. Also, gather any parameter attributes.
5441 FunctionType::param_iterator I = Ty->param_begin();
5442 FunctionType::param_iterator E = Ty->param_end();
5443 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005444 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005445 if (I != E) {
5446 ExpectedTy = *I++;
5447 } else if (!Ty->isVarArg()) {
5448 return Error(ArgList[i].Loc, "too many arguments specified");
5449 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005450
Chris Lattnerac161bf2009-01-02 07:01:27 +00005451 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5452 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005453 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005454 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005455 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005456 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005457
Chris Lattnerac161bf2009-01-02 07:01:27 +00005458 if (I != E)
5459 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005460
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005461 if (FnAttrs.hasAlignmentAttr())
5462 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005463
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005464 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005465 AttributeList PAL =
5466 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5467 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005468
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005469 InvokeInst *II =
5470 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005471 II->setCallingConv(CC);
5472 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005473 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005474 Inst = II;
5475 return false;
5476}
5477
Bill Wendlingf891bf82011-07-31 06:30:59 +00005478/// ParseResume
5479/// ::= 'resume' TypeAndValue
5480bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5481 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005482 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5483 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005484
Bill Wendlingf891bf82011-07-31 06:30:59 +00005485 ResumeInst *RI = ResumeInst::Create(Exn);
5486 Inst = RI;
5487 return false;
5488}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005489
David Majnemer654e1302015-07-31 17:58:14 +00005490bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5491 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005492 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005493 return true;
5494
5495 while (Lex.getKind() != lltok::rsquare) {
5496 // If this isn't the first argument, we need a comma.
5497 if (!Args.empty() &&
5498 ParseToken(lltok::comma, "expected ',' in argument list"))
5499 return true;
5500
5501 // Parse the argument.
5502 LocTy ArgLoc;
5503 Type *ArgTy = nullptr;
5504 if (ParseType(ArgTy, ArgLoc))
5505 return true;
5506
5507 Value *V;
5508 if (ArgTy->isMetadataTy()) {
5509 if (ParseMetadataAsValue(V, PFS))
5510 return true;
5511 } else {
5512 if (ParseValue(ArgTy, V, PFS))
5513 return true;
5514 }
5515 Args.push_back(V);
5516 }
5517
5518 Lex.Lex(); // Lex the ']'.
5519 return false;
5520}
5521
5522/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005523/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005524bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005525 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005526
David Majnemer8a1c45d2015-12-12 05:38:55 +00005527 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5528 return true;
5529
5530 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005531 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005532
5533 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5534 return true;
5535
5536 BasicBlock *UnwindBB = nullptr;
5537 if (Lex.getKind() == lltok::kw_to) {
5538 Lex.Lex();
5539 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5540 return true;
5541 } else {
5542 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5543 return true;
5544 }
5545 }
5546
David Majnemer8a1c45d2015-12-12 05:38:55 +00005547 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005548 return false;
5549}
5550
5551/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005552/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005553bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005554 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005555
David Majnemer8a1c45d2015-12-12 05:38:55 +00005556 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5557 return true;
5558
5559 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005560 return true;
5561
David Majnemer0bc0eef2015-08-15 02:46:08 +00005562 BasicBlock *BB;
5563 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5564 ParseTypeAndBasicBlock(BB, PFS))
5565 return true;
5566
David Majnemer8a1c45d2015-12-12 05:38:55 +00005567 Inst = CatchReturnInst::Create(CatchPad, BB);
5568 return false;
5569}
5570
5571/// ParseCatchSwitch
5572/// ::= 'catchswitch' within Parent
5573bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5574 Value *ParentPad;
5575 LocTy BBLoc;
5576
5577 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5578 return true;
5579
5580 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5581 Lex.getKind() != lltok::LocalVarID)
5582 return TokError("expected scope value for catchswitch");
5583
5584 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5585 return true;
5586
5587 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5588 return true;
5589
5590 SmallVector<BasicBlock *, 32> Table;
5591 do {
5592 BasicBlock *DestBB;
5593 if (ParseTypeAndBasicBlock(DestBB, PFS))
5594 return true;
5595 Table.push_back(DestBB);
5596 } while (EatIfPresent(lltok::comma));
5597
5598 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5599 return true;
5600
5601 if (ParseToken(lltok::kw_unwind,
5602 "expected 'unwind' after catchswitch scope"))
5603 return true;
5604
5605 BasicBlock *UnwindBB = nullptr;
5606 if (EatIfPresent(lltok::kw_to)) {
5607 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5608 return true;
5609 } else {
5610 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5611 return true;
5612 }
5613
5614 auto *CatchSwitch =
5615 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5616 for (BasicBlock *DestBB : Table)
5617 CatchSwitch->addHandler(DestBB);
5618 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005619 return false;
5620}
5621
5622/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005623/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005624bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005625 Value *CatchSwitch = nullptr;
5626
5627 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5628 return true;
5629
5630 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5631 return TokError("expected scope value for catchpad");
5632
5633 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5634 return true;
5635
David Majnemer654e1302015-07-31 17:58:14 +00005636 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005637 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005638 return true;
5639
David Majnemer8a1c45d2015-12-12 05:38:55 +00005640 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005641 return false;
5642}
5643
David Majnemer654e1302015-07-31 17:58:14 +00005644/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005645/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005646bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005647 Value *ParentPad = nullptr;
5648
5649 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5650 return true;
5651
5652 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5653 Lex.getKind() != lltok::LocalVarID)
5654 return TokError("expected scope value for cleanuppad");
5655
5656 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5657 return true;
5658
David Majnemer654e1302015-07-31 17:58:14 +00005659 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005660 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005661 return true;
5662
David Majnemer8a1c45d2015-12-12 05:38:55 +00005663 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005664 return false;
5665}
5666
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667//===----------------------------------------------------------------------===//
5668// Binary Operators.
5669//===----------------------------------------------------------------------===//
5670
5671/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005672/// ::= ArithmeticOps TypeAndValue ',' Value
5673///
5674/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5675/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005676bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005677 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 LocTy Loc; Value *LHS, *RHS;
5679 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5680 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5681 ParseValue(LHS->getType(), RHS, PFS))
5682 return true;
5683
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005684 bool Valid;
5685 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005686 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005687 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005688 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5689 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005690 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005691 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5692 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005693 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005694
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005695 if (!Valid)
5696 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005697
Chris Lattnerac161bf2009-01-02 07:01:27 +00005698 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5699 return false;
5700}
5701
5702/// ParseLogical
5703/// ::= ArithmeticOps TypeAndValue ',' Value {
5704bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5705 unsigned Opc) {
5706 LocTy Loc; Value *LHS, *RHS;
5707 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5708 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5709 ParseValue(LHS->getType(), RHS, PFS))
5710 return true;
5711
Duncan Sands9dff9be2010-02-15 16:12:20 +00005712 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005713 return Error(Loc,"instruction requires integer or integer vector operands");
5714
5715 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5716 return false;
5717}
5718
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719/// ParseCompare
5720/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5721/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005722bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5723 unsigned Opc) {
5724 // Parse the integer/fp comparison predicate.
5725 LocTy Loc;
5726 unsigned Pred;
5727 Value *LHS, *RHS;
5728 if (ParseCmpPredicate(Pred, Opc) ||
5729 ParseTypeAndValue(LHS, Loc, PFS) ||
5730 ParseToken(lltok::comma, "expected ',' after compare value") ||
5731 ParseValue(LHS->getType(), RHS, PFS))
5732 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005733
Chris Lattnerac161bf2009-01-02 07:01:27 +00005734 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005735 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005736 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005737 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005738 } else {
5739 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005740 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00005741 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005742 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005743 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005744 }
5745 return false;
5746}
5747
5748//===----------------------------------------------------------------------===//
5749// Other Instructions.
5750//===----------------------------------------------------------------------===//
5751
5752
5753/// ParseCast
5754/// ::= CastOpc TypeAndValue 'to' Type
5755bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5756 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005757 LocTy Loc;
5758 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005759 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005760 if (ParseTypeAndValue(Op, Loc, PFS) ||
5761 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5762 ParseType(DestTy))
5763 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005764
Chris Lattner89d856e2009-03-01 00:53:13 +00005765 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5766 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005767 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005768 getTypeString(Op->getType()) + "' to '" +
5769 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005770 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005771 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5772 return false;
5773}
5774
5775/// ParseSelect
5776/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5777bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5778 LocTy Loc;
5779 Value *Op0, *Op1, *Op2;
5780 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5781 ParseToken(lltok::comma, "expected ',' after select condition") ||
5782 ParseTypeAndValue(Op1, PFS) ||
5783 ParseToken(lltok::comma, "expected ',' after select value") ||
5784 ParseTypeAndValue(Op2, PFS))
5785 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005786
Chris Lattnerac161bf2009-01-02 07:01:27 +00005787 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5788 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005789
Chris Lattnerac161bf2009-01-02 07:01:27 +00005790 Inst = SelectInst::Create(Op0, Op1, Op2);
5791 return false;
5792}
5793
Chris Lattnerb55ab542009-01-05 08:18:44 +00005794/// ParseVA_Arg
5795/// ::= 'va_arg' TypeAndValue ',' Type
5796bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005797 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005798 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005799 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 if (ParseTypeAndValue(Op, PFS) ||
5801 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005802 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005804
Chris Lattnerb55ab542009-01-05 08:18:44 +00005805 if (!EltTy->isFirstClassType())
5806 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005807
5808 Inst = new VAArgInst(Op, EltTy);
5809 return false;
5810}
5811
5812/// ParseExtractElement
5813/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5814bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5815 LocTy Loc;
5816 Value *Op0, *Op1;
5817 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5818 ParseToken(lltok::comma, "expected ',' after extract value") ||
5819 ParseTypeAndValue(Op1, PFS))
5820 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005821
Chris Lattnerac161bf2009-01-02 07:01:27 +00005822 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5823 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005824
Eric Christopherc9742252009-07-25 02:28:41 +00005825 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005826 return false;
5827}
5828
5829/// ParseInsertElement
5830/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5831bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5832 LocTy Loc;
5833 Value *Op0, *Op1, *Op2;
5834 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5835 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5836 ParseTypeAndValue(Op1, PFS) ||
5837 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5838 ParseTypeAndValue(Op2, PFS))
5839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005840
Chris Lattnerac161bf2009-01-02 07:01:27 +00005841 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005842 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005843
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5845 return false;
5846}
5847
5848/// ParseShuffleVector
5849/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5850bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5851 LocTy Loc;
5852 Value *Op0, *Op1, *Op2;
5853 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5854 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5855 ParseTypeAndValue(Op1, PFS) ||
5856 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5857 ParseTypeAndValue(Op2, PFS))
5858 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005859
Chris Lattnerac161bf2009-01-02 07:01:27 +00005860 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005861 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005862
Chris Lattnerac161bf2009-01-02 07:01:27 +00005863 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5864 return false;
5865}
5866
5867/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005868/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005869int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005870 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005871 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005872
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005873 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005874 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5875 ParseValue(Ty, Op0, PFS) ||
5876 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005877 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005878 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5879 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005880
Chris Lattnerf4f03422009-12-30 05:27:33 +00005881 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005882 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005883
5884 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005885 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005886
Chris Lattner3822f632009-01-02 08:05:26 +00005887 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888 break;
5889
Chris Lattnerf4f03422009-12-30 05:27:33 +00005890 if (Lex.getKind() == lltok::MetadataVar) {
5891 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005892 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005893 }
Devang Patel8f842d32009-10-16 18:45:49 +00005894
Chris Lattner3822f632009-01-02 08:05:26 +00005895 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005896 ParseValue(Ty, Op0, PFS) ||
5897 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005898 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005899 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5900 return true;
5901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005902
Chris Lattnerac161bf2009-01-02 07:01:27 +00005903 if (!Ty->isFirstClassType())
5904 return Error(TypeLoc, "phi node must have first class type");
5905
Jay Foad52131342011-03-30 11:28:46 +00005906 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005907 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5908 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5909 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005910 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005911}
5912
Bill Wendlingfae14752011-08-12 20:24:12 +00005913/// ParseLandingPad
5914/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5915/// Clause
5916/// ::= 'catch' TypeAndValue
5917/// ::= 'filter'
5918/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5919bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005920 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005921
David Majnemer7fddecc2015-06-17 20:52:32 +00005922 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005923 return true;
5924
David Majnemer7fddecc2015-06-17 20:52:32 +00005925 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005926 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5927
5928 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5929 LandingPadInst::ClauseType CT;
5930 if (EatIfPresent(lltok::kw_catch))
5931 CT = LandingPadInst::Catch;
5932 else if (EatIfPresent(lltok::kw_filter))
5933 CT = LandingPadInst::Filter;
5934 else
5935 return TokError("expected 'catch' or 'filter' clause type");
5936
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005937 Value *V;
5938 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005939 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005940 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005941
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005942 // A 'catch' type expects a non-array constant. A filter clause expects an
5943 // array constant.
5944 if (CT == LandingPadInst::Catch) {
5945 if (isa<ArrayType>(V->getType()))
5946 Error(VLoc, "'catch' clause has an invalid type");
5947 } else {
5948 if (!isa<ArrayType>(V->getType()))
5949 Error(VLoc, "'filter' clause has an invalid type");
5950 }
5951
Owen Andersonf8f259d2015-03-09 07:13:42 +00005952 Constant *CV = dyn_cast<Constant>(V);
5953 if (!CV)
5954 return Error(VLoc, "clause argument must be a constant");
5955 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005956 }
5957
Owen Andersonf8f259d2015-03-09 07:13:42 +00005958 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005959 return false;
5960}
5961
Chris Lattnerac161bf2009-01-02 07:01:27 +00005962/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005963/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5964/// OptionalAttrs Type Value ParameterList OptionalAttrs
5965/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5966/// OptionalAttrs Type Value ParameterList OptionalAttrs
5967/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5968/// OptionalAttrs Type Value ParameterList OptionalAttrs
5969/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5970/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005971bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005972 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005973 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005974 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005975 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005976 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005977 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005978 LocTy RetTypeLoc;
5979 ValID CalleeID;
5980 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005981 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005982 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005983
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005984 if (TCK != CallInst::TCK_None &&
5985 ParseToken(lltok::kw_call,
5986 "expected 'tail call', 'musttail call', or 'notail call'"))
5987 return true;
5988
5989 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5990
5991 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005992 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005993 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005994 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5995 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005996 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5997 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005998 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005999
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006000 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6001 return Error(CallLoc, "fast-math-flags specified for call without "
6002 "floating-point scalar or vector return type");
6003
Chris Lattnerac161bf2009-01-02 07:01:27 +00006004 // If RetType is a non-function pointer type, then this is the short syntax
6005 // for the call, which means that RetType is just the return type. Infer the
6006 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006007 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6008 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006009 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006010 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006011 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6012 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006013
Chris Lattnerac161bf2009-01-02 07:01:27 +00006014 if (!FunctionType::isValidReturnType(RetType))
6015 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006016
Owen Anderson4056ca92009-07-29 22:17:13 +00006017 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006018 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006019
David Blaikie41ba2b42015-07-27 23:32:19 +00006020 CalleeID.FTy = Ty;
6021
Chris Lattnerac161bf2009-01-02 07:01:27 +00006022 // Look up the callee.
6023 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00006024 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6025 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006026
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006027 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006028 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006029
Chris Lattnerac161bf2009-01-02 07:01:27 +00006030 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006031
Chris Lattnerac161bf2009-01-02 07:01:27 +00006032 // Loop through FunctionType's arguments and ensure they are specified
6033 // correctly. Also, gather any parameter attributes.
6034 FunctionType::param_iterator I = Ty->param_begin();
6035 FunctionType::param_iterator E = Ty->param_end();
6036 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006037 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006038 if (I != E) {
6039 ExpectedTy = *I++;
6040 } else if (!Ty->isVarArg()) {
6041 return Error(ArgList[i].Loc, "too many arguments specified");
6042 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006043
Chris Lattnerac161bf2009-01-02 07:01:27 +00006044 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6045 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006046 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006047 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006048 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006049 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006050
Chris Lattnerac161bf2009-01-02 07:01:27 +00006051 if (I != E)
6052 return Error(CallLoc, "not enough parameters specified for call");
6053
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006054 if (FnAttrs.hasAlignmentAttr())
6055 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006056
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006057 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006058 AttributeList PAL =
6059 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6060 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006061
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006062 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006063 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006064 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006065 if (FMF.any())
6066 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006067 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006068 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006069 Inst = CI;
6070 return false;
6071}
6072
6073//===----------------------------------------------------------------------===//
6074// Memory Instructions.
6075//===----------------------------------------------------------------------===//
6076
6077/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006078/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6079/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006080int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006081 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006082 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006083 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006084 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006085 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006086
6087 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006088 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006089
David Majnemera3b0eb22015-02-16 08:38:03 +00006090 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006091
David Majnemera3b0eb22015-02-16 08:38:03 +00006092 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6093 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006094
Chris Lattnerb2f39502009-12-30 05:44:30 +00006095 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006096 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006097 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006098 if (ParseOptionalAlignment(Alignment))
6099 return true;
6100 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6101 return true;
6102 } else if (Lex.getKind() == lltok::kw_addrspace) {
6103 ASLoc = Lex.getLoc();
6104 if (ParseOptionalAddrSpace(AddrSpace))
6105 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006106 } else if (Lex.getKind() == lltok::MetadataVar) {
6107 AteExtraComma = true;
6108 } else {
6109 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006110 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6111 (!AteExtraComma &&
6112 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006113 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006114 }
6115 }
6116
Dan Gohman2140a742010-05-28 01:14:11 +00006117 if (Size && !Size->getType()->isIntegerTy())
6118 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006119
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006120 const DataLayout &DL = M->getDataLayout();
6121 unsigned AS = DL.getAllocaAddrSpace();
6122 if (AS != AddrSpace) {
6123 // TODO: In the future it should be possible to specify addrspace per-alloca.
6124 return Error(ASLoc, "address space must match datalayout");
6125 }
6126
6127 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006128 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006129 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006130 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006131 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132}
6133
6134/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006135/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006136/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006137/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006138int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006139 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006140 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006141 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006142 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006143 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006144 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006145
6146 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006147 isAtomic = true;
6148 Lex.Lex();
6149 }
6150
Chris Lattnerbc639292011-11-27 06:56:53 +00006151 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006152 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006153 isVolatile = true;
6154 Lex.Lex();
6155 }
6156
David Blaikie15d9a4c2015-04-06 20:59:48 +00006157 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006158 LocTy ExplicitTypeLoc = Lex.getLoc();
6159 if (ParseType(Ty) ||
6160 ParseToken(lltok::comma, "expected comma after load's type") ||
6161 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006162 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006163 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6164 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006165
David Blaikie15d9a4c2015-04-06 20:59:48 +00006166 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006167 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006168 if (isAtomic && !Alignment)
6169 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006170 if (Ordering == AtomicOrdering::Release ||
6171 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006172 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006173
David Blaikiea79ac142015-02-27 21:17:42 +00006174 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6175 return Error(ExplicitTypeLoc,
6176 "explicit pointee type doesn't match operand's pointee type");
6177
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006178 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006179 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006180}
6181
6182/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006183
6184/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6185/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006186/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006187int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006188 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006189 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006190 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006191 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006192 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006193 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006194
6195 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006196 isAtomic = true;
6197 Lex.Lex();
6198 }
6199
Chris Lattnerbc639292011-11-27 06:56:53 +00006200 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006201 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006202 isVolatile = true;
6203 Lex.Lex();
6204 }
6205
Chris Lattnerac161bf2009-01-02 07:01:27 +00006206 if (ParseTypeAndValue(Val, Loc, PFS) ||
6207 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006208 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006209 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006210 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006211 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006212
Duncan Sands19d0b472010-02-16 11:11:14 +00006213 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006214 return Error(PtrLoc, "store operand must be a pointer");
6215 if (!Val->getType()->isFirstClassType())
6216 return Error(Loc, "store operand must be a first class value");
6217 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6218 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006219 if (isAtomic && !Alignment)
6220 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006221 if (Ordering == AtomicOrdering::Acquire ||
6222 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006223 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006224
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006225 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006226 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006227}
6228
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006229/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006230/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6231/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006232int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006233 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6234 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006235 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6236 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006237 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006238 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006239 bool isWeak = false;
6240
6241 if (EatIfPresent(lltok::kw_weak))
6242 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006243
6244 if (EatIfPresent(lltok::kw_volatile))
6245 isVolatile = true;
6246
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006247 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6248 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6249 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6250 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6251 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006252 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006253 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006254 return true;
6255
JF Bastien800f87a2016-04-06 21:19:33 +00006256 if (SuccessOrdering == AtomicOrdering::Unordered ||
6257 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006258 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006259 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6260 return TokError("cmpxchg failure argument shall be no stronger than the "
6261 "success argument");
6262 if (FailureOrdering == AtomicOrdering::Release ||
6263 FailureOrdering == AtomicOrdering::AcquireRelease)
6264 return TokError(
6265 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006266 if (!Ptr->getType()->isPointerTy())
6267 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6268 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6269 return Error(CmpLoc, "compare value and pointer type do not match");
6270 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6271 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006272 if (!New->getType()->isFirstClassType())
6273 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006274 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006275 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006276 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006277 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006278 Inst = CXI;
6279 return AteExtraComma ? InstExtraComma : InstNormal;
6280}
6281
6282/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006283/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6284/// 'singlethread'? AtomicOrdering
6285int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006286 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6287 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006288 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006289 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006290 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006291 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006292
6293 if (EatIfPresent(lltok::kw_volatile))
6294 isVolatile = true;
6295
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006296 switch (Lex.getKind()) {
6297 default: return TokError("expected binary operation in atomicrmw");
6298 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6299 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6300 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6301 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6302 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6303 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6304 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6305 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6306 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6307 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6308 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6309 }
6310 Lex.Lex(); // Eat the operation.
6311
6312 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6313 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6314 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006315 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006316 return true;
6317
JF Bastien800f87a2016-04-06 21:19:33 +00006318 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006319 return TokError("atomicrmw cannot be unordered");
6320 if (!Ptr->getType()->isPointerTy())
6321 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6322 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6323 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6324 if (!Val->getType()->isIntegerTy())
6325 return Error(ValLoc, "atomicrmw operand must be an integer");
6326 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6327 if (Size < 8 || (Size & (Size - 1)))
6328 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6329 " integer");
6330
6331 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006332 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006333 RMWI->setVolatile(isVolatile);
6334 Inst = RMWI;
6335 return AteExtraComma ? InstExtraComma : InstNormal;
6336}
6337
Eli Friedmanfee02c62011-07-25 23:16:38 +00006338/// ParseFence
6339/// ::= 'fence' 'singlethread'? AtomicOrdering
6340int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006341 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006342 SyncScope::ID SSID = SyncScope::System;
6343 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006344 return true;
6345
JF Bastien800f87a2016-04-06 21:19:33 +00006346 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006347 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006348 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006349 return TokError("fence cannot be monotonic");
6350
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006351 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006352 return InstNormal;
6353}
6354
Chris Lattnerac161bf2009-01-02 07:01:27 +00006355/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006356/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006357int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006358 Value *Ptr = nullptr;
6359 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006360 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006361
Dan Gohman16cbbe42009-07-29 15:58:36 +00006362 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006363
David Blaikie79e6c742015-02-27 19:29:02 +00006364 Type *Ty = nullptr;
6365 LocTy ExplicitTypeLoc = Lex.getLoc();
6366 if (ParseType(Ty) ||
6367 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6368 ParseTypeAndValue(Ptr, Loc, PFS))
6369 return true;
6370
Eli Benderskyd9806682013-04-22 17:03:42 +00006371 Type *BaseType = Ptr->getType();
6372 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6373 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006374 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006375
David Blaikie8d757942015-03-09 23:08:44 +00006376 if (Ty != BasePointerType->getElementType())
6377 return Error(ExplicitTypeLoc,
6378 "explicit pointee type doesn't match operand's pointee type");
6379
Chris Lattnerac161bf2009-01-02 07:01:27 +00006380 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006381 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006382 // GEP returns a vector of pointers if at least one of parameters is a vector.
6383 // All vector parameters should have the same vector width.
6384 unsigned GEPWidth = BaseType->isVectorTy() ?
6385 BaseType->getVectorNumElements() : 0;
6386
Chris Lattner3822f632009-01-02 08:05:26 +00006387 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006388 if (Lex.getKind() == lltok::MetadataVar) {
6389 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006390 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006391 }
Chris Lattner3822f632009-01-02 08:05:26 +00006392 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006393 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006394 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006395
Nadav Rotem3924cb02011-12-05 06:29:09 +00006396 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006397 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6398 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006399 return Error(EltLoc,
6400 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006401 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006402 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006403 Indices.push_back(Val);
6404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006405
Craig Toppere3dcce92015-08-01 22:20:21 +00006406 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006407 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006408 return Error(Loc, "base element of getelementptr must be sized");
6409
David Blaikied33bad32015-04-17 22:32:13 +00006410 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006411 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006412 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006413 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006414 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006415 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006416}
6417
6418/// ParseExtractValue
6419/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006420int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006421 Value *Val; LocTy Loc;
6422 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006423 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006424 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006425 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006426 return true;
6427
Chris Lattner392be582010-02-12 20:49:41 +00006428 if (!Val->getType()->isAggregateType())
6429 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006430
Jay Foad57aa6362011-07-13 10:26:04 +00006431 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006432 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006433 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006434 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006435}
6436
6437/// ParseInsertValue
6438/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006439int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006440 Value *Val0, *Val1; LocTy Loc0, Loc1;
6441 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006442 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006443 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6444 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6445 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006446 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006447 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006448
Chris Lattner392be582010-02-12 20:49:41 +00006449 if (!Val0->getType()->isAggregateType())
6450 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006451
David Majnemer30074532015-02-11 07:43:58 +00006452 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6453 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006454 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006455 if (IndexedType != Val1->getType())
6456 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6457 getTypeString(Val1->getType()) + "' instead of '" +
6458 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006459 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006460 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006461}
Nick Lewycky49f89192009-04-04 07:22:01 +00006462
6463//===----------------------------------------------------------------------===//
6464// Embedded metadata.
6465//===----------------------------------------------------------------------===//
6466
6467/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006468/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006469/// Element
6470/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006471bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006472 if (ParseToken(lltok::lbrace, "expected '{' here"))
6473 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006474
Dan Gohman1e0213a2010-07-13 19:33:27 +00006475 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006476 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006477 return false;
6478
Nick Lewycky49f89192009-04-04 07:22:01 +00006479 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006480 // Null is a special case since it is typeless.
6481 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006482 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006483 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006484 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006485
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006486 Metadata *MD;
6487 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006488 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006489 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006490 } while (EatIfPresent(lltok::comma));
6491
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006492 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006493}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006494
6495//===----------------------------------------------------------------------===//
6496// Use-list order directives.
6497//===----------------------------------------------------------------------===//
6498bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6499 SMLoc Loc) {
6500 if (V->use_empty())
6501 return Error(Loc, "value has no uses");
6502
6503 unsigned NumUses = 0;
6504 SmallDenseMap<const Use *, unsigned, 16> Order;
6505 for (const Use &U : V->uses()) {
6506 if (++NumUses > Indexes.size())
6507 break;
6508 Order[&U] = Indexes[NumUses - 1];
6509 }
6510 if (NumUses < 2)
6511 return Error(Loc, "value only has one use");
6512 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6513 return Error(Loc, "wrong number of indexes, expected " +
6514 Twine(std::distance(V->use_begin(), V->use_end())));
6515
6516 V->sortUseList([&](const Use &L, const Use &R) {
6517 return Order.lookup(&L) < Order.lookup(&R);
6518 });
6519 return false;
6520}
6521
6522/// ParseUseListOrderIndexes
6523/// ::= '{' uint32 (',' uint32)+ '}'
6524bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6525 SMLoc Loc = Lex.getLoc();
6526 if (ParseToken(lltok::lbrace, "expected '{' here"))
6527 return true;
6528 if (Lex.getKind() == lltok::rbrace)
6529 return Lex.Error("expected non-empty list of uselistorder indexes");
6530
6531 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6532 // indexes should be distinct numbers in the range [0, size-1], and should
6533 // not be in order.
6534 unsigned Offset = 0;
6535 unsigned Max = 0;
6536 bool IsOrdered = true;
6537 assert(Indexes.empty() && "Expected empty order vector");
6538 do {
6539 unsigned Index;
6540 if (ParseUInt32(Index))
6541 return true;
6542
6543 // Update consistency checks.
6544 Offset += Index - Indexes.size();
6545 Max = std::max(Max, Index);
6546 IsOrdered &= Index == Indexes.size();
6547
6548 Indexes.push_back(Index);
6549 } while (EatIfPresent(lltok::comma));
6550
6551 if (ParseToken(lltok::rbrace, "expected '}' here"))
6552 return true;
6553
6554 if (Indexes.size() < 2)
6555 return Error(Loc, "expected >= 2 uselistorder indexes");
6556 if (Offset != 0 || Max >= Indexes.size())
6557 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6558 if (IsOrdered)
6559 return Error(Loc, "expected uselistorder indexes to change the order");
6560
6561 return false;
6562}
6563
6564/// ParseUseListOrder
6565/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6566bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6567 SMLoc Loc = Lex.getLoc();
6568 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6569 return true;
6570
6571 Value *V;
6572 SmallVector<unsigned, 16> Indexes;
6573 if (ParseTypeAndValue(V, PFS) ||
6574 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6575 ParseUseListOrderIndexes(Indexes))
6576 return true;
6577
6578 return sortUseListOrder(V, Indexes, Loc);
6579}
6580
6581/// ParseUseListOrderBB
6582/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6583bool LLParser::ParseUseListOrderBB() {
6584 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6585 SMLoc Loc = Lex.getLoc();
6586 Lex.Lex();
6587
6588 ValID Fn, Label;
6589 SmallVector<unsigned, 16> Indexes;
6590 if (ParseValID(Fn) ||
6591 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6592 ParseValID(Label) ||
6593 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6594 ParseUseListOrderIndexes(Indexes))
6595 return true;
6596
6597 // Check the function.
6598 GlobalValue *GV;
6599 if (Fn.Kind == ValID::t_GlobalName)
6600 GV = M->getNamedValue(Fn.StrVal);
6601 else if (Fn.Kind == ValID::t_GlobalID)
6602 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6603 else
6604 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6605 if (!GV)
6606 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6607 auto *F = dyn_cast<Function>(GV);
6608 if (!F)
6609 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6610 if (F->isDeclaration())
6611 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6612
6613 // Check the basic block.
6614 if (Label.Kind == ValID::t_LocalID)
6615 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6616 if (Label.Kind != ValID::t_LocalName)
6617 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006618 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006619 if (!V)
6620 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6621 if (!isa<BasicBlock>(V))
6622 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6623
6624 return sortUseListOrder(V, Indexes, Loc);
6625}