blob: 941ee347a78d8f26b4b1b6efe64f86d38aea89b9 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000019#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000044#include "llvm/Support/Dwarf.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 Kleckner211b1f32017-04-10 20:34:19 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeList::FunctionIndex);
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex,
136 AS.getFnAttributes());
Bill Wendlingb32b0412013-02-08 06:32:06 +0000137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
Reid Klecknerb5180542017-03-21 16:57:19 +0000147 AS = AS.addAttributes(
148 Context, AttributeList::FunctionIndex,
149 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000152 AttributeList AS = CI->getAttributes();
Reid Kleckner211b1f32017-04-10 20:34:19 +0000153 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeList::FunctionIndex);
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex,
155 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000156 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000157 AS = AS.addAttributes(
158 Context, AttributeList::FunctionIndex,
159 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000160 CI->setAttributes(AS);
161 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000162 AttributeList AS = II->getAttributes();
Reid Kleckner211b1f32017-04-10 20:34:19 +0000163 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeList::FunctionIndex);
164 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex,
165 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000166 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000167 AS = AS.addAttributes(
168 Context, AttributeList::FunctionIndex,
169 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000170 II->setAttributes(AS);
171 } else {
172 llvm_unreachable("invalid object with forward attribute group reference");
173 }
174 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000175
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000176 // If there are entries in ForwardRefBlockAddresses at this point, the
177 // function was never defined.
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000181
David Majnemer19b51052015-02-11 07:43:56 +0000182 for (const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186
187 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
188 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
189 if (I->second.second.isValid())
190 return Error(I->second.second,
191 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000192
David Majnemerdad0a642014-06-27 18:19:56 +0000193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first + "'");
197
Chris Lattnerac161bf2009-01-02 07:01:27 +0000198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000202
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000206 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000207
Devang Pateld2541152009-07-08 19:23:54 +0000208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000211 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
217 }
Devang Pateld2541152009-07-08 19:23:54 +0000218
Mehdi Aminie4709272016-09-14 22:29:59 +0000219 for (auto *Inst : InstsWithTBAATag) {
220 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
221 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
222 auto *UpgradedMD = UpgradeTBAANode(*MD);
223 if (MD != UpgradedMD)
224 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000226
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 // Look for intrinsic functions and CallInst that need to be upgraded
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000230
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000231 // Some types could be renamed during loading if several modules are
232 // loaded in the same LLVMContext (LTO scenario). In this case we should
233 // remangle intrinsics names as well.
234 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
235 Function *F = &*FI++;
236 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
237 F->replaceAllUsesWith(Remangled.getValue());
238 F->eraseFromParent();
239 }
240 }
241
Manman Ren8b4306c2013-12-02 21:29:56 +0000242 UpgradeDebugInfo(*M);
243
Manman Renb5d7ff42016-05-25 23:14:48 +0000244 UpgradeModuleFlags(*M);
245
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 {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000648 if (ParseToken(lltok::exclaim, "Expected '!' here"))
649 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000650
Craig Topper2617dcc2014-04-15 06:32:26 +0000651 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000652 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000653 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000654 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000655
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000656 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000657}
658
Devang Patel39e64d42009-07-01 19:21:12 +0000659/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000660/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000661bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000662 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000663 Lex.Lex();
664 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000665
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000666 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000667 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000668 ParseToken(lltok::equal, "expected '=' here"))
669 return true;
670
671 // Detect common error, from old metadata syntax.
672 if (Lex.getKind() == lltok::Type)
673 return TokError("unexpected type in metadata definition");
674
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000675 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000676 if (Lex.getKind() == lltok::MetadataVar) {
677 if (ParseSpecializedMDNode(Init, IsDistinct))
678 return true;
679 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
680 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000681 return true;
682
Chris Lattnerfc58af22009-12-30 04:51:58 +0000683 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000684 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000685 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000686 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000687 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000688
Chris Lattnerfc58af22009-12-30 04:51:58 +0000689 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
690 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000691 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000692 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000693 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000694 }
695
Devang Patel39e64d42009-07-01 19:21:12 +0000696 return false;
697}
698
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000699static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
700 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
701 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
702}
703
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000704/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000705/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
706/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000707/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000708///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000709/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000710/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711///
Eric Christopher536f0a92015-05-28 23:07:39 +0000712/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000713///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000714bool LLParser::parseIndirectSymbol(
715 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
716 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
717 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000718 bool IsAlias;
719 if (Lex.getKind() == lltok::kw_alias)
720 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000721 else if (Lex.getKind() == lltok::kw_ifunc)
722 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000723 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000724 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726
Rafael Espindola78527052013-10-06 15:10:43 +0000727 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
728
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000729 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000730 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000731
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000732 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000733 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000734 "symbol with local linkage must have default visibility");
735
David Blaikie2f408302015-09-11 03:22:04 +0000736 Type *Ty;
737 LocTy ExplicitTypeLoc = Lex.getLoc();
738 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000739 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000740 return true;
741
Rafael Espindola64c1e182014-06-03 02:41:57 +0000742 Constant *Aliasee;
743 LocTy AliaseeLoc = Lex.getLoc();
744 if (Lex.getKind() != lltok::kw_bitcast &&
745 Lex.getKind() != lltok::kw_getelementptr &&
746 Lex.getKind() != lltok::kw_addrspacecast &&
747 Lex.getKind() != lltok::kw_inttoptr) {
748 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000749 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000751 // The bitcast dest type is not present, it is implied by the dest type.
752 ValID ID;
753 if (ParseValID(ID))
754 return true;
755 if (ID.Kind != ValID::t_Constant)
756 return Error(AliaseeLoc, "invalid aliasee");
757 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000759
Rafael Espindola64c1e182014-06-03 02:41:57 +0000760 Type *AliaseeType = Aliasee->getType();
761 auto *PTy = dyn_cast<PointerType>(AliaseeType);
762 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000763 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000764 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000766 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000767 return Error(
768 ExplicitTypeLoc,
769 "explicit pointee type doesn't match operand's pointee type");
770
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000771 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
772 return Error(
773 ExplicitTypeLoc,
774 "explicit pointee type should be a function type");
775
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000776 GlobalValue *GVal = nullptr;
777
778 // See if the alias was forward referenced, if so, prepare to replace the
779 // forward reference.
780 if (!Name.empty()) {
781 GVal = M->getNamedValue(Name);
782 if (GVal) {
783 if (!ForwardRefVals.erase(Name))
784 return Error(NameLoc, "redefinition of global '@" + Name + "'");
785 }
786 } else {
787 auto I = ForwardRefValIDs.find(NumberedVals.size());
788 if (I != ForwardRefValIDs.end()) {
789 GVal = I->second.first;
790 ForwardRefValIDs.erase(I);
791 }
792 }
793
Chris Lattnerac161bf2009-01-02 07:01:27 +0000794 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000795 std::unique_ptr<GlobalIndirectSymbol> GA;
796 if (IsAlias)
797 GA.reset(GlobalAlias::create(Ty, AddrSpace,
798 (GlobalValue::LinkageTypes)Linkage, Name,
799 Aliasee, /*Parent*/ nullptr));
800 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000801 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
802 (GlobalValue::LinkageTypes)Linkage, Name,
803 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000804 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000805 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000806 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000807 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Rafael Espindola54fc2982015-06-17 17:53:31 +0000809 if (Name.empty())
810 NumberedVals.push_back(GA.get());
811
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000812 if (GVal) {
813 // Verify that types agree.
814 if (GVal->getType() != GA->getType())
815 return Error(
816 ExplicitTypeLoc,
817 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Chris Lattnerac161bf2009-01-02 07:01:27 +0000819 // If they agree, just RAUW the old value with the alias and remove the
820 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000821 GVal->replaceAllUsesWith(GA.get());
822 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000826 if (IsAlias)
827 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
828 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000829 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000830 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
Rafael Espindolaaa273822014-05-09 21:49:17 +0000832 // The module owns this now
833 GA.release();
834
Chris Lattnerac161bf2009-01-02 07:01:27 +0000835 return false;
836}
837
838/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000839/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000840/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000841/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000842/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000843/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000844/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845///
Eric Christopher536f0a92015-05-28 23:07:39 +0000846/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000847/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848///
849bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
850 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000851 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000852 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000853 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000854 if (!isValidVisibilityForLinkage(Visibility, Linkage))
855 return Error(NameLoc,
856 "symbol with local linkage must have default visibility");
857
Chris Lattnerac161bf2009-01-02 07:01:27 +0000858 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000859 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000860 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000862
Craig Topper2617dcc2014-04-15 06:32:26 +0000863 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000864 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000865 ParseOptionalToken(lltok::kw_externally_initialized,
866 IsExternallyInitialized,
867 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 ParseGlobalType(IsConstant) ||
869 ParseType(Ty, TyLoc))
870 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000871
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872 // If the linkage is specified and is external, then no initializer is
873 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000874 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000875 if (!HasLinkage ||
876 !GlobalValue::isValidDeclarationLinkage(
877 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000878 if (ParseGlobalValue(Ty, Init))
879 return true;
880 }
881
David Majnemer49b3d9b2015-02-16 08:41:08 +0000882 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000883 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000884
David Majnemer598bd052014-12-09 05:56:09 +0000885 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000886
887 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000888 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000889 GVal = M->getNamedValue(Name);
890 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000891 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000892 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000893 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000895 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000896 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000897 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000898 ForwardRefValIDs.erase(I);
899 }
900 }
901
David Majnemer598bd052014-12-09 05:56:09 +0000902 GlobalVariable *GV;
903 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000904 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
905 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000906 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000908 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000909 return Error(TyLoc,
910 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000911
David Majnemer598bd052014-12-09 05:56:09 +0000912 GV = cast<GlobalVariable>(GVal);
913
Chris Lattnerac161bf2009-01-02 07:01:27 +0000914 // Move the forward-reference to the correct spot in the module.
915 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
916 }
917
918 if (Name.empty())
919 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000920
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 // Set the parsed properties on the global.
922 if (Init)
923 GV->setInitializer(Init);
924 GV->setConstant(IsConstant);
925 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
926 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000927 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000928 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000929 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000930 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000931
Chris Lattnerac161bf2009-01-02 07:01:27 +0000932 // Parse attributes on the global.
933 while (Lex.getKind() == lltok::comma) {
934 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000935
Chris Lattnerac161bf2009-01-02 07:01:27 +0000936 if (Lex.getKind() == lltok::kw_section) {
937 Lex.Lex();
938 GV->setSection(Lex.getStrVal());
939 if (ParseToken(lltok::StringConstant, "expected global section string"))
940 return true;
941 } else if (Lex.getKind() == lltok::kw_align) {
942 unsigned Alignment;
943 if (ParseOptionalAlignment(Alignment)) return true;
944 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000945 } else if (Lex.getKind() == lltok::MetadataVar) {
946 if (ParseGlobalObjectMetadataAttachment(*GV))
947 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000948 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000949 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000950 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000951 return true;
952 if (C)
953 GV->setComdat(C);
954 else
955 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000956 }
957 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000958
Chris Lattnerac161bf2009-01-02 07:01:27 +0000959 return false;
960}
961
Bill Wendling63b88192013-02-06 06:52:58 +0000962/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000963/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000964bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000965 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000966 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000967 Lex.Lex();
968
David Majnemerb39e22b2014-12-09 18:33:57 +0000969 if (Lex.getKind() != lltok::AttrGrpID)
970 return TokError("expected attribute group id");
971
Bill Wendling63b88192013-02-06 06:52:58 +0000972 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000973 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000974 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000975 Lex.Lex();
976
977 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000978 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000979 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000980 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000981 ParseToken(lltok::rbrace, "expected end of attribute group"))
982 return true;
983
Bill Wendlingb32b0412013-02-08 06:32:06 +0000984 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000985 return Error(AttrGrpLoc, "attribute group has no attributes");
986
987 return false;
988}
989
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000991/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000992bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
993 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000994 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000995 bool HaveError = false;
996
997 B.clear();
998
Bill Wendling63b88192013-02-06 06:52:58 +0000999 while (true) {
1000 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001001 if (Token == lltok::kw_builtin)
1002 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001003 switch (Token) {
1004 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001005 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001006 return Error(Lex.getLoc(), "unterminated attribute group");
1007 case lltok::rbrace:
1008 // Finished.
1009 return false;
1010
Bill Wendlingb32b0412013-02-08 06:32:06 +00001011 case lltok::AttrGrpID: {
1012 // Allow a function to reference an attribute group:
1013 //
1014 // define void @foo() #1 { ... }
1015 if (inAttrGrp)
1016 HaveError |=
1017 Error(Lex.getLoc(),
1018 "cannot have an attribute group reference in an attribute group");
1019
1020 unsigned AttrGrpNum = Lex.getUIntVal();
1021 if (inAttrGrp) break;
1022
1023 // Save the reference to the attribute group. We'll fill it in later.
1024 FwdRefAttrGrps.push_back(AttrGrpNum);
1025 break;
1026 }
Bill Wendling63b88192013-02-06 06:52:58 +00001027 // Target-dependent attributes:
1028 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001029 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001030 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001031 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001032 }
1033
1034 // Target-independent attributes:
1035 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001036 // As a hack, we allow function alignment to be initially parsed as an
1037 // attribute on a function declaration/definition or added to an attribute
1038 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001039 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001040 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001041 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001042 if (ParseToken(lltok::equal, "expected '=' here") ||
1043 ParseUInt32(Alignment))
1044 return true;
1045 } else {
1046 if (ParseOptionalAlignment(Alignment))
1047 return true;
1048 }
Bill Wendling63b88192013-02-06 06:52:58 +00001049 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001050 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001051 }
1052 case lltok::kw_alignstack: {
1053 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001054 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001055 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001056 if (ParseToken(lltok::equal, "expected '=' here") ||
1057 ParseUInt32(Alignment))
1058 return true;
1059 } else {
1060 if (ParseOptionalStackAlignment(Alignment))
1061 return true;
1062 }
Bill Wendling63b88192013-02-06 06:52:58 +00001063 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001064 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001065 }
George Burgess IV278199f2016-04-12 01:05:35 +00001066 case lltok::kw_allocsize: {
1067 unsigned ElemSizeArg;
1068 Optional<unsigned> NumElemsArg;
1069 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1070 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1071 return true;
1072 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1073 continue;
1074 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001075 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1076 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1077 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1078 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1079 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001080 case lltok::kw_inaccessiblememonly:
1081 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1082 case lltok::kw_inaccessiblemem_or_argmemonly:
1083 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001084 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1085 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1086 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1087 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1088 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1089 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1090 case lltok::kw_noimplicitfloat:
1091 B.addAttribute(Attribute::NoImplicitFloat); break;
1092 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1093 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1094 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1095 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001096 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001097 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1098 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1099 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1100 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1101 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1102 case lltok::kw_returns_twice:
1103 B.addAttribute(Attribute::ReturnsTwice); break;
1104 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1105 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1106 case lltok::kw_sspstrong:
1107 B.addAttribute(Attribute::StackProtectStrong); break;
1108 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1109 case lltok::kw_sanitize_address:
1110 B.addAttribute(Attribute::SanitizeAddress); break;
1111 case lltok::kw_sanitize_thread:
1112 B.addAttribute(Attribute::SanitizeThread); break;
1113 case lltok::kw_sanitize_memory:
1114 B.addAttribute(Attribute::SanitizeMemory); break;
1115 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001116 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001117
1118 // Error handling.
1119 case lltok::kw_inreg:
1120 case lltok::kw_signext:
1121 case lltok::kw_zeroext:
1122 HaveError |=
1123 Error(Lex.getLoc(),
1124 "invalid use of attribute on a function");
1125 break;
1126 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001127 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001128 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001129 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001130 case lltok::kw_nest:
1131 case lltok::kw_noalias:
1132 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001133 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001134 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001135 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001136 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001137 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001138 HaveError |=
1139 Error(Lex.getLoc(),
1140 "invalid use of parameter-only attribute on a function");
1141 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001142 }
1143
1144 Lex.Lex();
1145 }
1146}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147
1148//===----------------------------------------------------------------------===//
1149// GlobalValue Reference/Resolution Routines.
1150//===----------------------------------------------------------------------===//
1151
Karl Schimpf77729782015-09-03 18:06:44 +00001152static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1153 const std::string &Name) {
1154 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1155 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1156 else
1157 return new GlobalVariable(*M, PTy->getElementType(), false,
1158 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1159 nullptr, GlobalVariable::NotThreadLocal,
1160 PTy->getAddressSpace());
1161}
1162
Chris Lattnerac161bf2009-01-02 07:01:27 +00001163/// GetGlobalVal - Get a value with the specified name or ID, creating a
1164/// forward reference record if needed. This can return null if the value
1165/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001166GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001168 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001169 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001171 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Chris Lattnerac161bf2009-01-02 07:01:27 +00001174 // Look this name up in the normal function symbol table.
1175 GlobalValue *Val =
1176 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001177
Chris Lattnerac161bf2009-01-02 07:01:27 +00001178 // If this is a forward reference for the value, see if we already created a
1179 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001181 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001182 if (I != ForwardRefVals.end())
1183 Val = I->second.first;
1184 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001185
Chris Lattnerac161bf2009-01-02 07:01:27 +00001186 // If we have the value in the symbol table or fwd-ref table, return it.
1187 if (Val) {
1188 if (Val->getType() == Ty) return Val;
1189 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001190 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001191 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001193
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001195 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001196 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1197 return FwdVal;
1198}
1199
Chris Lattner229907c2011-07-18 04:54:35 +00001200GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1201 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001202 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001204 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001206
Craig Topper2617dcc2014-04-15 06:32:26 +00001207 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001208
Chris Lattnerac161bf2009-01-02 07:01:27 +00001209 // If this is a forward reference for the value, see if we already created a
1210 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001211 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001212 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 if (I != ForwardRefValIDs.end())
1214 Val = I->second.first;
1215 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001216
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 // If we have the value in the symbol table or fwd-ref table, return it.
1218 if (Val) {
1219 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001220 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001221 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001222 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001223 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001224
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001226 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1228 return FwdVal;
1229}
1230
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001232// Comdat Reference/Resolution Routines.
1233//===----------------------------------------------------------------------===//
1234
1235Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1236 // Look this name up in the comdat symbol table.
1237 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1238 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1239 if (I != ComdatSymTab.end())
1240 return &I->second;
1241
1242 // Otherwise, create a new forward reference for this value and remember it.
1243 Comdat *C = M->getOrInsertComdat(Name);
1244 ForwardRefComdats[Name] = Loc;
1245 return C;
1246}
1247
David Majnemerdad0a642014-06-27 18:19:56 +00001248//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001249// Helper Routines.
1250//===----------------------------------------------------------------------===//
1251
1252/// ParseToken - If the current token has the specified kind, eat it and return
1253/// success. Otherwise, emit the specified error and return failure.
1254bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1255 if (Lex.getKind() != T)
1256 return TokError(ErrMsg);
1257 Lex.Lex();
1258 return false;
1259}
1260
Chris Lattner3822f632009-01-02 08:05:26 +00001261/// ParseStringConstant
1262/// ::= StringConstant
1263bool LLParser::ParseStringConstant(std::string &Result) {
1264 if (Lex.getKind() != lltok::StringConstant)
1265 return TokError("expected string constant");
1266 Result = Lex.getStrVal();
1267 Lex.Lex();
1268 return false;
1269}
1270
1271/// ParseUInt32
1272/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001273bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1275 return TokError("expected integer");
1276 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1277 if (Val64 != unsigned(Val64))
1278 return TokError("expected 32-bit integer (too large)");
1279 Val = Val64;
1280 Lex.Lex();
1281 return false;
1282}
1283
Hal Finkelb0407ba2014-07-18 15:51:28 +00001284/// ParseUInt64
1285/// ::= uint64
1286bool LLParser::ParseUInt64(uint64_t &Val) {
1287 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1288 return TokError("expected integer");
1289 Val = Lex.getAPSIntVal().getLimitedValue();
1290 Lex.Lex();
1291 return false;
1292}
1293
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001294/// ParseTLSModel
1295/// := 'localdynamic'
1296/// := 'initialexec'
1297/// := 'localexec'
1298bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1299 switch (Lex.getKind()) {
1300 default:
1301 return TokError("expected localdynamic, initialexec or localexec");
1302 case lltok::kw_localdynamic:
1303 TLM = GlobalVariable::LocalDynamicTLSModel;
1304 break;
1305 case lltok::kw_initialexec:
1306 TLM = GlobalVariable::InitialExecTLSModel;
1307 break;
1308 case lltok::kw_localexec:
1309 TLM = GlobalVariable::LocalExecTLSModel;
1310 break;
1311 }
1312
1313 Lex.Lex();
1314 return false;
1315}
1316
1317/// ParseOptionalThreadLocal
1318/// := /*empty*/
1319/// := 'thread_local'
1320/// := 'thread_local' '(' tlsmodel ')'
1321bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1322 TLM = GlobalVariable::NotThreadLocal;
1323 if (!EatIfPresent(lltok::kw_thread_local))
1324 return false;
1325
1326 TLM = GlobalVariable::GeneralDynamicTLSModel;
1327 if (Lex.getKind() == lltok::lparen) {
1328 Lex.Lex();
1329 return ParseTLSModel(TLM) ||
1330 ParseToken(lltok::rparen, "expected ')' after thread local model");
1331 }
1332 return false;
1333}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001334
1335/// ParseOptionalAddrSpace
1336/// := /*empty*/
1337/// := 'addrspace' '(' uint32 ')'
1338bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1339 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001340 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001341 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001342 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001343 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001344 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001345}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001346
Artur Pilipenko17376c42015-08-03 14:31:49 +00001347/// ParseStringAttribute
1348/// := StringConstant
1349/// := StringConstant '=' StringConstant
1350bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1351 std::string Attr = Lex.getStrVal();
1352 Lex.Lex();
1353 std::string Val;
1354 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1355 return true;
1356 B.addAttribute(Attr, Val);
1357 return false;
1358}
1359
Bill Wendling34c2eb22012-12-04 23:40:58 +00001360/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1361bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1362 bool HaveError = false;
1363
1364 B.clear();
1365
Eugene Zelenko1804a772016-08-25 00:45:04 +00001366 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001367 lltok::Kind Token = Lex.getKind();
1368 switch (Token) {
1369 default: // End of attributes.
1370 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001371 case lltok::StringConstant: {
1372 if (ParseStringAttribute(B))
1373 return true;
1374 continue;
1375 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001376 case lltok::kw_align: {
1377 unsigned Alignment;
1378 if (ParseOptionalAlignment(Alignment))
1379 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001380 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381 continue;
1382 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001383 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001384 case lltok::kw_dereferenceable: {
1385 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001386 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001387 return true;
1388 B.addDereferenceableAttr(Bytes);
1389 continue;
1390 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001391 case lltok::kw_dereferenceable_or_null: {
1392 uint64_t Bytes;
1393 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1394 return true;
1395 B.addDereferenceableOrNullAttr(Bytes);
1396 continue;
1397 }
Reid Klecknera534a382013-12-19 02:14:12 +00001398 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001399 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1400 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1401 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1402 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001403 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001404 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1405 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001406 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001407 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1408 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001409 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001410 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001411 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001412 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001413
Stephen Lin7577ed52013-04-20 13:16:13 +00001414 case lltok::kw_alignstack:
1415 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001416 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001417 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001418 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001419 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001420 case lltok::kw_minsize:
1421 case lltok::kw_naked:
1422 case lltok::kw_nobuiltin:
1423 case lltok::kw_noduplicate:
1424 case lltok::kw_noimplicitfloat:
1425 case lltok::kw_noinline:
1426 case lltok::kw_nonlazybind:
1427 case lltok::kw_noredzone:
1428 case lltok::kw_noreturn:
1429 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001430 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001431 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001432 case lltok::kw_returns_twice:
1433 case lltok::kw_sanitize_address:
1434 case lltok::kw_sanitize_memory:
1435 case lltok::kw_sanitize_thread:
1436 case lltok::kw_ssp:
1437 case lltok::kw_sspreq:
1438 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001439 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001440 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001441 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1442 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001443 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001444
Bill Wendling34c2eb22012-12-04 23:40:58 +00001445 Lex.Lex();
1446 }
1447}
1448
1449/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1450bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1451 bool HaveError = false;
1452
1453 B.clear();
1454
Eugene Zelenko1804a772016-08-25 00:45:04 +00001455 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001456 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001457 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001458 default: // End of attributes.
1459 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001460 case lltok::StringConstant: {
1461 if (ParseStringAttribute(B))
1462 return true;
1463 continue;
1464 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001465 case lltok::kw_dereferenceable: {
1466 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001467 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001468 return true;
1469 B.addDereferenceableAttr(Bytes);
1470 continue;
1471 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001472 case lltok::kw_dereferenceable_or_null: {
1473 uint64_t Bytes;
1474 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1475 return true;
1476 B.addDereferenceableOrNullAttr(Bytes);
1477 continue;
1478 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001479 case lltok::kw_align: {
1480 unsigned Alignment;
1481 if (ParseOptionalAlignment(Alignment))
1482 return true;
1483 B.addAlignmentAttr(Alignment);
1484 continue;
1485 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001486 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1487 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001488 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001489 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1490 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001491
Bill Wendling34c2eb22012-12-04 23:40:58 +00001492 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001493 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001494 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001495 case lltok::kw_nest:
1496 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001497 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001498 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001499 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001500 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001501 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001502 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001503
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001504 case lltok::kw_alignstack:
1505 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001506 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001507 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001508 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001509 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001510 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001511 case lltok::kw_minsize:
1512 case lltok::kw_naked:
1513 case lltok::kw_nobuiltin:
1514 case lltok::kw_noduplicate:
1515 case lltok::kw_noimplicitfloat:
1516 case lltok::kw_noinline:
1517 case lltok::kw_nonlazybind:
1518 case lltok::kw_noredzone:
1519 case lltok::kw_noreturn:
1520 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001521 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001522 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001523 case lltok::kw_returns_twice:
1524 case lltok::kw_sanitize_address:
1525 case lltok::kw_sanitize_memory:
1526 case lltok::kw_sanitize_thread:
1527 case lltok::kw_ssp:
1528 case lltok::kw_sspreq:
1529 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001530 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001531 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001532 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001533 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001534
1535 case lltok::kw_readnone:
1536 case lltok::kw_readonly:
1537 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001538 }
1539
Chris Lattnerac161bf2009-01-02 07:01:27 +00001540 Lex.Lex();
1541 }
1542}
1543
Rafael Espindolac6269912016-05-10 17:16:45 +00001544static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1545 HasLinkage = true;
1546 switch (Kind) {
1547 default:
1548 HasLinkage = false;
1549 return GlobalValue::ExternalLinkage;
1550 case lltok::kw_private:
1551 return GlobalValue::PrivateLinkage;
1552 case lltok::kw_internal:
1553 return GlobalValue::InternalLinkage;
1554 case lltok::kw_weak:
1555 return GlobalValue::WeakAnyLinkage;
1556 case lltok::kw_weak_odr:
1557 return GlobalValue::WeakODRLinkage;
1558 case lltok::kw_linkonce:
1559 return GlobalValue::LinkOnceAnyLinkage;
1560 case lltok::kw_linkonce_odr:
1561 return GlobalValue::LinkOnceODRLinkage;
1562 case lltok::kw_available_externally:
1563 return GlobalValue::AvailableExternallyLinkage;
1564 case lltok::kw_appending:
1565 return GlobalValue::AppendingLinkage;
1566 case lltok::kw_common:
1567 return GlobalValue::CommonLinkage;
1568 case lltok::kw_extern_weak:
1569 return GlobalValue::ExternalWeakLinkage;
1570 case lltok::kw_external:
1571 return GlobalValue::ExternalLinkage;
1572 }
1573}
1574
Chris Lattnerac161bf2009-01-02 07:01:27 +00001575/// ParseOptionalLinkage
1576/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001577/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578/// ::= 'internal'
1579/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001580/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001582/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001583/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001585/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001586/// ::= 'extern_weak'
1587/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001588bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1589 unsigned &Visibility,
1590 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001591 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1592 if (HasLinkage)
1593 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001594 ParseOptionalVisibility(Visibility);
1595 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001596 return false;
1597}
1598
1599/// ParseOptionalVisibility
1600/// ::= /*empty*/
1601/// ::= 'default'
1602/// ::= 'hidden'
1603/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001604///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001605void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001607 default:
1608 Res = GlobalValue::DefaultVisibility;
1609 return;
1610 case lltok::kw_default:
1611 Res = GlobalValue::DefaultVisibility;
1612 break;
1613 case lltok::kw_hidden:
1614 Res = GlobalValue::HiddenVisibility;
1615 break;
1616 case lltok::kw_protected:
1617 Res = GlobalValue::ProtectedVisibility;
1618 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001619 }
1620 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621}
1622
Nico Rieck7157bb72014-01-14 15:22:47 +00001623/// ParseOptionalDLLStorageClass
1624/// ::= /*empty*/
1625/// ::= 'dllimport'
1626/// ::= 'dllexport'
1627///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001628void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001629 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001630 default:
1631 Res = GlobalValue::DefaultStorageClass;
1632 return;
1633 case lltok::kw_dllimport:
1634 Res = GlobalValue::DLLImportStorageClass;
1635 break;
1636 case lltok::kw_dllexport:
1637 Res = GlobalValue::DLLExportStorageClass;
1638 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001639 }
1640 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001641}
1642
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643/// ParseOptionalCallingConv
1644/// ::= /*empty*/
1645/// ::= 'ccc'
1646/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001647/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001648/// ::= 'coldcc'
1649/// ::= 'x86_stdcallcc'
1650/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001651/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001652/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001653/// ::= 'arm_apcscc'
1654/// ::= 'arm_aapcscc'
1655/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001656/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001657/// ::= 'avr_intrcc'
1658/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001659/// ::= 'ptx_kernel'
1660/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001661/// ::= 'spir_func'
1662/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001663/// ::= 'x86_64_sysvcc'
1664/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001665/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001666/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001667/// ::= 'preserve_mostcc'
1668/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001669/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001670/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001671/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001672/// ::= 'hhvmcc'
1673/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001674/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001675/// ::= 'amdgpu_vs'
1676/// ::= 'amdgpu_tcs'
1677/// ::= 'amdgpu_tes'
1678/// ::= 'amdgpu_gs'
1679/// ::= 'amdgpu_ps'
1680/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001681/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001683///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001684bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 switch (Lex.getKind()) {
1686 default: CC = CallingConv::C; return false;
1687 case lltok::kw_ccc: CC = CallingConv::C; break;
1688 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1689 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1690 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1691 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001692 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001693 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001694 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001695 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1696 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1697 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001698 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001699 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1700 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001701 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1702 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001703 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1704 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001705 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001706 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1707 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001708 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001709 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001710 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1711 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001712 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001713 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001714 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001715 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1716 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001717 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001718 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1719 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1720 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1721 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001722 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001723 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001724 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001725 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001726 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001728
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729 Lex.Lex();
1730 return false;
1731}
1732
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001733/// ParseMetadataAttachment
1734/// ::= !dbg !42
1735bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1736 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1737
1738 std::string Name = Lex.getStrVal();
1739 Kind = M->getMDKindID(Name);
1740 Lex.Lex();
1741
1742 return ParseMDNode(MD);
1743}
1744
Chris Lattner5c427632009-12-30 05:31:19 +00001745/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001746/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001747bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001748 do {
1749 if (Lex.getKind() != lltok::MetadataVar)
1750 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001751
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001752 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001753 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001754 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001755 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001756
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001757 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001758 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001759 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001760
Chris Lattner596760d2009-12-29 21:25:40 +00001761 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001762 } while (EatIfPresent(lltok::comma));
1763 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001764}
1765
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001766/// ParseGlobalObjectMetadataAttachment
1767/// ::= !dbg !57
1768bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1769 unsigned MDK;
1770 MDNode *N;
1771 if (ParseMetadataAttachment(MDK, N))
1772 return true;
1773
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001774 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001775 return false;
1776}
1777
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001778/// ParseOptionalFunctionMetadata
1779/// ::= (!dbg !57)*
1780bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001781 while (Lex.getKind() == lltok::MetadataVar)
1782 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001783 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001784 return false;
1785}
1786
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787/// ParseOptionalAlignment
1788/// ::= /* empty */
1789/// ::= 'align' 4
1790bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1791 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001792 if (!EatIfPresent(lltok::kw_align))
1793 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001794 LocTy AlignLoc = Lex.getLoc();
1795 if (ParseUInt32(Alignment)) return true;
1796 if (!isPowerOf2_32(Alignment))
1797 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001798 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001799 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001800 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801}
1802
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001803/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001804/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001805/// ::= AttrKind '(' 4 ')'
1806///
1807/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1808bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1809 uint64_t &Bytes) {
1810 assert((AttrKind == lltok::kw_dereferenceable ||
1811 AttrKind == lltok::kw_dereferenceable_or_null) &&
1812 "contract!");
1813
Hal Finkelb0407ba2014-07-18 15:51:28 +00001814 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001815 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001816 return false;
1817 LocTy ParenLoc = Lex.getLoc();
1818 if (!EatIfPresent(lltok::lparen))
1819 return Error(ParenLoc, "expected '('");
1820 LocTy DerefLoc = Lex.getLoc();
1821 if (ParseUInt64(Bytes)) return true;
1822 ParenLoc = Lex.getLoc();
1823 if (!EatIfPresent(lltok::rparen))
1824 return Error(ParenLoc, "expected ')'");
1825 if (!Bytes)
1826 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1827 return false;
1828}
1829
Chris Lattnerb2f39502009-12-30 05:44:30 +00001830/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001831/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001832/// ::= ',' align 4
1833///
1834/// This returns with AteExtraComma set to true if it ate an excess comma at the
1835/// end.
1836bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1837 bool &AteExtraComma) {
1838 AteExtraComma = false;
1839 while (EatIfPresent(lltok::comma)) {
1840 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001841 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001842 AteExtraComma = true;
1843 return false;
1844 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001845
Chris Lattner95b0ff42010-04-23 00:50:50 +00001846 if (Lex.getKind() != lltok::kw_align)
1847 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001848
Chris Lattner95b0ff42010-04-23 00:50:50 +00001849 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001850 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001851
Devang Patelea8a4b92009-09-17 23:04:48 +00001852 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853}
1854
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001855/// ParseOptionalCommaAddrSpace
1856/// ::=
1857/// ::= ',' addrspace(1)
1858///
1859/// This returns with AteExtraComma set to true if it ate an excess comma at the
1860/// end.
1861bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1862 LocTy &Loc,
1863 bool &AteExtraComma) {
1864 AteExtraComma = false;
1865 while (EatIfPresent(lltok::comma)) {
1866 // Metadata at the end is an early exit.
1867 if (Lex.getKind() == lltok::MetadataVar) {
1868 AteExtraComma = true;
1869 return false;
1870 }
1871
1872 Loc = Lex.getLoc();
1873 if (Lex.getKind() != lltok::kw_addrspace)
1874 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1875
1876 if (ParseOptionalAddrSpace(AddrSpace))
1877 return true;
1878 }
1879
1880 return false;
1881}
1882
George Burgess IV278199f2016-04-12 01:05:35 +00001883bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1884 Optional<unsigned> &HowManyArg) {
1885 Lex.Lex();
1886
1887 auto StartParen = Lex.getLoc();
1888 if (!EatIfPresent(lltok::lparen))
1889 return Error(StartParen, "expected '('");
1890
1891 if (ParseUInt32(BaseSizeArg))
1892 return true;
1893
1894 if (EatIfPresent(lltok::comma)) {
1895 auto HowManyAt = Lex.getLoc();
1896 unsigned HowMany;
1897 if (ParseUInt32(HowMany))
1898 return true;
1899 if (HowMany == BaseSizeArg)
1900 return Error(HowManyAt,
1901 "'allocsize' indices can't refer to the same parameter");
1902 HowManyArg = HowMany;
1903 } else
1904 HowManyArg = None;
1905
1906 auto EndParen = Lex.getLoc();
1907 if (!EatIfPresent(lltok::rparen))
1908 return Error(EndParen, "expected ')'");
1909 return false;
1910}
1911
Eli Friedmanfee02c62011-07-25 23:16:38 +00001912/// ParseScopeAndOrdering
1913/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1914/// else: ::=
1915///
1916/// This sets Scope and Ordering to the parsed values.
1917bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1918 AtomicOrdering &Ordering) {
1919 if (!isAtomic)
1920 return false;
1921
1922 Scope = CrossThread;
1923 if (EatIfPresent(lltok::kw_singlethread))
1924 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001925
1926 return ParseOrdering(Ordering);
1927}
1928
1929/// ParseOrdering
1930/// ::= AtomicOrdering
1931///
1932/// This sets Ordering to the parsed value.
1933bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001934 switch (Lex.getKind()) {
1935 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001936 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1937 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1938 // Not specified yet:
1939 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1940 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1941 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1942 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1943 case lltok::kw_seq_cst:
1944 Ordering = AtomicOrdering::SequentiallyConsistent;
1945 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001946 }
1947 Lex.Lex();
1948 return false;
1949}
1950
Charles Davisbe5557e2010-02-12 00:31:15 +00001951/// ParseOptionalStackAlignment
1952/// ::= /* empty */
1953/// ::= 'alignstack' '(' 4 ')'
1954bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1955 Alignment = 0;
1956 if (!EatIfPresent(lltok::kw_alignstack))
1957 return false;
1958 LocTy ParenLoc = Lex.getLoc();
1959 if (!EatIfPresent(lltok::lparen))
1960 return Error(ParenLoc, "expected '('");
1961 LocTy AlignLoc = Lex.getLoc();
1962 if (ParseUInt32(Alignment)) return true;
1963 ParenLoc = Lex.getLoc();
1964 if (!EatIfPresent(lltok::rparen))
1965 return Error(ParenLoc, "expected ')'");
1966 if (!isPowerOf2_32(Alignment))
1967 return Error(AlignLoc, "stack alignment is not a power of two");
1968 return false;
1969}
Devang Patelea8a4b92009-09-17 23:04:48 +00001970
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001971/// ParseIndexList - This parses the index list for an insert/extractvalue
1972/// instruction. This sets AteExtraComma in the case where we eat an extra
1973/// comma at the end of the line and find that it is followed by metadata.
1974/// Clients that don't allow metadata can call the version of this function that
1975/// only takes one argument.
1976///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977/// ParseIndexList
1978/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001979///
1980bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1981 bool &AteExtraComma) {
1982 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001983
Chris Lattnerac161bf2009-01-02 07:01:27 +00001984 if (Lex.getKind() != lltok::comma)
1985 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Chris Lattner3822f632009-01-02 08:05:26 +00001987 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001988 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001989 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001990 AteExtraComma = true;
1991 return false;
1992 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001993 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001994 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995 Indices.push_back(Idx);
1996 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001997
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 return false;
1999}
2000
2001//===----------------------------------------------------------------------===//
2002// Type Parsing.
2003//===----------------------------------------------------------------------===//
2004
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002006bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 switch (Lex.getKind()) {
2009 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002010 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002012 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002013 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002014 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002015 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002016 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 // Type ::= StructType
2018 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002019 return true;
2020 break;
2021 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023 Lex.Lex(); // eat the lsquare.
2024 if (ParseArrayVectorType(Result, false))
2025 return true;
2026 break;
2027 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002029 Lex.Lex();
2030 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002032 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002034 } else if (ParseArrayVectorType(Result, true))
2035 return true;
2036 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 case lltok::LocalVar: {
2038 // Type ::= %foo
2039 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002040
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002041 // If the type hasn't been defined yet, create a forward definition and
2042 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002043 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002044 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048 Lex.Lex();
2049 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002050 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002051
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052 case lltok::LocalVarID: {
2053 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002054 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002055
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056 // If the type hasn't been defined yet, create a forward definition and
2057 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002058 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002059 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002062 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002063 Lex.Lex();
2064 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 }
2066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002067
2068 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002069 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002070 switch (Lex.getKind()) {
2071 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002072 default:
2073 if (!AllowVoid && Result->isVoidTy())
2074 return Error(TypeLoc, "void type only allowed for function results");
2075 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002079 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 if (Result->isVoidTy())
2082 return TokError("pointers to void are invalid - use i8* instead");
2083 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002084 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002085 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002086 Lex.Lex();
2087 break;
2088
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002089 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002090 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002093 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002094 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002095 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002096 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002097 unsigned AddrSpace;
2098 if (ParseOptionalAddrSpace(AddrSpace) ||
2099 ParseToken(lltok::star, "expected '*' in address space"))
2100 return true;
2101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002102 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002103 break;
2104 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002105
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2107 case lltok::lparen:
2108 if (ParseFunctionType(Result))
2109 return true;
2110 break;
2111 }
2112 }
2113}
2114
2115/// ParseParameterList
2116/// ::= '(' ')'
2117/// ::= '(' Arg (',' Arg)* ')'
2118/// Arg
2119/// ::= Type OptionalAttributes Value OptionalAttributes
2120bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002121 PerFunctionState &PFS, bool IsMustTailCall,
2122 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 if (ParseToken(lltok::lparen, "expected '(' in call"))
2124 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002125
Reid Kleckner211b1f32017-04-10 20:34:19 +00002126 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 while (Lex.getKind() != lltok::rparen) {
2128 // If this isn't the first argument, we need a comma.
2129 if (!ArgList.empty() &&
2130 ParseToken(lltok::comma, "expected ',' in argument list"))
2131 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002132
Reid Kleckner83498642014-08-26 00:33:28 +00002133 // Parse an ellipsis if this is a musttail call in a variadic function.
2134 if (Lex.getKind() == lltok::dotdotdot) {
2135 const char *Msg = "unexpected ellipsis in argument list for ";
2136 if (!IsMustTailCall)
2137 return TokError(Twine(Msg) + "non-musttail call");
2138 if (!InVarArgsFunc)
2139 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2140 Lex.Lex(); // Lex the '...', it is purely for readability.
2141 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2142 }
2143
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 // Parse the argument.
2145 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002146 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002147 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002149 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002150 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002151
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002152 if (ArgTy->isMetadataTy()) {
2153 if (ParseMetadataAsValue(V, PFS))
2154 return true;
2155 } else {
2156 // Otherwise, handle normal operands.
2157 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2158 return true;
2159 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002160 ArgList.push_back(ParamInfo(
Reid Kleckner211b1f32017-04-10 20:34:19 +00002161 ArgLoc, V, AttributeList::get(V->getContext(), AttrIndex++, ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 }
2163
Reid Kleckner83498642014-08-26 00:33:28 +00002164 if (IsMustTailCall && InVarArgsFunc)
2165 return TokError("expected '...' at end of argument list for musttail call "
2166 "in varargs function");
2167
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 Lex.Lex(); // Lex the ')'.
2169 return false;
2170}
2171
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002172/// ParseOptionalOperandBundles
2173/// ::= /*empty*/
2174/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2175///
2176/// OperandBundle
2177/// ::= bundle-tag '(' ')'
2178/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2179///
2180/// bundle-tag ::= String Constant
2181bool LLParser::ParseOptionalOperandBundles(
2182 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2183 LocTy BeginLoc = Lex.getLoc();
2184 if (!EatIfPresent(lltok::lsquare))
2185 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002186
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002187 while (Lex.getKind() != lltok::rsquare) {
2188 // If this isn't the first operand bundle, we need a comma.
2189 if (!BundleList.empty() &&
2190 ParseToken(lltok::comma, "expected ',' in input list"))
2191 return true;
2192
2193 std::string Tag;
2194 if (ParseStringConstant(Tag))
2195 return true;
2196
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002197 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2198 return true;
2199
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002200 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002201 while (Lex.getKind() != lltok::rparen) {
2202 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002203 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002204 ParseToken(lltok::comma, "expected ',' in input list"))
2205 return true;
2206
2207 Type *Ty = nullptr;
2208 Value *Input = nullptr;
2209 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2210 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002211 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002212 }
2213
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002214 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2215
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002216 Lex.Lex(); // Lex the ')'.
2217 }
2218
2219 if (BundleList.empty())
2220 return Error(BeginLoc, "operand bundle set must not be empty");
2221
2222 Lex.Lex(); // Lex the ']'.
2223 return false;
2224}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225
Chris Lattner2ed06b42009-01-05 18:34:07 +00002226/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002227/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228/// ::= '(' ArgTypeListI ')'
2229/// ArgTypeListI
2230/// ::= /*empty*/
2231/// ::= '...'
2232/// ::= ArgTypeList ',' '...'
2233/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002234///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002235bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2236 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 isVarArg = false;
2238 assert(Lex.getKind() == lltok::lparen);
2239 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002240
Chris Lattnerac161bf2009-01-02 07:01:27 +00002241 if (Lex.getKind() == lltok::rparen) {
2242 // empty
2243 } else if (Lex.getKind() == lltok::dotdotdot) {
2244 isVarArg = true;
2245 Lex.Lex();
2246 } else {
2247 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002248 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002249 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002251
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002253 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254
Chris Lattnerfdd87902009-10-05 05:54:46 +00002255 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002256 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002257
Chris Lattnerdef19492011-06-17 06:36:20 +00002258 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 Name = Lex.getStrVal();
2260 Lex.Lex();
2261 }
Chris Lattner3822f632009-01-02 08:05:26 +00002262
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002263 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002264 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265
Reid Kleckner211b1f32017-04-10 20:34:19 +00002266 unsigned AttrIndex = 1;
2267 ArgList.emplace_back(TypeLoc, ArgTy, AttributeList::get(ArgTy->getContext(),
2268 AttrIndex++, Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002269 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270
Chris Lattner3822f632009-01-02 08:05:26 +00002271 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002273 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 break;
2276 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277
Chris Lattnerac161bf2009-01-02 07:01:27 +00002278 // Otherwise must be an argument type.
2279 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002280 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002281
Chris Lattnerfdd87902009-10-05 05:54:46 +00002282 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002283 return Error(TypeLoc, "argument can not have void type");
2284
Chris Lattnerdef19492011-06-17 06:36:20 +00002285 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 Name = Lex.getStrVal();
2287 Lex.Lex();
2288 } else {
2289 Name = "";
2290 }
Chris Lattner3822f632009-01-02 08:05:26 +00002291
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002292 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002293 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002294
Reid Kleckner211b1f32017-04-10 20:34:19 +00002295 ArgList.emplace_back(
2296 TypeLoc, ArgTy,
2297 AttributeList::get(ArgTy->getContext(), AttrIndex++, Attrs),
2298 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 }
2300 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002301
Chris Lattner3822f632009-01-02 08:05:26 +00002302 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305/// ParseFunctionType
2306/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002307bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 assert(Lex.getKind() == lltok::lparen);
2309
Chris Lattnerce473c72009-01-05 08:04:33 +00002310 if (!FunctionType::isValidReturnType(Result))
2311 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002313 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002315 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002317
Chris Lattnerac161bf2009-01-02 07:01:27 +00002318 // Reject names on the arguments lists.
2319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2320 if (!ArgList[i].Name.empty())
2321 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Kleckner211b1f32017-04-10 20:34:19 +00002322 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002323 return Error(ArgList[i].Loc,
2324 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002326
Jay Foadb804a2b2011-07-12 14:06:48 +00002327 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002329 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002330
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002331 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332 return false;
2333}
2334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2336/// other structs.
2337bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2338 SmallVector<Type*, 8> Elts;
2339 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 Result = StructType::get(Context, Elts, Packed);
2342 return false;
2343}
2344
2345/// ParseStructDefinition - Parse a struct in a 'type' definition.
2346bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2347 std::pair<Type*, LocTy> &Entry,
2348 Type *&ResultTy) {
2349 // If the type was already defined, diagnose the redefinition.
2350 if (Entry.first && !Entry.second.isValid())
2351 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002353 // If we have opaque, just return without filling in the definition for the
2354 // struct. This counts as a definition as far as the .ll file goes.
2355 if (EatIfPresent(lltok::kw_opaque)) {
2356 // This type is being defined, so clear the location to indicate this.
2357 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002358
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002359 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002360 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002361 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002362 ResultTy = Entry.first;
2363 return false;
2364 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002365
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002366 // If the type starts with '<', then it is either a packed struct or a vector.
2367 bool isPacked = EatIfPresent(lltok::less);
2368
2369 // If we don't have a struct, then we have a random type alias, which we
2370 // accept for compatibility with old files. These types are not allowed to be
2371 // forward referenced and not allowed to be recursive.
2372 if (Lex.getKind() != lltok::lbrace) {
2373 if (Entry.first)
2374 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002375
Craig Topper2617dcc2014-04-15 06:32:26 +00002376 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002377 if (isPacked)
2378 return ParseArrayVectorType(ResultTy, true);
2379 return ParseType(ResultTy);
2380 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002382 // This type is being defined, so clear the location to indicate this.
2383 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002386 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002387 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002388
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002389 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002390
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002391 SmallVector<Type*, 8> Body;
2392 if (ParseStructBody(Body) ||
2393 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2394 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 STy->setBody(Body, isPacked);
2397 ResultTy = STy;
2398 return false;
2399}
2400
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002402/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002404/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406/// ::= '<' '{' Type (',' Type)* '}' '>'
2407bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 assert(Lex.getKind() == lltok::lbrace);
2409 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002411 // Handle the empty struct.
2412 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414
Chris Lattnerf880ca22009-03-09 04:49:14 +00002415 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002416 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002417 if (ParseType(Ty)) return true;
2418 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002420 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002421 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002422
Chris Lattner3822f632009-01-02 08:05:26 +00002423 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002424 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002425 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002426
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002427 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002428 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002429
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002432
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002433 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434}
2435
2436/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2437/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002438/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002439/// ::= '[' APSINTVAL 'x' Types ']'
2440/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002441bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002442 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2443 Lex.getAPSIntVal().getBitWidth() > 64)
2444 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002445
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 LocTy SizeLoc = Lex.getLoc();
2447 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002448 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002449
Chris Lattner3822f632009-01-02 08:05:26 +00002450 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2451 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452
2453 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002454 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002455 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002456
Chris Lattner3822f632009-01-02 08:05:26 +00002457 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2458 "expected end of sequential type"))
2459 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002462 if (Size == 0)
2463 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 if ((unsigned)Size != Size)
2465 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002466 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002467 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002468 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002470 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002471 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002472 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 }
2474 return false;
2475}
2476
2477//===----------------------------------------------------------------------===//
2478// Function Semantic Analysis.
2479//===----------------------------------------------------------------------===//
2480
Chris Lattner3432c622009-10-28 03:39:23 +00002481LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2482 int functionNumber)
2483 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484
2485 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002486 for (Argument &A : F.args())
2487 if (!A.hasName())
2488 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489}
2490
2491LLParser::PerFunctionState::~PerFunctionState() {
2492 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002493
David Blaikie9ebdc692015-09-21 21:07:50 +00002494 for (const auto &P : ForwardRefVals) {
2495 if (isa<BasicBlock>(P.second.first))
2496 continue;
2497 P.second.first->replaceAllUsesWith(
2498 UndefValue::get(P.second.first->getType()));
2499 delete P.second.first;
2500 }
2501
2502 for (const auto &P : ForwardRefValIDs) {
2503 if (isa<BasicBlock>(P.second.first))
2504 continue;
2505 P.second.first->replaceAllUsesWith(
2506 UndefValue::get(P.second.first->getType()));
2507 delete P.second.first;
2508 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002509}
2510
Chris Lattner3432c622009-10-28 03:39:23 +00002511bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 if (!ForwardRefVals.empty())
2513 return P.Error(ForwardRefVals.begin()->second.second,
2514 "use of undefined value '%" + ForwardRefVals.begin()->first +
2515 "'");
2516 if (!ForwardRefValIDs.empty())
2517 return P.Error(ForwardRefValIDs.begin()->second.second,
2518 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002519 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 return false;
2521}
2522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523/// GetVal - Get a value with the specified name or ID, creating a
2524/// forward reference record if needed. This can return null if the value
2525/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002526Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002527 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002529 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 // If this is a forward reference for the value, see if we already created a
2532 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002533 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002534 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002535 if (I != ForwardRefVals.end())
2536 Val = I->second.first;
2537 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 // If we have the value in the symbol table or fwd-ref table, return it.
2540 if (Val) {
2541 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002542 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543 P.Error(Loc, "'%" + Name + "' is not a basic block");
2544 else
2545 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002546 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002547 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002549
Chris Lattnerac161bf2009-01-02 07:01:27 +00002550 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002551 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002553 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 // Otherwise, create a new forward reference for this value and remember it.
2557 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002558 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002559 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002560 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002561 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2565 return FwdVal;
2566}
2567
David Majnemer8a1c45d2015-12-12 05:38:55 +00002568Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002570 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002571
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 // If this is a forward reference for the value, see if we already created a
2573 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002574 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002575 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 if (I != ForwardRefValIDs.end())
2577 Val = I->second.first;
2578 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002579
Chris Lattnerac161bf2009-01-02 07:01:27 +00002580 // If we have the value in the symbol table or fwd-ref table, return it.
2581 if (Val) {
2582 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002583 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002584 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002585 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002586 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002587 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002588 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002589 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002590
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002591 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002593 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002594 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002595
Chris Lattnerac161bf2009-01-02 07:01:27 +00002596 // Otherwise, create a new forward reference for this value and remember it.
2597 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002598 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002599 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002600 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002601 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002602 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002603
Chris Lattnerac161bf2009-01-02 07:01:27 +00002604 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2605 return FwdVal;
2606}
2607
2608/// SetInstName - After an instruction is parsed and inserted into its
2609/// basic block, this installs its name.
2610bool LLParser::PerFunctionState::SetInstName(int NameID,
2611 const std::string &NameStr,
2612 LocTy NameLoc, Instruction *Inst) {
2613 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002614 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002615 if (NameID != -1 || !NameStr.empty())
2616 return P.Error(NameLoc, "instructions returning void cannot have a name");
2617 return false;
2618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002619
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 // If this was a numbered instruction, verify that the instruction is the
2621 // expected value and resolve any forward references.
2622 if (NameStr.empty()) {
2623 // If neither a name nor an ID was specified, just use the next ID.
2624 if (NameID == -1)
2625 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 if (unsigned(NameID) != NumberedVals.size())
2628 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002629 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002630
David Blaikie9ebdc692015-09-21 21:07:50 +00002631 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002633 Value *Sentinel = FI->second.first;
2634 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002635 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002636 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002637
2638 Sentinel->replaceAllUsesWith(Inst);
2639 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640 ForwardRefValIDs.erase(FI);
2641 }
2642
2643 NumberedVals.push_back(Inst);
2644 return false;
2645 }
2646
2647 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002648 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002650 Value *Sentinel = FI->second.first;
2651 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002653 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002654
2655 Sentinel->replaceAllUsesWith(Inst);
2656 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 ForwardRefVals.erase(FI);
2658 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002659
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660 // Set the name on the instruction.
2661 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002662
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002663 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002664 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 NameStr + "'");
2666 return false;
2667}
2668
2669/// GetBB - Get a basic block with the specified name or ID, creating a
2670/// forward reference record if needed.
2671BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2672 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002673 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2674 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675}
2676
2677BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002678 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2679 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680}
2681
2682/// DefineBB - Define the specified basic block, which is either named or
2683/// unnamed. If there is an error, this returns null otherwise it returns
2684/// the block being defined.
2685BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2686 LocTy Loc) {
2687 BasicBlock *BB;
2688 if (Name.empty())
2689 BB = GetBB(NumberedVals.size(), Loc);
2690 else
2691 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002692 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 // Move the block to the end of the function. Forward ref'd blocks are
2695 // inserted wherever they happen to be referenced.
2696 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002697
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 // Remove the block from forward ref sets.
2699 if (Name.empty()) {
2700 ForwardRefValIDs.erase(NumberedVals.size());
2701 NumberedVals.push_back(BB);
2702 } else {
2703 // BB forward references are already in the function symbol table.
2704 ForwardRefVals.erase(Name);
2705 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002706
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 return BB;
2708}
2709
2710//===----------------------------------------------------------------------===//
2711// Constants.
2712//===----------------------------------------------------------------------===//
2713
2714/// ParseValID - Parse an abstract value that doesn't necessarily have a
2715/// type implied. For example, if we parse "4" we don't know what integer type
2716/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002717/// sanity. PFS is used to convert function-local operands of metadata (since
2718/// metadata operands are not just parsed here but also converted to values).
2719/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002720bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002721 ID.Loc = Lex.getLoc();
2722 switch (Lex.getKind()) {
2723 default: return TokError("expected value token");
2724 case lltok::GlobalID: // @42
2725 ID.UIntVal = Lex.getUIntVal();
2726 ID.Kind = ValID::t_GlobalID;
2727 break;
2728 case lltok::GlobalVar: // @foo
2729 ID.StrVal = Lex.getStrVal();
2730 ID.Kind = ValID::t_GlobalName;
2731 break;
2732 case lltok::LocalVarID: // %42
2733 ID.UIntVal = Lex.getUIntVal();
2734 ID.Kind = ValID::t_LocalID;
2735 break;
2736 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002737 ID.StrVal = Lex.getStrVal();
2738 ID.Kind = ValID::t_LocalName;
2739 break;
2740 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 ID.Kind = ValID::t_APSInt;
2743 break;
2744 case lltok::APFloat:
2745 ID.APFloatVal = Lex.getAPFloatVal();
2746 ID.Kind = ValID::t_APFloat;
2747 break;
2748 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002749 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002750 ID.Kind = ValID::t_Constant;
2751 break;
2752 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002753 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002754 ID.Kind = ValID::t_Constant;
2755 break;
2756 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2757 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2758 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002759 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002760
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 case lltok::lbrace: {
2762 // ValID ::= '{' ConstVector '}'
2763 Lex.Lex();
2764 SmallVector<Constant*, 16> Elts;
2765 if (ParseGlobalValueVector(Elts) ||
2766 ParseToken(lltok::rbrace, "expected end of struct constant"))
2767 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002768
David Blaikieadbda4b2015-08-03 20:08:41 +00002769 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002770 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002771 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2772 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002773 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002774 return false;
2775 }
2776 case lltok::less: {
2777 // ValID ::= '<' ConstVector '>' --> Vector.
2778 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2779 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002780 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 SmallVector<Constant*, 16> Elts;
2783 LocTy FirstEltLoc = Lex.getLoc();
2784 if (ParseGlobalValueVector(Elts) ||
2785 (isPackedStruct &&
2786 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2787 ParseToken(lltok::greater, "expected end of constant"))
2788 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002789
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002791 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2792 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2793 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002794 ID.UIntVal = Elts.size();
2795 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 return false;
2797 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002798
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 if (Elts.empty())
2800 return Error(ID.Loc, "constant vector must not be empty");
2801
Duncan Sands9dff9be2010-02-15 16:12:20 +00002802 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002803 !Elts[0]->getType()->isFloatingPointTy() &&
2804 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002806 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 // Verify that all the vector elements have the same type.
2809 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2810 if (Elts[i]->getType() != Elts[0]->getType())
2811 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002812 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002813 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002814
Chris Lattner69229312011-02-15 00:14:00 +00002815 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002816 ID.Kind = ValID::t_Constant;
2817 return false;
2818 }
2819 case lltok::lsquare: { // Array Constant
2820 Lex.Lex();
2821 SmallVector<Constant*, 16> Elts;
2822 LocTy FirstEltLoc = Lex.getLoc();
2823 if (ParseGlobalValueVector(Elts) ||
2824 ParseToken(lltok::rsquare, "expected end of array constant"))
2825 return true;
2826
2827 // Handle empty element.
2828 if (Elts.empty()) {
2829 // Use undef instead of an array because it's inconvenient to determine
2830 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002831 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 return false;
2833 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002836 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002837 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002838
Owen Anderson4056ca92009-07-29 22:17:13 +00002839 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002842 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 if (Elts[i]->getType() != Elts[0]->getType())
2844 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002845 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002846 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002848
Jay Foad83be3612011-06-22 09:24:39 +00002849 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002850 ID.Kind = ValID::t_Constant;
2851 return false;
2852 }
2853 case lltok::kw_c: // c "foo"
2854 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002855 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2856 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2858 ID.Kind = ValID::t_Constant;
2859 return false;
2860
2861 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002862 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2863 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002864 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 Lex.Lex();
2866 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002867 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002868 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002869 ParseStringConstant(ID.StrVal) ||
2870 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 ParseToken(lltok::StringConstant, "expected constraint string"))
2872 return true;
2873 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002874 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002875 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 ID.Kind = ValID::t_InlineAsm;
2877 return false;
2878 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002879
Chris Lattner3432c622009-10-28 03:39:23 +00002880 case lltok::kw_blockaddress: {
2881 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2882 Lex.Lex();
2883
2884 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002885
Chris Lattner3432c622009-10-28 03:39:23 +00002886 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2887 ParseValID(Fn) ||
2888 ParseToken(lltok::comma, "expected comma in block address expression")||
2889 ParseValID(Label) ||
2890 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2891 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002892
Chris Lattner3432c622009-10-28 03:39:23 +00002893 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2894 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002895 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002896 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002897
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002898 // Try to find the function (but skip it if it's forward-referenced).
2899 GlobalValue *GV = nullptr;
2900 if (Fn.Kind == ValID::t_GlobalID) {
2901 if (Fn.UIntVal < NumberedVals.size())
2902 GV = NumberedVals[Fn.UIntVal];
2903 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2904 GV = M->getNamedValue(Fn.StrVal);
2905 }
2906 Function *F = nullptr;
2907 if (GV) {
2908 // Confirm that it's actually a function with a definition.
2909 if (!isa<Function>(GV))
2910 return Error(Fn.Loc, "expected function name in blockaddress");
2911 F = cast<Function>(GV);
2912 if (F->isDeclaration())
2913 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2914 }
2915
2916 if (!F) {
2917 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002918 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002919 ForwardRefBlockAddresses.insert(std::make_pair(
2920 std::move(Fn),
2921 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002922 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2923 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002924 if (!FwdRef)
2925 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2926 GlobalValue::InternalLinkage, nullptr, "");
2927 ID.ConstantVal = FwdRef;
2928 ID.Kind = ValID::t_Constant;
2929 return false;
2930 }
2931
2932 // We found the function; now find the basic block. Don't use PFS, since we
2933 // might be inside a constant expression.
2934 BasicBlock *BB;
2935 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2936 if (Label.Kind == ValID::t_LocalID)
2937 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2938 else
2939 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2940 if (!BB)
2941 return Error(Label.Loc, "referenced value is not a basic block");
2942 } else {
2943 if (Label.Kind == ValID::t_LocalID)
2944 return Error(Label.Loc, "cannot take address of numeric label after "
2945 "the function is defined");
2946 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002947 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002948 if (!BB)
2949 return Error(Label.Loc, "referenced value is not a basic block");
2950 }
2951
2952 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002953 ID.Kind = ValID::t_Constant;
2954 return false;
2955 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002956
Chris Lattnerac161bf2009-01-02 07:01:27 +00002957 case lltok::kw_trunc:
2958 case lltok::kw_zext:
2959 case lltok::kw_sext:
2960 case lltok::kw_fptrunc:
2961 case lltok::kw_fpext:
2962 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002963 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002964 case lltok::kw_uitofp:
2965 case lltok::kw_sitofp:
2966 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002967 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002968 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002969 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002971 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002972 Constant *SrcVal;
2973 Lex.Lex();
2974 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2975 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002976 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002977 ParseType(DestTy) ||
2978 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2979 return true;
2980 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2981 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002982 getTypeString(SrcVal->getType()) + "' to '" +
2983 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002984 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002985 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 ID.Kind = ValID::t_Constant;
2987 return false;
2988 }
2989 case lltok::kw_extractvalue: {
2990 Lex.Lex();
2991 Constant *Val;
2992 SmallVector<unsigned, 4> Indices;
2993 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2994 ParseGlobalTypeAndValue(Val) ||
2995 ParseIndexList(Indices) ||
2996 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2997 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002998
Chris Lattner392be582010-02-12 20:49:41 +00002999 if (!Val->getType()->isAggregateType())
3000 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003001 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003002 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003003 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004 ID.Kind = ValID::t_Constant;
3005 return false;
3006 }
3007 case lltok::kw_insertvalue: {
3008 Lex.Lex();
3009 Constant *Val0, *Val1;
3010 SmallVector<unsigned, 4> Indices;
3011 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3012 ParseGlobalTypeAndValue(Val0) ||
3013 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3014 ParseGlobalTypeAndValue(Val1) ||
3015 ParseIndexList(Indices) ||
3016 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3017 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003018 if (!Val0->getType()->isAggregateType())
3019 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003020 Type *IndexedType =
3021 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3022 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003024 if (IndexedType != Val1->getType())
3025 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3026 getTypeString(Val1->getType()) +
3027 "' instead of '" + getTypeString(IndexedType) +
3028 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003029 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 ID.Kind = ValID::t_Constant;
3031 return false;
3032 }
3033 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003034 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 unsigned PredVal, Opc = Lex.getUIntVal();
3036 Constant *Val0, *Val1;
3037 Lex.Lex();
3038 if (ParseCmpPredicate(PredVal, Opc) ||
3039 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3040 ParseGlobalTypeAndValue(Val0) ||
3041 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3042 ParseGlobalTypeAndValue(Val1) ||
3043 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3044 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003045
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 if (Val0->getType() != Val1->getType())
3047 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003048
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003050
Chris Lattnerac161bf2009-01-02 07:01:27 +00003051 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003052 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003054 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003055 } else {
3056 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003057 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003058 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003060 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003061 }
3062 ID.Kind = ValID::t_Constant;
3063 return false;
3064 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003065
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 // Binary Operators.
3067 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003068 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003069 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003070 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003071 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003072 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 case lltok::kw_udiv:
3074 case lltok::kw_sdiv:
3075 case lltok::kw_fdiv:
3076 case lltok::kw_urem:
3077 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003078 case lltok::kw_frem:
3079 case lltok::kw_shl:
3080 case lltok::kw_lshr:
3081 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003082 bool NUW = false;
3083 bool NSW = false;
3084 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003085 unsigned Opc = Lex.getUIntVal();
3086 Constant *Val0, *Val1;
3087 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003088 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003089 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3090 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003091 if (EatIfPresent(lltok::kw_nuw))
3092 NUW = true;
3093 if (EatIfPresent(lltok::kw_nsw)) {
3094 NSW = true;
3095 if (EatIfPresent(lltok::kw_nuw))
3096 NUW = true;
3097 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003098 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3099 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003100 if (EatIfPresent(lltok::kw_exact))
3101 Exact = true;
3102 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003103 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3104 ParseGlobalTypeAndValue(Val0) ||
3105 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3106 ParseGlobalTypeAndValue(Val1) ||
3107 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3108 return true;
3109 if (Val0->getType() != Val1->getType())
3110 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003111 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003112 if (NUW)
3113 return Error(ModifierLoc, "nuw only applies to integer operations");
3114 if (NSW)
3115 return Error(ModifierLoc, "nsw only applies to integer operations");
3116 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003117 // Check that the type is valid for the operator.
3118 switch (Opc) {
3119 case Instruction::Add:
3120 case Instruction::Sub:
3121 case Instruction::Mul:
3122 case Instruction::UDiv:
3123 case Instruction::SDiv:
3124 case Instruction::URem:
3125 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003126 case Instruction::Shl:
3127 case Instruction::AShr:
3128 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003129 if (!Val0->getType()->isIntOrIntVectorTy())
3130 return Error(ID.Loc, "constexpr requires integer operands");
3131 break;
3132 case Instruction::FAdd:
3133 case Instruction::FSub:
3134 case Instruction::FMul:
3135 case Instruction::FDiv:
3136 case Instruction::FRem:
3137 if (!Val0->getType()->isFPOrFPVectorTy())
3138 return Error(ID.Loc, "constexpr requires fp operands");
3139 break;
3140 default: llvm_unreachable("Unknown binary operator!");
3141 }
Dan Gohman1b849082009-09-07 23:54:19 +00003142 unsigned Flags = 0;
3143 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3144 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003145 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003146 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003147 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003148 ID.Kind = ValID::t_Constant;
3149 return false;
3150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003151
Chris Lattnerac161bf2009-01-02 07:01:27 +00003152 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003153 case lltok::kw_and:
3154 case lltok::kw_or:
3155 case lltok::kw_xor: {
3156 unsigned Opc = Lex.getUIntVal();
3157 Constant *Val0, *Val1;
3158 Lex.Lex();
3159 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3160 ParseGlobalTypeAndValue(Val0) ||
3161 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3162 ParseGlobalTypeAndValue(Val1) ||
3163 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3164 return true;
3165 if (Val0->getType() != Val1->getType())
3166 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003167 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003168 return Error(ID.Loc,
3169 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003170 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003171 ID.Kind = ValID::t_Constant;
3172 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003173 }
3174
Chris Lattnerac161bf2009-01-02 07:01:27 +00003175 case lltok::kw_getelementptr:
3176 case lltok::kw_shufflevector:
3177 case lltok::kw_insertelement:
3178 case lltok::kw_extractelement:
3179 case lltok::kw_select: {
3180 unsigned Opc = Lex.getUIntVal();
3181 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003182 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003183 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003184 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003185
Dan Gohman1639c392009-07-27 21:53:46 +00003186 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003187 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003188
3189 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3190 return true;
3191
3192 LocTy ExplicitTypeLoc = Lex.getLoc();
3193 if (Opc == Instruction::GetElementPtr) {
3194 if (ParseType(Ty) ||
3195 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3196 return true;
3197 }
3198
Peter Collingbourned93620b2016-11-10 22:34:55 +00003199 Optional<unsigned> InRangeOp;
3200 if (ParseGlobalValueVector(
3201 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003202 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3203 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003204
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003206 if (Elts.size() == 0 ||
3207 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003208 return Error(ID.Loc, "base of getelementptr must be a pointer");
3209
3210 Type *BaseType = Elts[0]->getType();
3211 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003212 if (Ty != BasePointerType->getElementType())
3213 return Error(
3214 ExplicitTypeLoc,
3215 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003217 unsigned GEPWidth =
3218 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3219
Jay Foaded8db7d2011-07-21 14:31:17 +00003220 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003221 for (Constant *Val : Indices) {
3222 Type *ValTy = Val->getType();
3223 if (!ValTy->getScalarType()->isIntegerTy())
3224 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003225 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003226 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003227 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003228 return Error(
3229 ID.Loc,
3230 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003231 // GEPWidth may have been unknown because the base is a scalar,
3232 // but it is known now.
3233 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003234 }
3235 }
3236
Craig Toppere3dcce92015-08-01 22:20:21 +00003237 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003238 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003239 return Error(ID.Loc, "base element of getelementptr must be sized");
3240
David Blaikie4a2e73b2015-04-02 18:55:32 +00003241 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003242 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003243
3244 if (InRangeOp) {
3245 if (*InRangeOp == 0)
3246 return Error(ID.Loc,
3247 "inrange keyword may not appear on pointer operand");
3248 --*InRangeOp;
3249 }
3250
3251 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3252 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003253 } else if (Opc == Instruction::Select) {
3254 if (Elts.size() != 3)
3255 return Error(ID.Loc, "expected three operands to select");
3256 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3257 Elts[2]))
3258 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003259 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003260 } else if (Opc == Instruction::ShuffleVector) {
3261 if (Elts.size() != 3)
3262 return Error(ID.Loc, "expected three operands to shufflevector");
3263 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3264 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003265 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003266 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 } else if (Opc == Instruction::ExtractElement) {
3268 if (Elts.size() != 2)
3269 return Error(ID.Loc, "expected two operands to extractelement");
3270 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3271 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003272 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 } else {
3274 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3275 if (Elts.size() != 3)
3276 return Error(ID.Loc, "expected three operands to insertelement");
3277 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3278 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003279 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003280 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003281 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003282
Chris Lattnerac161bf2009-01-02 07:01:27 +00003283 ID.Kind = ValID::t_Constant;
3284 return false;
3285 }
3286 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003287
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288 Lex.Lex();
3289 return false;
3290}
3291
3292/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003293bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003294 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003295 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003296 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003297 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003298 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003299 if (V && !(C = dyn_cast<Constant>(V)))
3300 return Error(ID.Loc, "global values must be constants");
3301 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003302}
3303
Victor Hernandez9d75c962010-01-11 22:31:58 +00003304bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003305 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003306 return ParseType(Ty) ||
3307 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003308}
3309
Rafael Espindola83a362c2015-01-06 22:55:16 +00003310bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003311 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003312
3313 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003314 if (!EatIfPresent(lltok::kw_comdat))
3315 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003316
3317 if (EatIfPresent(lltok::lparen)) {
3318 if (Lex.getKind() != lltok::ComdatVar)
3319 return TokError("expected comdat variable");
3320 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3321 Lex.Lex();
3322 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3323 return true;
3324 } else {
3325 if (GlobalName.empty())
3326 return TokError("comdat cannot be unnamed");
3327 C = getComdat(GlobalName, KwLoc);
3328 }
3329
David Majnemerdad0a642014-06-27 18:19:56 +00003330 return false;
3331}
3332
Victor Hernandez9d75c962010-01-11 22:31:58 +00003333/// ParseGlobalValueVector
3334/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003335/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3336bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3337 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003338 // Empty list.
3339 if (Lex.getKind() == lltok::rbrace ||
3340 Lex.getKind() == lltok::rsquare ||
3341 Lex.getKind() == lltok::greater ||
3342 Lex.getKind() == lltok::rparen)
3343 return false;
3344
Peter Collingbourned93620b2016-11-10 22:34:55 +00003345 do {
3346 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3347 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003348
Peter Collingbourned93620b2016-11-10 22:34:55 +00003349 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003350 if (ParseGlobalTypeAndValue(C)) return true;
3351 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003352 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003353
3354 return false;
3355}
3356
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003357bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003358 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003359 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003360 return true;
3361
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003362 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003363 return false;
3364}
3365
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003366/// MDNode:
3367/// ::= !{ ... }
3368/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003369/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003370bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003371 if (Lex.getKind() == lltok::MetadataVar)
3372 return ParseSpecializedMDNode(N);
3373
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003374 return ParseToken(lltok::exclaim, "expected '!' here") ||
3375 ParseMDNodeTail(N);
3376}
3377
3378bool LLParser::ParseMDNodeTail(MDNode *&N) {
3379 // !{ ... }
3380 if (Lex.getKind() == lltok::lbrace)
3381 return ParseMDTuple(N);
3382
3383 // !42
3384 return ParseMDNodeID(N);
3385}
3386
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003387namespace {
3388
3389/// Structure to represent an optional metadata field.
3390template <class FieldTy> struct MDFieldImpl {
3391 typedef MDFieldImpl ImplTy;
3392 FieldTy Val;
3393 bool Seen;
3394
3395 void assign(FieldTy Val) {
3396 Seen = true;
3397 this->Val = std::move(Val);
3398 }
3399
3400 explicit MDFieldImpl(FieldTy Default)
3401 : Val(std::move(Default)), Seen(false) {}
3402};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003403
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003404struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3405 uint64_t Max;
3406
3407 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3408 : ImplTy(Default), Max(Max) {}
3409};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003410
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003411struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003412 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003413};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003414
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003415struct ColumnField : public MDUnsignedField {
3416 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3417};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003418
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003419struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003420 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003421 DwarfTagField(dwarf::Tag DefaultTag)
3422 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003423};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003424
Amjad Abouda9bcf162015-12-10 12:56:35 +00003425struct DwarfMacinfoTypeField : public MDUnsignedField {
3426 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3427 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3428 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3429};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003430
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003431struct DwarfAttEncodingField : public MDUnsignedField {
3432 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3433};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003434
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003435struct DwarfVirtualityField : public MDUnsignedField {
3436 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3437};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003438
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003439struct DwarfLangField : public MDUnsignedField {
3440 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3441};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003442
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003443struct DwarfCCField : public MDUnsignedField {
3444 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3445};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003446
Adrian Prantlb939a252016-03-31 23:56:58 +00003447struct EmissionKindField : public MDUnsignedField {
3448 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3449};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003450
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003451struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3452 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003453};
3454
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003455struct MDSignedField : public MDFieldImpl<int64_t> {
3456 int64_t Min;
3457 int64_t Max;
3458
3459 MDSignedField(int64_t Default = 0)
3460 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3461 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3462 : ImplTy(Default), Min(Min), Max(Max) {}
3463};
3464
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003465struct MDBoolField : public MDFieldImpl<bool> {
3466 MDBoolField(bool Default = false) : ImplTy(Default) {}
3467};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003468
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003469struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003470 bool AllowNull;
3471
3472 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003473};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003474
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003475struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3476 MDConstant() : ImplTy(nullptr) {}
3477};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003478
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003479struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003480 bool AllowEmpty;
3481 MDStringField(bool AllowEmpty = true)
3482 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003483};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003484
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003485struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3486 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3487};
3488
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003489struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3490 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3491 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3492};
3493
Eugene Zelenko1804a772016-08-25 00:45:04 +00003494} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003495
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003496namespace llvm {
3497
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003498template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003499bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003500 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003501 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3502 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003503
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003504 auto &U = Lex.getAPSIntVal();
3505 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003506 return TokError("value for '" + Name + "' too large, limit is " +
3507 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003508 Result.assign(U.getZExtValue());
3509 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003510 Lex.Lex();
3511 return false;
3512}
3513
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003514template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003515bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3516 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3517}
3518template <>
3519bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3520 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3521}
3522
3523template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003524bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3525 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003526 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003527
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003528 if (Lex.getKind() != lltok::DwarfTag)
3529 return TokError("expected DWARF tag");
3530
3531 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3532 if (Tag == dwarf::DW_TAG_invalid)
3533 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003534 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003535
3536 Result.assign(Tag);
3537 Lex.Lex();
3538 return false;
3539}
3540
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003541template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003542bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003543 DwarfMacinfoTypeField &Result) {
3544 if (Lex.getKind() == lltok::APSInt)
3545 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3546
3547 if (Lex.getKind() != lltok::DwarfMacinfo)
3548 return TokError("expected DWARF macinfo type");
3549
3550 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3551 if (Macinfo == dwarf::DW_MACINFO_invalid)
3552 return TokError(
3553 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3554 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3555
3556 Result.assign(Macinfo);
3557 Lex.Lex();
3558 return false;
3559}
3560
3561template <>
3562bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003563 DwarfVirtualityField &Result) {
3564 if (Lex.getKind() == lltok::APSInt)
3565 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3566
3567 if (Lex.getKind() != lltok::DwarfVirtuality)
3568 return TokError("expected DWARF virtuality code");
3569
3570 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003571 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003572 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3573 Lex.getStrVal() + "'");
3574 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3575 Result.assign(Virtuality);
3576 Lex.Lex();
3577 return false;
3578}
3579
3580template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003581bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3582 if (Lex.getKind() == lltok::APSInt)
3583 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3584
3585 if (Lex.getKind() != lltok::DwarfLang)
3586 return TokError("expected DWARF language");
3587
3588 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3589 if (!Lang)
3590 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3591 "'");
3592 assert(Lang <= Result.Max && "Expected valid DWARF language");
3593 Result.assign(Lang);
3594 Lex.Lex();
3595 return false;
3596}
3597
3598template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003599bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3600 if (Lex.getKind() == lltok::APSInt)
3601 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3602
3603 if (Lex.getKind() != lltok::DwarfCC)
3604 return TokError("expected DWARF calling convention");
3605
3606 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3607 if (!CC)
3608 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3609 "'");
3610 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3611 Result.assign(CC);
3612 Lex.Lex();
3613 return false;
3614}
3615
3616template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003617bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3618 if (Lex.getKind() == lltok::APSInt)
3619 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3620
3621 if (Lex.getKind() != lltok::EmissionKind)
3622 return TokError("expected emission kind");
3623
3624 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3625 if (!Kind)
3626 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3627 "'");
3628 assert(*Kind <= Result.Max && "Expected valid emission kind");
3629 Result.assign(*Kind);
3630 Lex.Lex();
3631 return false;
3632}
3633
3634template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003635bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003636 DwarfAttEncodingField &Result) {
3637 if (Lex.getKind() == lltok::APSInt)
3638 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3639
3640 if (Lex.getKind() != lltok::DwarfAttEncoding)
3641 return TokError("expected DWARF type attribute encoding");
3642
3643 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3644 if (!Encoding)
3645 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3646 Lex.getStrVal() + "'");
3647 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3648 Result.assign(Encoding);
3649 Lex.Lex();
3650 return false;
3651}
3652
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003653/// DIFlagField
3654/// ::= uint32
3655/// ::= DIFlagVector
3656/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3657template <>
3658bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003659
3660 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003661 auto parseFlag = [&](DINode::DIFlags &Val) {
3662 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3663 uint32_t TempVal = static_cast<uint32_t>(Val);
3664 bool Res = ParseUInt32(TempVal);
3665 Val = static_cast<DINode::DIFlags>(TempVal);
3666 return Res;
3667 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003668
3669 if (Lex.getKind() != lltok::DIFlag)
3670 return TokError("expected debug info flag");
3671
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003672 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003673 if (!Val)
3674 return TokError(Twine("invalid debug info flag flag '") +
3675 Lex.getStrVal() + "'");
3676 Lex.Lex();
3677 return false;
3678 };
3679
3680 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003681 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003682 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003683 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003684 if (parseFlag(Val))
3685 return true;
3686 Combined |= Val;
3687 } while (EatIfPresent(lltok::bar));
3688
3689 Result.assign(Combined);
3690 return false;
3691}
3692
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003693template <>
3694bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003695 MDSignedField &Result) {
3696 if (Lex.getKind() != lltok::APSInt)
3697 return TokError("expected signed integer");
3698
3699 auto &S = Lex.getAPSIntVal();
3700 if (S < Result.Min)
3701 return TokError("value for '" + Name + "' too small, limit is " +
3702 Twine(Result.Min));
3703 if (S > Result.Max)
3704 return TokError("value for '" + Name + "' too large, limit is " +
3705 Twine(Result.Max));
3706 Result.assign(S.getExtValue());
3707 assert(Result.Val >= Result.Min && "Expected value in range");
3708 assert(Result.Val <= Result.Max && "Expected value in range");
3709 Lex.Lex();
3710 return false;
3711}
3712
3713template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003714bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3715 switch (Lex.getKind()) {
3716 default:
3717 return TokError("expected 'true' or 'false'");
3718 case lltok::kw_true:
3719 Result.assign(true);
3720 break;
3721 case lltok::kw_false:
3722 Result.assign(false);
3723 break;
3724 }
3725 Lex.Lex();
3726 return false;
3727}
3728
3729template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003730bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003731 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003732 if (!Result.AllowNull)
3733 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003734 Lex.Lex();
3735 Result.assign(nullptr);
3736 return false;
3737 }
3738
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003739 Metadata *MD;
3740 if (ParseMetadata(MD, nullptr))
3741 return true;
3742
3743 Result.assign(MD);
3744 return false;
3745}
3746
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003747template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003748bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003749 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003750 std::string S;
3751 if (ParseStringConstant(S))
3752 return true;
3753
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003754 if (!Result.AllowEmpty && S.empty())
3755 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3756
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003757 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003758 return false;
3759}
3760
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003761template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003762bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3763 SmallVector<Metadata *, 4> MDs;
3764 if (ParseMDNodeVector(MDs))
3765 return true;
3766
3767 Result.assign(std::move(MDs));
3768 return false;
3769}
3770
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003771template <>
3772bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3773 ChecksumKindField &Result) {
3774 if (Lex.getKind() != lltok::ChecksumKind)
3775 return TokError(
3776 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3777
3778 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3779
3780 Result.assign(CSKind);
3781 Lex.Lex();
3782 return false;
3783}
3784
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003785} // end namespace llvm
3786
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003787template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003788bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003789 do {
3790 if (Lex.getKind() != lltok::LabelStr)
3791 return TokError("expected field label here");
3792
3793 if (parseField())
3794 return true;
3795 } while (EatIfPresent(lltok::comma));
3796
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003797 return false;
3798}
3799
3800template <class ParserTy>
3801bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3802 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3803 Lex.Lex();
3804
3805 if (ParseToken(lltok::lparen, "expected '(' here"))
3806 return true;
3807 if (Lex.getKind() != lltok::rparen)
3808 if (ParseMDFieldsImplBody(parseField))
3809 return true;
3810
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003811 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003812 return ParseToken(lltok::rparen, "expected ')' here");
3813}
3814
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003815template <class FieldTy>
3816bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3817 if (Result.Seen)
3818 return TokError("field '" + Name + "' cannot be specified more than once");
3819
3820 LocTy Loc = Lex.getLoc();
3821 Lex.Lex();
3822 return ParseMDField(Loc, Name, Result);
3823}
3824
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003825bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3826 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003827
3828#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003829 if (Lex.getStrVal() == #CLASS) \
3830 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003831#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003832
3833 return TokError("expected metadata type");
3834}
3835
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003836#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3837#define NOP_FIELD(NAME, TYPE, INIT)
3838#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3839 if (!NAME.Seen) \
3840 return Error(ClosingLoc, "missing required field '" #NAME "'");
3841#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003842 if (Lex.getStrVal() == #NAME) \
3843 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003844#define PARSE_MD_FIELDS() \
3845 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3846 do { \
3847 LocTy ClosingLoc; \
3848 if (ParseMDFieldsImpl([&]() -> bool { \
3849 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3850 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3851 }, ClosingLoc)) \
3852 return true; \
3853 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3854 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003855#define GET_OR_DISTINCT(CLASS, ARGS) \
3856 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003857
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003858/// ParseDILocationFields:
3859/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3860bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003861#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003862 OPTIONAL(line, LineField, ); \
3863 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003864 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003865 OPTIONAL(inlinedAt, MDField, );
3866 PARSE_MD_FIELDS();
3867#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003868
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003869 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003870 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003871 return false;
3872}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003873
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003874/// ParseGenericDINode:
3875/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3876bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003877#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003878 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003879 OPTIONAL(header, MDStringField, ); \
3880 OPTIONAL(operands, MDFieldList, );
3881 PARSE_MD_FIELDS();
3882#undef VISIT_MD_FIELDS
3883
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003884 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003885 (Context, tag.Val, header.Val, operands.Val));
3886 return false;
3887}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003888
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003889/// ParseDISubrange:
3890/// ::= !DISubrange(count: 30, lowerBound: 2)
3891bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003892#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003893 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003894 OPTIONAL(lowerBound, MDSignedField, );
3895 PARSE_MD_FIELDS();
3896#undef VISIT_MD_FIELDS
3897
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003898 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003899 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003900}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003901
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003902/// ParseDIEnumerator:
3903/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3904bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003905#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003906 REQUIRED(name, MDStringField, ); \
3907 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003908 PARSE_MD_FIELDS();
3909#undef VISIT_MD_FIELDS
3910
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003911 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003912 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003913}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003914
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003915/// ParseDIBasicType:
3916/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3917bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003918#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003919 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003920 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003921 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003922 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003923 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003924 PARSE_MD_FIELDS();
3925#undef VISIT_MD_FIELDS
3926
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003927 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003928 align.Val, encoding.Val));
3929 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003930}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003931
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003932/// ParseDIDerivedType:
3933/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003934/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003935/// align: 32, offset: 0, flags: 0, extraData: !3,
3936/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003937bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003938#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3939 REQUIRED(tag, DwarfTagField, ); \
3940 OPTIONAL(name, MDStringField, ); \
3941 OPTIONAL(file, MDField, ); \
3942 OPTIONAL(line, LineField, ); \
3943 OPTIONAL(scope, MDField, ); \
3944 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003945 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003946 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003947 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003948 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003949 OPTIONAL(extraData, MDField, ); \
3950 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003951 PARSE_MD_FIELDS();
3952#undef VISIT_MD_FIELDS
3953
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003954 Optional<unsigned> DWARFAddressSpace;
3955 if (dwarfAddressSpace.Val != UINT32_MAX)
3956 DWARFAddressSpace = dwarfAddressSpace.Val;
3957
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003958 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003959 (Context, tag.Val, name.Val, file.Val, line.Val,
3960 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003961 offset.Val, DWARFAddressSpace, flags.Val,
3962 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003963 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003964}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003965
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003966bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003967#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3968 REQUIRED(tag, DwarfTagField, ); \
3969 OPTIONAL(name, MDStringField, ); \
3970 OPTIONAL(file, MDField, ); \
3971 OPTIONAL(line, LineField, ); \
3972 OPTIONAL(scope, MDField, ); \
3973 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003974 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003975 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003976 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003977 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003978 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003979 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003980 OPTIONAL(vtableHolder, MDField, ); \
3981 OPTIONAL(templateParams, MDField, ); \
3982 OPTIONAL(identifier, MDStringField, );
3983 PARSE_MD_FIELDS();
3984#undef VISIT_MD_FIELDS
3985
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003986 // If this has an identifier try to build an ODR type.
3987 if (identifier.Val)
3988 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003989 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3990 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3991 elements.Val, runtimeLang.Val, vtableHolder.Val,
3992 templateParams.Val)) {
3993 Result = CT;
3994 return false;
3995 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003996
3997 // Create a new node, and save it in the context if it belongs in the type
3998 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003999 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004000 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004001 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4002 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4003 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4004 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004005}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004006
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004007bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004008#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004009 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004010 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004011 REQUIRED(types, MDField, );
4012 PARSE_MD_FIELDS();
4013#undef VISIT_MD_FIELDS
4014
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004015 Result = GET_OR_DISTINCT(DISubroutineType,
4016 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004017 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004018}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004019
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004020/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004021/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4022/// checksumkind: CSK_MD5,
4023/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004024bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004025#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4026 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004027 REQUIRED(directory, MDStringField, ); \
4028 OPTIONAL(checksumkind, ChecksumKindField, ); \
4029 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004030 PARSE_MD_FIELDS();
4031#undef VISIT_MD_FIELDS
4032
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004033 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4034 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004035 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004036}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004037
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004038/// ParseDICompileUnit:
4039/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004040/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004041/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004042/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004043/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004044bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004045 if (!IsDistinct)
4046 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4047
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004048#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4049 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004050 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004051 OPTIONAL(producer, MDStringField, ); \
4052 OPTIONAL(isOptimized, MDBoolField, ); \
4053 OPTIONAL(flags, MDStringField, ); \
4054 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4055 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004056 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004057 OPTIONAL(enums, MDField, ); \
4058 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004059 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004060 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004061 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004062 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004063 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4064 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004065 PARSE_MD_FIELDS();
4066#undef VISIT_MD_FIELDS
4067
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004068 Result = DICompileUnit::getDistinct(
4069 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4070 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004071 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004072 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004073 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004074}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004075
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004076/// ParseDISubprogram:
4077/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004078/// file: !1, line: 7, type: !2, isLocal: false,
4079/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004080/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004081/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004082/// isOptimized: false, templateParams: !4, declaration: !5,
4083/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004084bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004085 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004086#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4087 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004088 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004089 OPTIONAL(linkageName, MDStringField, ); \
4090 OPTIONAL(file, MDField, ); \
4091 OPTIONAL(line, LineField, ); \
4092 OPTIONAL(type, MDField, ); \
4093 OPTIONAL(isLocal, MDBoolField, ); \
4094 OPTIONAL(isDefinition, MDBoolField, (true)); \
4095 OPTIONAL(scopeLine, LineField, ); \
4096 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004097 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004098 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004099 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004100 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004101 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004102 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004103 OPTIONAL(templateParams, MDField, ); \
4104 OPTIONAL(declaration, MDField, ); \
4105 OPTIONAL(variables, MDField, );
4106 PARSE_MD_FIELDS();
4107#undef VISIT_MD_FIELDS
4108
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004109 if (isDefinition.Val && !IsDistinct)
4110 return Lex.Error(
4111 Loc,
4112 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4113
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004114 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004115 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4116 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4117 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004118 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4119 isOptimized.Val, unit.Val, templateParams.Val,
4120 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004121 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004122}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004123
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004124/// ParseDILexicalBlock:
4125/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4126bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004127#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004128 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004129 OPTIONAL(file, MDField, ); \
4130 OPTIONAL(line, LineField, ); \
4131 OPTIONAL(column, ColumnField, );
4132 PARSE_MD_FIELDS();
4133#undef VISIT_MD_FIELDS
4134
4135 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004136 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004137 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004138}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004139
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004140/// ParseDILexicalBlockFile:
4141/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4142bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004143#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004144 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004145 OPTIONAL(file, MDField, ); \
4146 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4147 PARSE_MD_FIELDS();
4148#undef VISIT_MD_FIELDS
4149
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004150 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004151 (Context, scope.Val, file.Val, discriminator.Val));
4152 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004153}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004154
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004155/// ParseDINamespace:
4156/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4157bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004158#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4159 REQUIRED(scope, MDField, ); \
4160 OPTIONAL(file, MDField, ); \
4161 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004162 OPTIONAL(line, LineField, ); \
4163 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004164 PARSE_MD_FIELDS();
4165#undef VISIT_MD_FIELDS
4166
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004167 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantldbfda632016-11-03 19:42:02 +00004168 (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004169 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004170}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004171
Amjad Abouda9bcf162015-12-10 12:56:35 +00004172/// ParseDIMacro:
4173/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4174bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4175#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4176 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004177 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004178 REQUIRED(name, MDStringField, ); \
4179 OPTIONAL(value, MDStringField, );
4180 PARSE_MD_FIELDS();
4181#undef VISIT_MD_FIELDS
4182
4183 Result = GET_OR_DISTINCT(DIMacro,
4184 (Context, type.Val, line.Val, name.Val, value.Val));
4185 return false;
4186}
4187
4188/// ParseDIMacroFile:
4189/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4190bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4191#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4192 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004193 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004194 REQUIRED(file, MDField, ); \
4195 OPTIONAL(nodes, MDField, );
4196 PARSE_MD_FIELDS();
4197#undef VISIT_MD_FIELDS
4198
4199 Result = GET_OR_DISTINCT(DIMacroFile,
4200 (Context, type.Val, line.Val, file.Val, nodes.Val));
4201 return false;
4202}
4203
Adrian Prantlab1243f2015-06-29 23:03:47 +00004204/// ParseDIModule:
4205/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4206/// includePath: "/usr/include", isysroot: "/")
4207bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4208#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4209 REQUIRED(scope, MDField, ); \
4210 REQUIRED(name, MDStringField, ); \
4211 OPTIONAL(configMacros, MDStringField, ); \
4212 OPTIONAL(includePath, MDStringField, ); \
4213 OPTIONAL(isysroot, MDStringField, );
4214 PARSE_MD_FIELDS();
4215#undef VISIT_MD_FIELDS
4216
4217 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4218 configMacros.Val, includePath.Val, isysroot.Val));
4219 return false;
4220}
4221
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004222/// ParseDITemplateTypeParameter:
4223/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4224bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004225#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004226 OPTIONAL(name, MDStringField, ); \
4227 REQUIRED(type, MDField, );
4228 PARSE_MD_FIELDS();
4229#undef VISIT_MD_FIELDS
4230
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004231 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004232 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004233 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004234}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004235
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004236/// ParseDITemplateValueParameter:
4237/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004238/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004239bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004240#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004241 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004242 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004243 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004244 REQUIRED(value, MDField, );
4245 PARSE_MD_FIELDS();
4246#undef VISIT_MD_FIELDS
4247
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004248 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004249 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004250 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004251}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004252
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004253/// ParseDIGlobalVariable:
4254/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004255/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004256/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004257bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004258#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004259 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004260 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004261 OPTIONAL(linkageName, MDStringField, ); \
4262 OPTIONAL(file, MDField, ); \
4263 OPTIONAL(line, LineField, ); \
4264 OPTIONAL(type, MDField, ); \
4265 OPTIONAL(isLocal, MDBoolField, ); \
4266 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004267 OPTIONAL(declaration, MDField, ); \
4268 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004269 PARSE_MD_FIELDS();
4270#undef VISIT_MD_FIELDS
4271
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004272 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004273 (Context, scope.Val, name.Val, linkageName.Val,
4274 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004275 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004276 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004277}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004278
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004279/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004280/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004281/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4282/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004283/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004284/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4285/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004286bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004287#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004288 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004289 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004290 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004291 OPTIONAL(file, MDField, ); \
4292 OPTIONAL(line, LineField, ); \
4293 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004294 OPTIONAL(flags, DIFlagField, ); \
4295 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004296 PARSE_MD_FIELDS();
4297#undef VISIT_MD_FIELDS
4298
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004299 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004300 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004301 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004302 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004303}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004304
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004305/// ParseDIExpression:
4306/// ::= !DIExpression(0, 7, -1)
4307bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004308 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4309 Lex.Lex();
4310
4311 if (ParseToken(lltok::lparen, "expected '(' here"))
4312 return true;
4313
4314 SmallVector<uint64_t, 8> Elements;
4315 if (Lex.getKind() != lltok::rparen)
4316 do {
4317 if (Lex.getKind() == lltok::DwarfOp) {
4318 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4319 Lex.Lex();
4320 Elements.push_back(Op);
4321 continue;
4322 }
4323 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4324 }
4325
4326 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4327 return TokError("expected unsigned integer");
4328
4329 auto &U = Lex.getAPSIntVal();
4330 if (U.ugt(UINT64_MAX))
4331 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4332 Elements.push_back(U.getZExtValue());
4333 Lex.Lex();
4334 } while (EatIfPresent(lltok::comma));
4335
4336 if (ParseToken(lltok::rparen, "expected ')' here"))
4337 return true;
4338
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004339 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004340 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004341}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004342
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004343/// ParseDIGlobalVariableExpression:
4344/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4345bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4346 bool IsDistinct) {
4347#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4348 REQUIRED(var, MDField, ); \
4349 OPTIONAL(expr, MDField, );
4350 PARSE_MD_FIELDS();
4351#undef VISIT_MD_FIELDS
4352
4353 Result =
4354 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4355 return false;
4356}
4357
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004358/// ParseDIObjCProperty:
4359/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004360/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004361bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004362#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004363 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004364 OPTIONAL(file, MDField, ); \
4365 OPTIONAL(line, LineField, ); \
4366 OPTIONAL(setter, MDStringField, ); \
4367 OPTIONAL(getter, MDStringField, ); \
4368 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4369 OPTIONAL(type, MDField, );
4370 PARSE_MD_FIELDS();
4371#undef VISIT_MD_FIELDS
4372
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004373 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004374 (Context, name.Val, file.Val, line.Val, setter.Val,
4375 getter.Val, attributes.Val, type.Val));
4376 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004377}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004378
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004379/// ParseDIImportedEntity:
4380/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004381/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004382bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004383#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4384 REQUIRED(tag, DwarfTagField, ); \
4385 REQUIRED(scope, MDField, ); \
4386 OPTIONAL(entity, MDField, ); \
4387 OPTIONAL(line, LineField, ); \
4388 OPTIONAL(name, MDStringField, );
4389 PARSE_MD_FIELDS();
4390#undef VISIT_MD_FIELDS
4391
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004392 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004393 entity.Val, line.Val, name.Val));
4394 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004395}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004396
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004397#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004398#undef NOP_FIELD
4399#undef REQUIRE_FIELD
4400#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004401
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004402/// ParseMetadataAsValue
4403/// ::= metadata i32 %local
4404/// ::= metadata i32 @global
4405/// ::= metadata i32 7
4406/// ::= metadata !0
4407/// ::= metadata !{...}
4408/// ::= metadata !"string"
4409bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4410 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004411 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004412 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004413 return true;
4414
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004415 V = MetadataAsValue::get(Context, MD);
4416 return false;
4417}
4418
4419/// ParseValueAsMetadata
4420/// ::= i32 %local
4421/// ::= i32 @global
4422/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004423bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4424 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004425 Type *Ty;
4426 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004427 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004428 return true;
4429 if (Ty->isMetadataTy())
4430 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4431
4432 Value *V;
4433 if (ParseValue(Ty, V, PFS))
4434 return true;
4435
4436 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004437 return false;
4438}
4439
4440/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004441/// ::= i32 %local
4442/// ::= i32 @global
4443/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004444/// ::= !42
4445/// ::= !{...}
4446/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004447/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004448bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004449 if (Lex.getKind() == lltok::MetadataVar) {
4450 MDNode *N;
4451 if (ParseSpecializedMDNode(N))
4452 return true;
4453 MD = N;
4454 return false;
4455 }
4456
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004457 // ValueAsMetadata:
4458 // <type> <value>
4459 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004460 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004461
4462 // '!'.
4463 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4464 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004465
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004466 // MDString:
4467 // ::= '!' STRINGCONSTANT
4468 if (Lex.getKind() == lltok::StringConstant) {
4469 MDString *S;
4470 if (ParseMDString(S))
4471 return true;
4472 MD = S;
4473 return false;
4474 }
4475
Dan Gohman8939ba332010-07-14 18:26:50 +00004476 // MDNode:
4477 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004478 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004479 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004480 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004481 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004482 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004483 return false;
4484}
4485
Victor Hernandez9d75c962010-01-11 22:31:58 +00004486//===----------------------------------------------------------------------===//
4487// Function Parsing.
4488//===----------------------------------------------------------------------===//
4489
Chris Lattner229907c2011-07-18 04:54:35 +00004490bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004491 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004492 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004493 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004494
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004496 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004497 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004498 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004499 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004500 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004501 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004502 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004503 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004504 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004505 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004506 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004507 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4508 (ID.UIntVal >> 1) & 1,
4509 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004510 return false;
4511 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004512 case ValID::t_GlobalName:
4513 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004514 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 case ValID::t_GlobalID:
4516 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004517 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004519 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004521 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004522 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 return false;
4524 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004525 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4527 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004528
Dan Gohman518cda42011-12-17 00:04:22 +00004529 // The lexer has no type info, so builds all half, float, and double FP
4530 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004531 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004532 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004533 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004534 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004535 &Ignored);
4536 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004537 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004538 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004539 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004540 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004541
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004542 if (V->getType() != Ty)
4543 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004544 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004545
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546 return false;
4547 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004548 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004549 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004550 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004551 return false;
4552 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004553 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004554 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004555 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004556 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004558 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004559 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004560 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004561 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004562 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004564 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004565 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004566 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004567 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004568 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004569 case ValID::t_None:
4570 if (!Ty->isTokenTy())
4571 return Error(ID.Loc, "invalid type for none constant");
4572 V = Constant::getNullValue(Ty);
4573 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004574 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004575 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004576 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004577
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578 V = ID.ConstantVal;
4579 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004580 case ValID::t_ConstantStruct:
4581 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004582 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004583 if (ST->getNumElements() != ID.UIntVal)
4584 return Error(ID.Loc,
4585 "initializer with struct type has wrong # elements");
4586 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4587 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004588
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004589 // Verify that the elements are compatible with the structtype.
4590 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4591 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4592 return Error(ID.Loc, "element " + Twine(i) +
4593 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004594
David Blaikieadbda4b2015-08-03 20:08:41 +00004595 V = ConstantStruct::get(
4596 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004597 } else
4598 return Error(ID.Loc, "constant expression type mismatch");
4599 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004601 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004602}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004603
Alex Lorenzd2255952015-07-17 22:07:03 +00004604bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4605 C = nullptr;
4606 ValID ID;
4607 auto Loc = Lex.getLoc();
4608 if (ParseValID(ID, /*PFS=*/nullptr))
4609 return true;
4610 switch (ID.Kind) {
4611 case ValID::t_APSInt:
4612 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004613 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004614 case ValID::t_Constant:
4615 case ValID::t_ConstantStruct:
4616 case ValID::t_PackedConstantStruct: {
4617 Value *V;
4618 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4619 return true;
4620 assert(isa<Constant>(V) && "Expected a constant value");
4621 C = cast<Constant>(V);
4622 return false;
4623 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004624 case ValID::t_Null:
4625 C = Constant::getNullValue(Ty);
4626 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004627 default:
4628 return Error(Loc, "expected a constant value");
4629 }
4630}
4631
David Majnemer8a1c45d2015-12-12 05:38:55 +00004632bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004633 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004635 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636}
4637
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004638bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004639 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004640 return ParseType(Ty) ||
4641 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642}
4643
Chris Lattner3ed871f2009-10-27 19:13:16 +00004644bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4645 PerFunctionState &PFS) {
4646 Value *V;
4647 Loc = Lex.getLoc();
4648 if (ParseTypeAndValue(V, PFS)) return true;
4649 if (!isa<BasicBlock>(V))
4650 return Error(Loc, "expected a basic block");
4651 BB = cast<BasicBlock>(V);
4652 return false;
4653}
4654
Chris Lattnerac161bf2009-01-02 07:01:27 +00004655/// FunctionHeader
4656/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004657/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004658/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4660 // Parse the linkage.
4661 LocTy LinkageLoc = Lex.getLoc();
4662 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004663
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004664 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004665 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004666 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004667 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004668 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004669 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004670 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004671 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4672 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004673 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674 return true;
4675
4676 // Verify that the linkage is ok.
4677 switch ((GlobalValue::LinkageTypes)Linkage) {
4678 case GlobalValue::ExternalLinkage:
4679 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004680 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004681 if (isDefine)
4682 return Error(LinkageLoc, "invalid linkage for function definition");
4683 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004684 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004685 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004686 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004687 case GlobalValue::LinkOnceAnyLinkage:
4688 case GlobalValue::LinkOnceODRLinkage:
4689 case GlobalValue::WeakAnyLinkage:
4690 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004691 if (!isDefine)
4692 return Error(LinkageLoc, "invalid linkage for function declaration");
4693 break;
4694 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004695 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 return Error(LinkageLoc, "invalid function linkage type");
4697 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004698
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004699 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4700 return Error(LinkageLoc,
4701 "symbol with local linkage must have default visibility");
4702
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004703 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004704 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004705
Chris Lattnerac161bf2009-01-02 07:01:27 +00004706 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004707
4708 std::string FunctionName;
4709 if (Lex.getKind() == lltok::GlobalVar) {
4710 FunctionName = Lex.getStrVal();
4711 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4712 unsigned NameID = Lex.getUIntVal();
4713
4714 if (NameID != NumberedVals.size())
4715 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004716 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004717 } else {
4718 return TokError("expected function name");
4719 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004720
Chris Lattner3822f632009-01-02 08:05:26 +00004721 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004722
Chris Lattner3822f632009-01-02 08:05:26 +00004723 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004724 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004725
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004726 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004727 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004728 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004729 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004730 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004733 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004734 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004735 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004736 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004737 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004738 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004739 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004740
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004741 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004742 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004743 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004744 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004745 (EatIfPresent(lltok::kw_section) &&
4746 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004747 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004748 ParseOptionalAlignment(Alignment) ||
4749 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004750 ParseStringConstant(GC)) ||
4751 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004752 ParseGlobalTypeAndValue(Prefix)) ||
4753 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004754 ParseGlobalTypeAndValue(Prologue)) ||
4755 (EatIfPresent(lltok::kw_personality) &&
4756 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004757 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004758
Michael Gottesman41748d72013-06-27 00:25:01 +00004759 if (FuncAttrs.contains(Attribute::Builtin))
4760 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004761
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004763 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004764 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004765 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004766 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004767
Chris Lattnerac161bf2009-01-02 07:01:27 +00004768 // Okay, if we got here, the function is syntactically valid. Convert types
4769 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004770 std::vector<Type*> ParamTypeList;
Reid Kleckner211b1f32017-04-10 20:34:19 +00004771 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004772
Reid Kleckner211b1f32017-04-10 20:34:19 +00004773 if (RetAttrs.hasAttributes())
4774 Attrs.push_back(AttributeList::get(RetType->getContext(),
4775 AttributeList::ReturnIndex, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004776
Chris Lattnerac161bf2009-01-02 07:01:27 +00004777 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004778 ParamTypeList.push_back(ArgList[i].Ty);
Reid Kleckner211b1f32017-04-10 20:34:19 +00004779 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4780 AttrBuilder B(ArgList[i].Attrs, i + 1);
4781 Attrs.push_back(AttributeList::get(RetType->getContext(), i + 1, B));
4782 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004783 }
4784
Reid Kleckner211b1f32017-04-10 20:34:19 +00004785 if (FuncAttrs.hasAttributes())
4786 Attrs.push_back(AttributeList::get(
4787 RetType->getContext(), AttributeList::FunctionIndex, FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788
Reid Klecknerb5180542017-03-21 16:57:19 +00004789 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004790
Bill Wendling749a43d2012-12-30 13:50:49 +00004791 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004792 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4793
Chris Lattner229907c2011-07-18 04:54:35 +00004794 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004795 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004796 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004797
Craig Topper2617dcc2014-04-15 06:32:26 +00004798 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 if (!FunctionName.empty()) {
4800 // If this was a definition of a forward reference, remove the definition
4801 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004802 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803 if (FRVI != ForwardRefVals.end()) {
4804 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004805 if (!Fn)
4806 return Error(FRVI->second.second, "invalid forward reference to "
4807 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004808 if (Fn->getType() != PFT)
4809 return Error(FRVI->second.second, "invalid forward reference to "
4810 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004811
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 ForwardRefVals.erase(FRVI);
4813 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004814 // Reject redefinitions.
4815 return Error(NameLoc, "invalid redefinition of function '" +
4816 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004817 } else if (M->getNamedValue(FunctionName)) {
4818 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004819 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004820
Dan Gohman399d6ae2009-08-29 23:37:49 +00004821 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822 // If this is a definition of a forward referenced function, make sure the
4823 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004824 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004825 if (I != ForwardRefValIDs.end()) {
4826 Fn = cast<Function>(I->second.first);
4827 if (Fn->getType() != PFT)
4828 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004829 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 ForwardRefValIDs.erase(I);
4831 }
4832 }
4833
Craig Topper2617dcc2014-04-15 06:32:26 +00004834 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004835 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4836 else // Move the forward-reference to the correct spot in the module.
4837 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4838
4839 if (FunctionName.empty())
4840 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004841
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4843 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004844 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004845 Fn->setCallingConv(CC);
4846 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004847 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 Fn->setAlignment(Alignment);
4849 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004850 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004851 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004852 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004853 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004854 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004855 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004856
Chris Lattnerac161bf2009-01-02 07:01:27 +00004857 // Add all of the arguments we parsed to the function.
4858 Function::arg_iterator ArgIt = Fn->arg_begin();
4859 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4860 // If the argument has a name, insert it into the argument symbol table.
4861 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004862
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 // Set the name, if it conflicted, it will be auto-renamed.
4864 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004865
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004866 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4868 ArgList[i].Name + "'");
4869 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004870
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004871 if (isDefine)
4872 return false;
4873
Robin Morisset039781e2014-08-29 21:53:01 +00004874 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004875 ValID ID;
4876 if (FunctionName.empty()) {
4877 ID.Kind = ValID::t_GlobalID;
4878 ID.UIntVal = NumberedVals.size() - 1;
4879 } else {
4880 ID.Kind = ValID::t_GlobalName;
4881 ID.StrVal = FunctionName;
4882 }
4883 auto Blocks = ForwardRefBlockAddresses.find(ID);
4884 if (Blocks != ForwardRefBlockAddresses.end())
4885 return Error(Blocks->first.Loc,
4886 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004887 return false;
4888}
4889
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004890bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4891 ValID ID;
4892 if (FunctionNumber == -1) {
4893 ID.Kind = ValID::t_GlobalName;
4894 ID.StrVal = F.getName();
4895 } else {
4896 ID.Kind = ValID::t_GlobalID;
4897 ID.UIntVal = FunctionNumber;
4898 }
4899
4900 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4901 if (Blocks == P.ForwardRefBlockAddresses.end())
4902 return false;
4903
4904 for (const auto &I : Blocks->second) {
4905 const ValID &BBID = I.first;
4906 GlobalValue *GV = I.second;
4907
4908 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4909 "Expected local id or name");
4910 BasicBlock *BB;
4911 if (BBID.Kind == ValID::t_LocalName)
4912 BB = GetBB(BBID.StrVal, BBID.Loc);
4913 else
4914 BB = GetBB(BBID.UIntVal, BBID.Loc);
4915 if (!BB)
4916 return P.Error(BBID.Loc, "referenced value is not a basic block");
4917
4918 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4919 GV->eraseFromParent();
4920 }
4921
4922 P.ForwardRefBlockAddresses.erase(Blocks);
4923 return false;
4924}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925
4926/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004927/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004928bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004929 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004930 return TokError("expected '{' in function body");
4931 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004932
Chris Lattner3432c622009-10-28 03:39:23 +00004933 int FunctionNumber = -1;
4934 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004935
Chris Lattner3432c622009-10-28 03:39:23 +00004936 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004937
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004938 // Resolve block addresses and allow basic blocks to be forward-declared
4939 // within this function.
4940 if (PFS.resolveForwardRefBlockAddresses())
4941 return true;
4942 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4943
Chris Lattnerbbddd962010-01-09 19:20:07 +00004944 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004945 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004946 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004947
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004948 while (Lex.getKind() != lltok::rbrace &&
4949 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004951
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004952 while (Lex.getKind() != lltok::rbrace)
4953 if (ParseUseListOrder(&PFS))
4954 return true;
4955
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 // Eat the }.
4957 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004958
Chris Lattnerac161bf2009-01-02 07:01:27 +00004959 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004960 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961}
4962
4963/// ParseBasicBlock
4964/// ::= LabelStr? Instruction*
4965bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4966 // If this basic block starts out with a name, remember it.
4967 std::string Name;
4968 LocTy NameLoc = Lex.getLoc();
4969 if (Lex.getKind() == lltok::LabelStr) {
4970 Name = Lex.getStrVal();
4971 Lex.Lex();
4972 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004973
Chris Lattnerac161bf2009-01-02 07:01:27 +00004974 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004975 if (!BB)
4976 return Error(NameLoc,
4977 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004978
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004980
Chris Lattnerac161bf2009-01-02 07:01:27 +00004981 // Parse the instructions in this block until we get a terminator.
4982 Instruction *Inst;
4983 do {
4984 // This instruction may have three possibilities for a name: a) none
4985 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4986 LocTy NameLoc = Lex.getLoc();
4987 int NameID = -1;
4988 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004989
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 if (Lex.getKind() == lltok::LocalVarID) {
4991 NameID = Lex.getUIntVal();
4992 Lex.Lex();
4993 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4994 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004995 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004996 NameStr = Lex.getStrVal();
4997 Lex.Lex();
4998 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4999 return true;
5000 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005001
Chris Lattner77b89dc2009-12-30 05:23:43 +00005002 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005003 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005004 case InstError: return true;
5005 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005006 BB->getInstList().push_back(Inst);
5007
Chris Lattner77b89dc2009-12-30 05:23:43 +00005008 // With a normal result, we check to see if the instruction is followed by
5009 // a comma and metadata.
5010 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005011 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005012 return true;
5013 break;
5014 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005015 BB->getInstList().push_back(Inst);
5016
Chris Lattner77b89dc2009-12-30 05:23:43 +00005017 // If the instruction parser ate an extra comma at the end of it, it
5018 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005019 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005020 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005021 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005022 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005023
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 // Set the name on the instruction.
5025 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5026 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005027
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028 return false;
5029}
5030
5031//===----------------------------------------------------------------------===//
5032// Instruction Parsing.
5033//===----------------------------------------------------------------------===//
5034
5035/// ParseInstruction - Parse one of the many different instructions.
5036///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005037int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5038 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 lltok::Kind Token = Lex.getKind();
5040 if (Token == lltok::Eof)
5041 return TokError("found end of file when expecting more instructions");
5042 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005043 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005044 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005045
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 switch (Token) {
5047 default: return Error(Loc, "expected instruction opcode");
5048 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005049 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005050 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5051 case lltok::kw_br: return ParseBr(Inst, PFS);
5052 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005053 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005054 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005055 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005056 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5057 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005058 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5059 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005060 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 // Binary Operators.
5062 case lltok::kw_add:
5063 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005064 case lltok::kw_mul:
5065 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005066 bool NUW = EatIfPresent(lltok::kw_nuw);
5067 bool NSW = EatIfPresent(lltok::kw_nsw);
5068 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005069
Chris Lattnera676c0f2011-02-07 16:40:21 +00005070 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005071
Chris Lattnera676c0f2011-02-07 16:40:21 +00005072 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5073 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5074 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005075 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005076 case lltok::kw_fadd:
5077 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005078 case lltok::kw_fmul:
5079 case lltok::kw_fdiv:
5080 case lltok::kw_frem: {
5081 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5082 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5083 if (Res != 0)
5084 return Res;
5085 if (FMF.any())
5086 Inst->setFastMathFlags(FMF);
5087 return 0;
5088 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005089
Chris Lattner35315d02011-02-06 21:44:57 +00005090 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005091 case lltok::kw_udiv:
5092 case lltok::kw_lshr:
5093 case lltok::kw_ashr: {
5094 bool Exact = EatIfPresent(lltok::kw_exact);
5095
5096 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5097 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5098 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005099 }
5100
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005102 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 case lltok::kw_and:
5104 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005105 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005106 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5107 case lltok::kw_fcmp: {
5108 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5109 int Res = ParseCompare(Inst, PFS, KeywordVal);
5110 if (Res != 0)
5111 return Res;
5112 if (FMF.any())
5113 Inst->setFastMathFlags(FMF);
5114 return 0;
5115 }
5116
Chris Lattnerac161bf2009-01-02 07:01:27 +00005117 // Casts.
5118 case lltok::kw_trunc:
5119 case lltok::kw_zext:
5120 case lltok::kw_sext:
5121 case lltok::kw_fptrunc:
5122 case lltok::kw_fpext:
5123 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005124 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005125 case lltok::kw_uitofp:
5126 case lltok::kw_sitofp:
5127 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005128 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005130 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005131 // Other.
5132 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005133 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005134 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5135 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5136 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5137 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005138 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005139 // Call.
5140 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5141 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5142 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005143 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005145 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005146 case lltok::kw_load: return ParseLoad(Inst, PFS);
5147 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005148 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5149 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005150 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5152 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5153 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5154 }
5155}
5156
5157/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5158bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005159 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005161 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5163 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5164 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5165 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5166 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5167 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5168 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5169 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5170 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5171 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5172 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5173 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5174 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5175 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5176 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5177 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5178 }
5179 } else {
5180 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005181 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5183 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5184 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5185 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5186 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5187 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5188 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5189 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5190 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5191 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5192 }
5193 }
5194 Lex.Lex();
5195 return false;
5196}
5197
5198//===----------------------------------------------------------------------===//
5199// Terminator Instructions.
5200//===----------------------------------------------------------------------===//
5201
5202/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005203/// ::= 'ret' void (',' !dbg, !1)*
5204/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005205bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005206 PerFunctionState &PFS) {
5207 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005208 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005209 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005210
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005211 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005212
Chris Lattnerfdd87902009-10-05 05:54:46 +00005213 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005214 if (!ResType->isVoidTy())
5215 return Error(TypeLoc, "value doesn't match function result type '" +
5216 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005217
Owen Anderson55f1c092009-08-13 21:58:54 +00005218 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005219 return false;
5220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005221
Chris Lattnerac161bf2009-01-02 07:01:27 +00005222 Value *RV;
5223 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005225 if (ResType != RV->getType())
5226 return Error(TypeLoc, "value doesn't match function result type '" +
5227 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005228
Owen Anderson55f1c092009-08-13 21:58:54 +00005229 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005230 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005231}
5232
Chris Lattnerac161bf2009-01-02 07:01:27 +00005233/// ParseBr
5234/// ::= 'br' TypeAndValue
5235/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5236bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5237 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005238 Value *Op0;
5239 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005241
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5243 Inst = BranchInst::Create(BB);
5244 return false;
5245 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005246
Owen Anderson55f1c092009-08-13 21:58:54 +00005247 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005249
Chris Lattnerac161bf2009-01-02 07:01:27 +00005250 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005251 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005252 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005253 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005255
Chris Lattner3ed871f2009-10-27 19:13:16 +00005256 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 return false;
5258}
5259
5260/// ParseSwitch
5261/// Instruction
5262/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5263/// JumpTable
5264/// ::= (TypeAndValue ',' TypeAndValue)*
5265bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5266 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005267 Value *Cond;
5268 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5270 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005271 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5273 return true;
5274
Duncan Sands19d0b472010-02-16 11:11:14 +00005275 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005277
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278 // Parse the jump table pairs.
5279 SmallPtrSet<Value*, 32> SeenCases;
5280 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5281 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005282 Value *Constant;
5283 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005284
Chris Lattnerac161bf2009-01-02 07:01:27 +00005285 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5286 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005287 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005288 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005289
David Blaikie70573dc2014-11-19 07:49:26 +00005290 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005291 return Error(CondLoc, "duplicate case value in switch");
5292 if (!isa<ConstantInt>(Constant))
5293 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005294
Chris Lattner3ed871f2009-10-27 19:13:16 +00005295 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005296 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005297
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005299
Chris Lattner3ed871f2009-10-27 19:13:16 +00005300 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005301 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5302 SI->addCase(Table[i].first, Table[i].second);
5303 Inst = SI;
5304 return false;
5305}
5306
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005307/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005308/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005309/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5310bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005311 LocTy AddrLoc;
5312 Value *Address;
5313 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005314 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5315 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005316 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005317
Duncan Sands19d0b472010-02-16 11:11:14 +00005318 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005319 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005320
Chris Lattner3ed871f2009-10-27 19:13:16 +00005321 // Parse the destination list.
5322 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005323
Chris Lattner3ed871f2009-10-27 19:13:16 +00005324 if (Lex.getKind() != lltok::rsquare) {
5325 BasicBlock *DestBB;
5326 if (ParseTypeAndBasicBlock(DestBB, PFS))
5327 return true;
5328 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005329
Chris Lattner3ed871f2009-10-27 19:13:16 +00005330 while (EatIfPresent(lltok::comma)) {
5331 if (ParseTypeAndBasicBlock(DestBB, PFS))
5332 return true;
5333 DestList.push_back(DestBB);
5334 }
5335 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005336
Chris Lattner3ed871f2009-10-27 19:13:16 +00005337 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5338 return true;
5339
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005340 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005341 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5342 IBI->addDestination(DestList[i]);
5343 Inst = IBI;
5344 return false;
5345}
5346
Chris Lattnerac161bf2009-01-02 07:01:27 +00005347/// ParseInvoke
5348/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5349/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5350bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5351 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005352 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005353 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005354 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005355 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005356 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005357 LocTy RetTypeLoc;
5358 ValID CalleeID;
5359 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005360 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005361
Chris Lattner3ed871f2009-10-27 19:13:16 +00005362 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005363 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005364 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005365 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005366 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5367 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005368 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005369 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005370 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005371 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005372 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005374
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 // If RetType is a non-function pointer type, then this is the short syntax
5376 // for the call, which means that RetType is just the return type. Infer the
5377 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005378 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5379 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005380 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005381 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005382 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5383 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005384
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385 if (!FunctionType::isValidReturnType(RetType))
5386 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005387
Owen Anderson4056ca92009-07-29 22:17:13 +00005388 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005390
David Blaikie41ba2b42015-07-27 23:32:19 +00005391 CalleeID.FTy = Ty;
5392
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393 // Look up the callee.
5394 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005395 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5396 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005397
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005398 // Set up the Attribute for the function.
Reid Kleckner211b1f32017-04-10 20:34:19 +00005399 SmallVector<AttributeList, 8> Attrs;
5400 if (RetAttrs.hasAttributes())
5401 Attrs.push_back(AttributeList::get(RetType->getContext(),
5402 AttributeList::ReturnIndex, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005403
Chris Lattnerac161bf2009-01-02 07:01:27 +00005404 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005405
Chris Lattnerac161bf2009-01-02 07:01:27 +00005406 // Loop through FunctionType's arguments and ensure they are specified
5407 // correctly. Also, gather any parameter attributes.
5408 FunctionType::param_iterator I = Ty->param_begin();
5409 FunctionType::param_iterator E = Ty->param_end();
5410 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005411 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005412 if (I != E) {
5413 ExpectedTy = *I++;
5414 } else if (!Ty->isVarArg()) {
5415 return Error(ArgList[i].Loc, "too many arguments specified");
5416 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005417
Chris Lattnerac161bf2009-01-02 07:01:27 +00005418 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5419 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005420 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005421 Args.push_back(ArgList[i].V);
Reid Kleckner211b1f32017-04-10 20:34:19 +00005422 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5423 AttrBuilder B(ArgList[i].Attrs, i + 1);
5424 Attrs.push_back(AttributeList::get(RetType->getContext(), i + 1, B));
5425 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005426 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005427
Chris Lattnerac161bf2009-01-02 07:01:27 +00005428 if (I != E)
5429 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005430
Reid Kleckner211b1f32017-04-10 20:34:19 +00005431 if (FnAttrs.hasAttributes()) {
5432 if (FnAttrs.hasAlignmentAttr())
5433 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005434
Reid Kleckner211b1f32017-04-10 20:34:19 +00005435 Attrs.push_back(AttributeList::get(RetType->getContext(),
5436 AttributeList::FunctionIndex, FnAttrs));
5437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005438
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005439 // Finish off the Attribute and check them
Reid Klecknerb5180542017-03-21 16:57:19 +00005440 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005441
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005442 InvokeInst *II =
5443 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005444 II->setCallingConv(CC);
5445 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005446 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005447 Inst = II;
5448 return false;
5449}
5450
Bill Wendlingf891bf82011-07-31 06:30:59 +00005451/// ParseResume
5452/// ::= 'resume' TypeAndValue
5453bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5454 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005455 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5456 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005457
Bill Wendlingf891bf82011-07-31 06:30:59 +00005458 ResumeInst *RI = ResumeInst::Create(Exn);
5459 Inst = RI;
5460 return false;
5461}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005462
David Majnemer654e1302015-07-31 17:58:14 +00005463bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5464 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005465 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005466 return true;
5467
5468 while (Lex.getKind() != lltok::rsquare) {
5469 // If this isn't the first argument, we need a comma.
5470 if (!Args.empty() &&
5471 ParseToken(lltok::comma, "expected ',' in argument list"))
5472 return true;
5473
5474 // Parse the argument.
5475 LocTy ArgLoc;
5476 Type *ArgTy = nullptr;
5477 if (ParseType(ArgTy, ArgLoc))
5478 return true;
5479
5480 Value *V;
5481 if (ArgTy->isMetadataTy()) {
5482 if (ParseMetadataAsValue(V, PFS))
5483 return true;
5484 } else {
5485 if (ParseValue(ArgTy, V, PFS))
5486 return true;
5487 }
5488 Args.push_back(V);
5489 }
5490
5491 Lex.Lex(); // Lex the ']'.
5492 return false;
5493}
5494
5495/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005496/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005497bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005498 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005499
David Majnemer8a1c45d2015-12-12 05:38:55 +00005500 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5501 return true;
5502
5503 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005504 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005505
5506 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5507 return true;
5508
5509 BasicBlock *UnwindBB = nullptr;
5510 if (Lex.getKind() == lltok::kw_to) {
5511 Lex.Lex();
5512 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5513 return true;
5514 } else {
5515 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5516 return true;
5517 }
5518 }
5519
David Majnemer8a1c45d2015-12-12 05:38:55 +00005520 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005521 return false;
5522}
5523
5524/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005525/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005526bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005527 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005528
David Majnemer8a1c45d2015-12-12 05:38:55 +00005529 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5530 return true;
5531
5532 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005533 return true;
5534
David Majnemer0bc0eef2015-08-15 02:46:08 +00005535 BasicBlock *BB;
5536 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5537 ParseTypeAndBasicBlock(BB, PFS))
5538 return true;
5539
David Majnemer8a1c45d2015-12-12 05:38:55 +00005540 Inst = CatchReturnInst::Create(CatchPad, BB);
5541 return false;
5542}
5543
5544/// ParseCatchSwitch
5545/// ::= 'catchswitch' within Parent
5546bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5547 Value *ParentPad;
5548 LocTy BBLoc;
5549
5550 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5551 return true;
5552
5553 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5554 Lex.getKind() != lltok::LocalVarID)
5555 return TokError("expected scope value for catchswitch");
5556
5557 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5558 return true;
5559
5560 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5561 return true;
5562
5563 SmallVector<BasicBlock *, 32> Table;
5564 do {
5565 BasicBlock *DestBB;
5566 if (ParseTypeAndBasicBlock(DestBB, PFS))
5567 return true;
5568 Table.push_back(DestBB);
5569 } while (EatIfPresent(lltok::comma));
5570
5571 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5572 return true;
5573
5574 if (ParseToken(lltok::kw_unwind,
5575 "expected 'unwind' after catchswitch scope"))
5576 return true;
5577
5578 BasicBlock *UnwindBB = nullptr;
5579 if (EatIfPresent(lltok::kw_to)) {
5580 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5581 return true;
5582 } else {
5583 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5584 return true;
5585 }
5586
5587 auto *CatchSwitch =
5588 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5589 for (BasicBlock *DestBB : Table)
5590 CatchSwitch->addHandler(DestBB);
5591 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005592 return false;
5593}
5594
5595/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005596/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005597bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005598 Value *CatchSwitch = nullptr;
5599
5600 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5601 return true;
5602
5603 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5604 return TokError("expected scope value for catchpad");
5605
5606 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5607 return true;
5608
David Majnemer654e1302015-07-31 17:58:14 +00005609 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005610 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005611 return true;
5612
David Majnemer8a1c45d2015-12-12 05:38:55 +00005613 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005614 return false;
5615}
5616
David Majnemer654e1302015-07-31 17:58:14 +00005617/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005618/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005619bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005620 Value *ParentPad = nullptr;
5621
5622 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5623 return true;
5624
5625 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5626 Lex.getKind() != lltok::LocalVarID)
5627 return TokError("expected scope value for cleanuppad");
5628
5629 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5630 return true;
5631
David Majnemer654e1302015-07-31 17:58:14 +00005632 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005633 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005634 return true;
5635
David Majnemer8a1c45d2015-12-12 05:38:55 +00005636 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005637 return false;
5638}
5639
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640//===----------------------------------------------------------------------===//
5641// Binary Operators.
5642//===----------------------------------------------------------------------===//
5643
5644/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005645/// ::= ArithmeticOps TypeAndValue ',' Value
5646///
5647/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5648/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005649bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005650 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005651 LocTy Loc; Value *LHS, *RHS;
5652 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5653 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5654 ParseValue(LHS->getType(), RHS, PFS))
5655 return true;
5656
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005657 bool Valid;
5658 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005659 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005660 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005661 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5662 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005663 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005664 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5665 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005667
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005668 if (!Valid)
5669 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005670
Chris Lattnerac161bf2009-01-02 07:01:27 +00005671 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5672 return false;
5673}
5674
5675/// ParseLogical
5676/// ::= ArithmeticOps TypeAndValue ',' Value {
5677bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5678 unsigned Opc) {
5679 LocTy Loc; Value *LHS, *RHS;
5680 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5681 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5682 ParseValue(LHS->getType(), RHS, PFS))
5683 return true;
5684
Duncan Sands9dff9be2010-02-15 16:12:20 +00005685 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005686 return Error(Loc,"instruction requires integer or integer vector operands");
5687
5688 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5689 return false;
5690}
5691
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692/// ParseCompare
5693/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5694/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005695bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5696 unsigned Opc) {
5697 // Parse the integer/fp comparison predicate.
5698 LocTy Loc;
5699 unsigned Pred;
5700 Value *LHS, *RHS;
5701 if (ParseCmpPredicate(Pred, Opc) ||
5702 ParseTypeAndValue(LHS, Loc, PFS) ||
5703 ParseToken(lltok::comma, "expected ',' after compare value") ||
5704 ParseValue(LHS->getType(), RHS, PFS))
5705 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005706
Chris Lattnerac161bf2009-01-02 07:01:27 +00005707 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005708 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005709 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005710 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005711 } else {
5712 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005713 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005714 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005716 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 }
5718 return false;
5719}
5720
5721//===----------------------------------------------------------------------===//
5722// Other Instructions.
5723//===----------------------------------------------------------------------===//
5724
5725
5726/// ParseCast
5727/// ::= CastOpc TypeAndValue 'to' Type
5728bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5729 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005730 LocTy Loc;
5731 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005732 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005733 if (ParseTypeAndValue(Op, Loc, PFS) ||
5734 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5735 ParseType(DestTy))
5736 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005737
Chris Lattner89d856e2009-03-01 00:53:13 +00005738 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5739 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005740 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005741 getTypeString(Op->getType()) + "' to '" +
5742 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005743 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005744 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5745 return false;
5746}
5747
5748/// ParseSelect
5749/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5750bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5751 LocTy Loc;
5752 Value *Op0, *Op1, *Op2;
5753 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5754 ParseToken(lltok::comma, "expected ',' after select condition") ||
5755 ParseTypeAndValue(Op1, PFS) ||
5756 ParseToken(lltok::comma, "expected ',' after select value") ||
5757 ParseTypeAndValue(Op2, PFS))
5758 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005759
Chris Lattnerac161bf2009-01-02 07:01:27 +00005760 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5761 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005762
Chris Lattnerac161bf2009-01-02 07:01:27 +00005763 Inst = SelectInst::Create(Op0, Op1, Op2);
5764 return false;
5765}
5766
Chris Lattnerb55ab542009-01-05 08:18:44 +00005767/// ParseVA_Arg
5768/// ::= 'va_arg' TypeAndValue ',' Type
5769bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005770 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005771 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005772 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005773 if (ParseTypeAndValue(Op, PFS) ||
5774 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005775 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005776 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005777
Chris Lattnerb55ab542009-01-05 08:18:44 +00005778 if (!EltTy->isFirstClassType())
5779 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005780
5781 Inst = new VAArgInst(Op, EltTy);
5782 return false;
5783}
5784
5785/// ParseExtractElement
5786/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5787bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5788 LocTy Loc;
5789 Value *Op0, *Op1;
5790 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5791 ParseToken(lltok::comma, "expected ',' after extract value") ||
5792 ParseTypeAndValue(Op1, PFS))
5793 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005794
Chris Lattnerac161bf2009-01-02 07:01:27 +00005795 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5796 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005797
Eric Christopherc9742252009-07-25 02:28:41 +00005798 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005799 return false;
5800}
5801
5802/// ParseInsertElement
5803/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5804bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5805 LocTy Loc;
5806 Value *Op0, *Op1, *Op2;
5807 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5808 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5809 ParseTypeAndValue(Op1, PFS) ||
5810 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5811 ParseTypeAndValue(Op2, PFS))
5812 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005813
Chris Lattnerac161bf2009-01-02 07:01:27 +00005814 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005815 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005816
Chris Lattnerac161bf2009-01-02 07:01:27 +00005817 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5818 return false;
5819}
5820
5821/// ParseShuffleVector
5822/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5823bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5824 LocTy Loc;
5825 Value *Op0, *Op1, *Op2;
5826 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5827 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5828 ParseTypeAndValue(Op1, PFS) ||
5829 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5830 ParseTypeAndValue(Op2, PFS))
5831 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005832
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005834 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005835
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5837 return false;
5838}
5839
5840/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005841/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005842int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005843 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005845
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005846 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005847 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5848 ParseValue(Ty, Op0, PFS) ||
5849 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005850 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005851 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5852 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005853
Chris Lattnerf4f03422009-12-30 05:27:33 +00005854 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005856
5857 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005858 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005859
Chris Lattner3822f632009-01-02 08:05:26 +00005860 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005861 break;
5862
Chris Lattnerf4f03422009-12-30 05:27:33 +00005863 if (Lex.getKind() == lltok::MetadataVar) {
5864 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005865 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005866 }
Devang Patel8f842d32009-10-16 18:45:49 +00005867
Chris Lattner3822f632009-01-02 08:05:26 +00005868 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005869 ParseValue(Ty, Op0, PFS) ||
5870 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005871 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005872 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5873 return true;
5874 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005875
Chris Lattnerac161bf2009-01-02 07:01:27 +00005876 if (!Ty->isFirstClassType())
5877 return Error(TypeLoc, "phi node must have first class type");
5878
Jay Foad52131342011-03-30 11:28:46 +00005879 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5881 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5882 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005883 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884}
5885
Bill Wendlingfae14752011-08-12 20:24:12 +00005886/// ParseLandingPad
5887/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5888/// Clause
5889/// ::= 'catch' TypeAndValue
5890/// ::= 'filter'
5891/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5892bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005893 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005894
David Majnemer7fddecc2015-06-17 20:52:32 +00005895 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005896 return true;
5897
David Majnemer7fddecc2015-06-17 20:52:32 +00005898 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005899 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5900
5901 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5902 LandingPadInst::ClauseType CT;
5903 if (EatIfPresent(lltok::kw_catch))
5904 CT = LandingPadInst::Catch;
5905 else if (EatIfPresent(lltok::kw_filter))
5906 CT = LandingPadInst::Filter;
5907 else
5908 return TokError("expected 'catch' or 'filter' clause type");
5909
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005910 Value *V;
5911 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005912 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005913 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005914
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005915 // A 'catch' type expects a non-array constant. A filter clause expects an
5916 // array constant.
5917 if (CT == LandingPadInst::Catch) {
5918 if (isa<ArrayType>(V->getType()))
5919 Error(VLoc, "'catch' clause has an invalid type");
5920 } else {
5921 if (!isa<ArrayType>(V->getType()))
5922 Error(VLoc, "'filter' clause has an invalid type");
5923 }
5924
Owen Andersonf8f259d2015-03-09 07:13:42 +00005925 Constant *CV = dyn_cast<Constant>(V);
5926 if (!CV)
5927 return Error(VLoc, "clause argument must be a constant");
5928 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005929 }
5930
Owen Andersonf8f259d2015-03-09 07:13:42 +00005931 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005932 return false;
5933}
5934
Chris Lattnerac161bf2009-01-02 07:01:27 +00005935/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005936/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5937/// OptionalAttrs Type Value ParameterList OptionalAttrs
5938/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5939/// OptionalAttrs Type Value ParameterList OptionalAttrs
5940/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5941/// OptionalAttrs Type Value ParameterList OptionalAttrs
5942/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5943/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005944bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005945 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005946 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005947 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005948 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005949 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005950 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005951 LocTy RetTypeLoc;
5952 ValID CalleeID;
5953 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005954 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005955 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005956
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005957 if (TCK != CallInst::TCK_None &&
5958 ParseToken(lltok::kw_call,
5959 "expected 'tail call', 'musttail call', or 'notail call'"))
5960 return true;
5961
5962 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5963
5964 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005965 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005966 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005967 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5968 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005969 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5970 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005971 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005972
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005973 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5974 return Error(CallLoc, "fast-math-flags specified for call without "
5975 "floating-point scalar or vector return type");
5976
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977 // If RetType is a non-function pointer type, then this is the short syntax
5978 // for the call, which means that RetType is just the return type. Infer the
5979 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005980 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5981 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005982 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005983 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005984 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5985 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005986
Chris Lattnerac161bf2009-01-02 07:01:27 +00005987 if (!FunctionType::isValidReturnType(RetType))
5988 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005989
Owen Anderson4056ca92009-07-29 22:17:13 +00005990 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005991 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005992
David Blaikie41ba2b42015-07-27 23:32:19 +00005993 CalleeID.FTy = Ty;
5994
Chris Lattnerac161bf2009-01-02 07:01:27 +00005995 // Look up the callee.
5996 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005997 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5998 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005999
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006000 // Set up the Attribute for the function.
Reid Kleckner211b1f32017-04-10 20:34:19 +00006001 SmallVector<AttributeList, 8> Attrs;
6002 if (RetAttrs.hasAttributes())
6003 Attrs.push_back(AttributeList::get(RetType->getContext(),
6004 AttributeList::ReturnIndex, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006005
Chris Lattnerac161bf2009-01-02 07:01:27 +00006006 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006007
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008 // Loop through FunctionType's arguments and ensure they are specified
6009 // correctly. Also, gather any parameter attributes.
6010 FunctionType::param_iterator I = Ty->param_begin();
6011 FunctionType::param_iterator E = Ty->param_end();
6012 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006013 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006014 if (I != E) {
6015 ExpectedTy = *I++;
6016 } else if (!Ty->isVarArg()) {
6017 return Error(ArgList[i].Loc, "too many arguments specified");
6018 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006019
Chris Lattnerac161bf2009-01-02 07:01:27 +00006020 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6021 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006022 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006023 Args.push_back(ArgList[i].V);
Reid Kleckner211b1f32017-04-10 20:34:19 +00006024 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
6025 AttrBuilder B(ArgList[i].Attrs, i + 1);
6026 Attrs.push_back(AttributeList::get(RetType->getContext(), i + 1, B));
6027 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006029
Chris Lattnerac161bf2009-01-02 07:01:27 +00006030 if (I != E)
6031 return Error(CallLoc, "not enough parameters specified for call");
6032
Reid Kleckner211b1f32017-04-10 20:34:19 +00006033 if (FnAttrs.hasAttributes()) {
6034 if (FnAttrs.hasAlignmentAttr())
6035 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006036
Reid Kleckner211b1f32017-04-10 20:34:19 +00006037 Attrs.push_back(AttributeList::get(RetType->getContext(),
6038 AttributeList::FunctionIndex, FnAttrs));
6039 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006040
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006041 // Finish off the Attribute and check them
Reid Klecknerb5180542017-03-21 16:57:19 +00006042 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006043
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006044 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006045 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006046 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006047 if (FMF.any())
6048 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006049 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006050 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006051 Inst = CI;
6052 return false;
6053}
6054
6055//===----------------------------------------------------------------------===//
6056// Memory Instructions.
6057//===----------------------------------------------------------------------===//
6058
6059/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006060/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6061/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006062int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006063 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006064 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006065 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006066 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006067 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006068
6069 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006070 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006071
David Majnemera3b0eb22015-02-16 08:38:03 +00006072 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006073
David Majnemera3b0eb22015-02-16 08:38:03 +00006074 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6075 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006076
Chris Lattnerb2f39502009-12-30 05:44:30 +00006077 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006078 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006079 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006080 if (ParseOptionalAlignment(Alignment))
6081 return true;
6082 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6083 return true;
6084 } else if (Lex.getKind() == lltok::kw_addrspace) {
6085 ASLoc = Lex.getLoc();
6086 if (ParseOptionalAddrSpace(AddrSpace))
6087 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006088 } else if (Lex.getKind() == lltok::MetadataVar) {
6089 AteExtraComma = true;
6090 } else {
6091 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006092 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6093 (!AteExtraComma &&
6094 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006095 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006096 }
6097 }
6098
Dan Gohman2140a742010-05-28 01:14:11 +00006099 if (Size && !Size->getType()->isIntegerTy())
6100 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006101
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006102 const DataLayout &DL = M->getDataLayout();
6103 unsigned AS = DL.getAllocaAddrSpace();
6104 if (AS != AddrSpace) {
6105 // TODO: In the future it should be possible to specify addrspace per-alloca.
6106 return Error(ASLoc, "address space must match datalayout");
6107 }
6108
6109 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006110 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006111 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006112 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006113 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006114}
6115
6116/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006117/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006118/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006119/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006120int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006121 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006122 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006123 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006124 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006125 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006126 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006127
6128 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006129 isAtomic = true;
6130 Lex.Lex();
6131 }
6132
Chris Lattnerbc639292011-11-27 06:56:53 +00006133 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006134 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006135 isVolatile = true;
6136 Lex.Lex();
6137 }
6138
David Blaikie15d9a4c2015-04-06 20:59:48 +00006139 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006140 LocTy ExplicitTypeLoc = Lex.getLoc();
6141 if (ParseType(Ty) ||
6142 ParseToken(lltok::comma, "expected comma after load's type") ||
6143 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006144 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006145 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6146 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006147
David Blaikie15d9a4c2015-04-06 20:59:48 +00006148 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006149 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006150 if (isAtomic && !Alignment)
6151 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006152 if (Ordering == AtomicOrdering::Release ||
6153 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006154 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006155
David Blaikiea79ac142015-02-27 21:17:42 +00006156 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6157 return Error(ExplicitTypeLoc,
6158 "explicit pointee type doesn't match operand's pointee type");
6159
David Blaikie15d9a4c2015-04-06 20:59:48 +00006160 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006161 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006162}
6163
6164/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006165
6166/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6167/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006168/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006169int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006170 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006171 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006172 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006173 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006174 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006175 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006176
6177 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006178 isAtomic = true;
6179 Lex.Lex();
6180 }
6181
Chris Lattnerbc639292011-11-27 06:56:53 +00006182 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006183 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006184 isVolatile = true;
6185 Lex.Lex();
6186 }
6187
Chris Lattnerac161bf2009-01-02 07:01:27 +00006188 if (ParseTypeAndValue(Val, Loc, PFS) ||
6189 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006190 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006191 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006192 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006193 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006194
Duncan Sands19d0b472010-02-16 11:11:14 +00006195 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006196 return Error(PtrLoc, "store operand must be a pointer");
6197 if (!Val->getType()->isFirstClassType())
6198 return Error(Loc, "store operand must be a first class value");
6199 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6200 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006201 if (isAtomic && !Alignment)
6202 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006203 if (Ordering == AtomicOrdering::Acquire ||
6204 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006205 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006206
Eli Friedman59b66882011-08-09 23:02:53 +00006207 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006208 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006209}
6210
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006211/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006212/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6213/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006214int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006215 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6216 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006217 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6218 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006219 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006220 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006221 bool isWeak = false;
6222
6223 if (EatIfPresent(lltok::kw_weak))
6224 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006225
6226 if (EatIfPresent(lltok::kw_volatile))
6227 isVolatile = true;
6228
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006229 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6230 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6231 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6232 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6233 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006234 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6235 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006236 return true;
6237
JF Bastien800f87a2016-04-06 21:19:33 +00006238 if (SuccessOrdering == AtomicOrdering::Unordered ||
6239 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006240 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006241 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6242 return TokError("cmpxchg failure argument shall be no stronger than the "
6243 "success argument");
6244 if (FailureOrdering == AtomicOrdering::Release ||
6245 FailureOrdering == AtomicOrdering::AcquireRelease)
6246 return TokError(
6247 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006248 if (!Ptr->getType()->isPointerTy())
6249 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6250 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6251 return Error(CmpLoc, "compare value and pointer type do not match");
6252 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6253 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006254 if (!New->getType()->isFirstClassType())
6255 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006256 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6257 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006258 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006259 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006260 Inst = CXI;
6261 return AteExtraComma ? InstExtraComma : InstNormal;
6262}
6263
6264/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006265/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6266/// 'singlethread'? AtomicOrdering
6267int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006268 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6269 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006270 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006271 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006272 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006273 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006274
6275 if (EatIfPresent(lltok::kw_volatile))
6276 isVolatile = true;
6277
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006278 switch (Lex.getKind()) {
6279 default: return TokError("expected binary operation in atomicrmw");
6280 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6281 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6282 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6283 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6284 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6285 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6286 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6287 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6288 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6289 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6290 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6291 }
6292 Lex.Lex(); // Eat the operation.
6293
6294 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6295 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6296 ParseTypeAndValue(Val, ValLoc, PFS) ||
6297 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6298 return true;
6299
JF Bastien800f87a2016-04-06 21:19:33 +00006300 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006301 return TokError("atomicrmw cannot be unordered");
6302 if (!Ptr->getType()->isPointerTy())
6303 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6304 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6305 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6306 if (!Val->getType()->isIntegerTy())
6307 return Error(ValLoc, "atomicrmw operand must be an integer");
6308 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6309 if (Size < 8 || (Size & (Size - 1)))
6310 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6311 " integer");
6312
6313 AtomicRMWInst *RMWI =
6314 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6315 RMWI->setVolatile(isVolatile);
6316 Inst = RMWI;
6317 return AteExtraComma ? InstExtraComma : InstNormal;
6318}
6319
Eli Friedmanfee02c62011-07-25 23:16:38 +00006320/// ParseFence
6321/// ::= 'fence' 'singlethread'? AtomicOrdering
6322int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006323 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006324 SynchronizationScope Scope = CrossThread;
6325 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6326 return true;
6327
JF Bastien800f87a2016-04-06 21:19:33 +00006328 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006329 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006330 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006331 return TokError("fence cannot be monotonic");
6332
6333 Inst = new FenceInst(Context, Ordering, Scope);
6334 return InstNormal;
6335}
6336
Chris Lattnerac161bf2009-01-02 07:01:27 +00006337/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006338/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006339int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006340 Value *Ptr = nullptr;
6341 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006342 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006343
Dan Gohman16cbbe42009-07-29 15:58:36 +00006344 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006345
David Blaikie79e6c742015-02-27 19:29:02 +00006346 Type *Ty = nullptr;
6347 LocTy ExplicitTypeLoc = Lex.getLoc();
6348 if (ParseType(Ty) ||
6349 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6350 ParseTypeAndValue(Ptr, Loc, PFS))
6351 return true;
6352
Eli Benderskyd9806682013-04-22 17:03:42 +00006353 Type *BaseType = Ptr->getType();
6354 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6355 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006356 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006357
David Blaikie8d757942015-03-09 23:08:44 +00006358 if (Ty != BasePointerType->getElementType())
6359 return Error(ExplicitTypeLoc,
6360 "explicit pointee type doesn't match operand's pointee type");
6361
Chris Lattnerac161bf2009-01-02 07:01:27 +00006362 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006363 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006364 // GEP returns a vector of pointers if at least one of parameters is a vector.
6365 // All vector parameters should have the same vector width.
6366 unsigned GEPWidth = BaseType->isVectorTy() ?
6367 BaseType->getVectorNumElements() : 0;
6368
Chris Lattner3822f632009-01-02 08:05:26 +00006369 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006370 if (Lex.getKind() == lltok::MetadataVar) {
6371 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006372 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006373 }
Chris Lattner3822f632009-01-02 08:05:26 +00006374 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006375 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006376 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006377
Nadav Rotem3924cb02011-12-05 06:29:09 +00006378 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006379 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6380 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006381 return Error(EltLoc,
6382 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006383 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006384 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006385 Indices.push_back(Val);
6386 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006387
Craig Toppere3dcce92015-08-01 22:20:21 +00006388 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006389 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006390 return Error(Loc, "base element of getelementptr must be sized");
6391
David Blaikied33bad32015-04-17 22:32:13 +00006392 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006393 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006394 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006395 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006396 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006397 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006398}
6399
6400/// ParseExtractValue
6401/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006402int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006403 Value *Val; LocTy Loc;
6404 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006405 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006406 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006407 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006408 return true;
6409
Chris Lattner392be582010-02-12 20:49:41 +00006410 if (!Val->getType()->isAggregateType())
6411 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006412
Jay Foad57aa6362011-07-13 10:26:04 +00006413 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006414 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006415 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006416 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006417}
6418
6419/// ParseInsertValue
6420/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006421int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006422 Value *Val0, *Val1; LocTy Loc0, Loc1;
6423 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006424 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006425 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6426 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6427 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006428 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006429 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006430
Chris Lattner392be582010-02-12 20:49:41 +00006431 if (!Val0->getType()->isAggregateType())
6432 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006433
David Majnemer30074532015-02-11 07:43:58 +00006434 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6435 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006436 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006437 if (IndexedType != Val1->getType())
6438 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6439 getTypeString(Val1->getType()) + "' instead of '" +
6440 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006441 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006442 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006443}
Nick Lewycky49f89192009-04-04 07:22:01 +00006444
6445//===----------------------------------------------------------------------===//
6446// Embedded metadata.
6447//===----------------------------------------------------------------------===//
6448
6449/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006450/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006451/// Element
6452/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006453bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006454 if (ParseToken(lltok::lbrace, "expected '{' here"))
6455 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006456
Dan Gohman1e0213a2010-07-13 19:33:27 +00006457 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006458 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006459 return false;
6460
Nick Lewycky49f89192009-04-04 07:22:01 +00006461 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006462 // Null is a special case since it is typeless.
6463 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006464 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006465 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006466 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006467
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006468 Metadata *MD;
6469 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006470 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006471 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006472 } while (EatIfPresent(lltok::comma));
6473
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006474 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006475}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006476
6477//===----------------------------------------------------------------------===//
6478// Use-list order directives.
6479//===----------------------------------------------------------------------===//
6480bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6481 SMLoc Loc) {
6482 if (V->use_empty())
6483 return Error(Loc, "value has no uses");
6484
6485 unsigned NumUses = 0;
6486 SmallDenseMap<const Use *, unsigned, 16> Order;
6487 for (const Use &U : V->uses()) {
6488 if (++NumUses > Indexes.size())
6489 break;
6490 Order[&U] = Indexes[NumUses - 1];
6491 }
6492 if (NumUses < 2)
6493 return Error(Loc, "value only has one use");
6494 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6495 return Error(Loc, "wrong number of indexes, expected " +
6496 Twine(std::distance(V->use_begin(), V->use_end())));
6497
6498 V->sortUseList([&](const Use &L, const Use &R) {
6499 return Order.lookup(&L) < Order.lookup(&R);
6500 });
6501 return false;
6502}
6503
6504/// ParseUseListOrderIndexes
6505/// ::= '{' uint32 (',' uint32)+ '}'
6506bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6507 SMLoc Loc = Lex.getLoc();
6508 if (ParseToken(lltok::lbrace, "expected '{' here"))
6509 return true;
6510 if (Lex.getKind() == lltok::rbrace)
6511 return Lex.Error("expected non-empty list of uselistorder indexes");
6512
6513 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6514 // indexes should be distinct numbers in the range [0, size-1], and should
6515 // not be in order.
6516 unsigned Offset = 0;
6517 unsigned Max = 0;
6518 bool IsOrdered = true;
6519 assert(Indexes.empty() && "Expected empty order vector");
6520 do {
6521 unsigned Index;
6522 if (ParseUInt32(Index))
6523 return true;
6524
6525 // Update consistency checks.
6526 Offset += Index - Indexes.size();
6527 Max = std::max(Max, Index);
6528 IsOrdered &= Index == Indexes.size();
6529
6530 Indexes.push_back(Index);
6531 } while (EatIfPresent(lltok::comma));
6532
6533 if (ParseToken(lltok::rbrace, "expected '}' here"))
6534 return true;
6535
6536 if (Indexes.size() < 2)
6537 return Error(Loc, "expected >= 2 uselistorder indexes");
6538 if (Offset != 0 || Max >= Indexes.size())
6539 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6540 if (IsOrdered)
6541 return Error(Loc, "expected uselistorder indexes to change the order");
6542
6543 return false;
6544}
6545
6546/// ParseUseListOrder
6547/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6548bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6549 SMLoc Loc = Lex.getLoc();
6550 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6551 return true;
6552
6553 Value *V;
6554 SmallVector<unsigned, 16> Indexes;
6555 if (ParseTypeAndValue(V, PFS) ||
6556 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6557 ParseUseListOrderIndexes(Indexes))
6558 return true;
6559
6560 return sortUseListOrder(V, Indexes, Loc);
6561}
6562
6563/// ParseUseListOrderBB
6564/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6565bool LLParser::ParseUseListOrderBB() {
6566 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6567 SMLoc Loc = Lex.getLoc();
6568 Lex.Lex();
6569
6570 ValID Fn, Label;
6571 SmallVector<unsigned, 16> Indexes;
6572 if (ParseValID(Fn) ||
6573 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6574 ParseValID(Label) ||
6575 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6576 ParseUseListOrderIndexes(Indexes))
6577 return true;
6578
6579 // Check the function.
6580 GlobalValue *GV;
6581 if (Fn.Kind == ValID::t_GlobalName)
6582 GV = M->getNamedValue(Fn.StrVal);
6583 else if (Fn.Kind == ValID::t_GlobalID)
6584 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6585 else
6586 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6587 if (!GV)
6588 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6589 auto *F = dyn_cast<Function>(GV);
6590 if (!F)
6591 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6592 if (F->isDeclaration())
6593 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6594
6595 // Check the basic block.
6596 if (Label.Kind == ValID::t_LocalID)
6597 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6598 if (Label.Kind != ValID::t_LocalName)
6599 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006600 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006601 if (!V)
6602 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6603 if (!isa<BasicBlock>(V))
6604 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6605
6606 return sortUseListOrder(V, Indexes, Loc);
6607}