blob: 78de0d65f25d17b76c5e780ae93fb1248f2d0928 [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"
Reid Kleckner324c99d2017-04-10 20:18:10 +000022#include "llvm/IR/AttributeSetNode.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000045#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000046#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000047#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000048#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000049#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000050#include <algorithm>
51#include <cassert>
52#include <cstring>
53#include <iterator>
54#include <vector>
55
Chris Lattnerac161bf2009-01-02 07:01:27 +000056using namespace llvm;
57
Chris Lattner229907c2011-07-18 04:54:35 +000058static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000059 std::string Result;
60 raw_string_ostream Tmp(Result);
61 Tmp << *T;
62 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000063}
64
Chris Lattner3822f632009-01-02 08:05:26 +000065/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000066bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000067 // Prime the lexer.
68 Lex.Lex();
69
Mehdi Amini50af49f2016-04-02 03:46:17 +000070 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000071 return Error(
72 Lex.getLoc(),
73 "Can't read textual IR with a Context that discards named Values");
74
Chris Lattnerad6f3352009-01-04 20:44:11 +000075 return ParseTopLevelEntities() ||
76 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000077}
78
Alex Lorenz1de2acd2015-08-21 21:32:39 +000079bool LLParser::parseStandaloneConstantValue(Constant *&C,
80 const SlotMapping *Slots) {
81 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000082 Lex.Lex();
83
84 Type *Ty = nullptr;
85 if (ParseType(Ty) || parseConstantValue(Ty, C))
86 return true;
87 if (Lex.getKind() != lltok::Eof)
88 return Error(Lex.getLoc(), "expected end of string");
89 return false;
90}
91
Quentin Colombetdafed5d2016-03-08 00:37:07 +000092bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
93 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000094 restoreParsingState(Slots);
95 Lex.Lex();
96
Quentin Colombetdafed5d2016-03-08 00:37:07 +000097 Read = 0;
98 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000099 Ty = nullptr;
100 if (ParseType(Ty))
101 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000102 SMLoc End = Lex.getLoc();
103 Read = End.getPointer() - Start.getPointer();
104
Quentin Colombet81e72b42016-03-07 22:09:05 +0000105 return false;
106}
107
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000108void LLParser::restoreParsingState(const SlotMapping *Slots) {
109 if (!Slots)
110 return;
111 NumberedVals = Slots->GlobalValues;
112 NumberedMetadata = Slots->MetadataNodes;
113 for (const auto &I : Slots->NamedTypes)
114 NamedTypes.insert(
115 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
116 for (const auto &I : Slots->Types)
117 NumberedTypes.insert(
118 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
119}
120
Chris Lattnerac161bf2009-01-02 07:01:27 +0000121/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
122/// module.
123bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000124 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000128 AttrBuilder B;
129
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000132
133 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000134 AttributeList AS = Fn->getAttributes();
Reid Kleckner324c99d2017-04-10 20:18:10 +0000135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
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 Kleckner324c99d2017-04-10 20:18:10 +0000153 AttrBuilder FnAttrs(AS.getFnAttributes());
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000155 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000156 AS = AS.addAttributes(
157 Context, AttributeList::FunctionIndex,
158 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000159 CI->setAttributes(AS);
160 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000161 AttributeList AS = II->getAttributes();
Reid Kleckner324c99d2017-04-10 20:18:10 +0000162 AttrBuilder FnAttrs(AS.getFnAttributes());
163 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000164 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000165 AS = AS.addAttributes(
166 Context, AttributeList::FunctionIndex,
167 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000168 II->setAttributes(AS);
169 } else {
170 llvm_unreachable("invalid object with forward attribute group reference");
171 }
172 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000173
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000179
David Majnemer19b51052015-02-11 07:43:56 +0000180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
195
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
199 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000204 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Devang Pateld2541152009-07-08 19:23:54 +0000206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
215 }
Devang Pateld2541152009-07-08 19:23:54 +0000216
Mehdi Aminie4709272016-09-14 22:29:59 +0000217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000224
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000228
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
237 }
238 }
239
Manman Ren8b4306c2013-12-02 21:29:56 +0000240 UpgradeDebugInfo(*M);
241
Manman Renb5d7ff42016-05-25 23:14:48 +0000242 UpgradeModuleFlags(*M);
243
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000244 if (!Slots)
245 return false;
246 // Initialize the slot mapping.
247 // Because by this point we've parsed and validated everything, we can "steal"
248 // the mapping from LLParser as it doesn't need it anymore.
249 Slots->GlobalValues = std::move(NumberedVals);
250 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000251 for (const auto &I : NamedTypes)
252 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
253 for (const auto &I : NumberedTypes)
254 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000255
Chris Lattnerac161bf2009-01-02 07:01:27 +0000256 return false;
257}
258
259//===----------------------------------------------------------------------===//
260// Top-Level Entities
261//===----------------------------------------------------------------------===//
262
263bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000264 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 switch (Lex.getKind()) {
266 default: return TokError("expected top-level entity");
267 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 case lltok::kw_declare: if (ParseDeclare()) return true; break;
269 case lltok::kw_define: if (ParseDefine()) return true; break;
270 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
271 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000272 case lltok::kw_source_filename:
273 if (ParseSourceFileName())
274 return true;
275 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000276 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000277 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000278 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000279 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000281 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000282 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000283 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000284 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000285 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
286 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000287 if (ParseUseListOrderBB())
288 return true;
289 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 }
291 }
292}
293
Chris Lattnerac161bf2009-01-02 07:01:27 +0000294/// toplevelentity
295/// ::= 'module' 'asm' STRINGCONSTANT
296bool LLParser::ParseModuleAsm() {
297 assert(Lex.getKind() == lltok::kw_module);
298 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000299
300 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000301 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
302 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000303
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000304 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305 return false;
306}
307
308/// toplevelentity
309/// ::= 'target' 'triple' '=' STRINGCONSTANT
310/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
311bool LLParser::ParseTargetDefinition() {
312 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000313 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 switch (Lex.Lex()) {
315 default: return TokError("unknown target property");
316 case lltok::kw_triple:
317 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000318 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
319 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000321 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return false;
323 case lltok::kw_datalayout:
324 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000325 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
326 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000328 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return false;
330 }
331}
332
Bill Wendling706d3d62012-11-28 08:41:48 +0000333/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000334/// ::= 'source_filename' '=' STRINGCONSTANT
335bool LLParser::ParseSourceFileName() {
336 assert(Lex.getKind() == lltok::kw_source_filename);
337 std::string Str;
338 Lex.Lex();
339 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
340 ParseStringConstant(Str))
341 return true;
342 M->setSourceFileName(Str);
343 return false;
344}
345
346/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000347/// ::= 'deplibs' '=' '[' ']'
348/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
349/// FIXME: Remove in 4.0. Currently parse, but ignore.
350bool LLParser::ParseDepLibs() {
351 assert(Lex.getKind() == lltok::kw_deplibs);
352 Lex.Lex();
353 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
354 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
355 return true;
356
357 if (EatIfPresent(lltok::rsquare))
358 return false;
359
360 do {
361 std::string Str;
362 if (ParseStringConstant(Str)) return true;
363 } while (EatIfPresent(lltok::comma));
364
365 return ParseToken(lltok::rsquare, "expected ']' at end of list");
366}
367
Dan Gohman466876b2009-08-12 23:32:33 +0000368/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000369/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000371 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000372 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000373 Lex.Lex(); // eat LocalVarID;
374
375 if (ParseToken(lltok::equal, "expected '=' after name") ||
376 ParseToken(lltok::kw_type, "expected 'type' after '='"))
377 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378
Craig Topper2617dcc2014-04-15 06:32:26 +0000379 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000380 if (ParseStructDefinition(TypeLoc, "",
381 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000382
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383 if (!isa<StructType>(Result)) {
384 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
385 if (Entry.first)
386 return Error(TypeLoc, "non-struct types may not be recursive");
387 Entry.first = Result;
388 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000390
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391 return false;
392}
393
394/// toplevelentity
395/// ::= LocalVar '=' 'type' type
396bool LLParser::ParseNamedType() {
397 std::string Name = Lex.getStrVal();
398 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000399 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000400
Chris Lattner3822f632009-01-02 08:05:26 +0000401 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000402 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000403 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000404
Craig Topper2617dcc2014-04-15 06:32:26 +0000405 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 if (ParseStructDefinition(NameLoc, Name,
407 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 if (!isa<StructType>(Result)) {
410 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
411 if (Entry.first)
412 return Error(NameLoc, "non-struct types may not be recursive");
413 Entry.first = Result;
414 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000415 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000417 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000418}
419
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420/// toplevelentity
421/// ::= 'declare' FunctionHeader
422bool LLParser::ParseDeclare() {
423 assert(Lex.getKind() == lltok::kw_declare);
424 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000425
Peter Collingbourne21521892016-06-21 23:42:48 +0000426 std::vector<std::pair<unsigned, MDNode *>> MDs;
427 while (Lex.getKind() == lltok::MetadataVar) {
428 unsigned MDK;
429 MDNode *N;
430 if (ParseMetadataAttachment(MDK, N))
431 return true;
432 MDs.push_back({MDK, N});
433 }
434
Chris Lattnerac161bf2009-01-02 07:01:27 +0000435 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000436 if (ParseFunctionHeader(F, false))
437 return true;
438 for (auto &MD : MDs)
439 F->addMetadata(MD.first, *MD.second);
440 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441}
442
443/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000444/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445bool LLParser::ParseDefine() {
446 assert(Lex.getKind() == lltok::kw_define);
447 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000448
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000450 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000451 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000452 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000453}
454
Chris Lattner3822f632009-01-02 08:05:26 +0000455/// ParseGlobalType
456/// ::= 'constant'
457/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458bool LLParser::ParseGlobalType(bool &IsConstant) {
459 if (Lex.getKind() == lltok::kw_constant)
460 IsConstant = true;
461 else if (Lex.getKind() == lltok::kw_global)
462 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000463 else {
464 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000466 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 Lex.Lex();
468 return false;
469}
470
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000471bool LLParser::ParseOptionalUnnamedAddr(
472 GlobalVariable::UnnamedAddr &UnnamedAddr) {
473 if (EatIfPresent(lltok::kw_unnamed_addr))
474 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
475 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
476 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
477 else
478 UnnamedAddr = GlobalValue::UnnamedAddr::None;
479 return false;
480}
481
Dan Gohman466876b2009-08-12 23:32:33 +0000482/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000483/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000484/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000486/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000487/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
488/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000489bool LLParser::ParseUnnamedGlobal() {
490 unsigned VarID = NumberedVals.size();
491 std::string Name;
492 LocTy NameLoc = Lex.getLoc();
493
494 // Handle the GlobalID form.
495 if (Lex.getKind() == lltok::GlobalID) {
496 if (Lex.getUIntVal() != VarID)
497 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000498 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000499 Lex.Lex(); // eat GlobalID;
500
501 if (ParseToken(lltok::equal, "expected '=' after name"))
502 return true;
503 }
504
505 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000506 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000507 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000508 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000509 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000510 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000511 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000512
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000513 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000514 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000515 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000516
517 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
518 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000519}
520
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000522/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000523/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
524/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525bool LLParser::ParseNamedGlobal() {
526 assert(Lex.getKind() == lltok::GlobalVar);
527 LocTy NameLoc = Lex.getLoc();
528 std::string Name = Lex.getStrVal();
529 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000530
Chris Lattnerac161bf2009-01-02 07:01:27 +0000531 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000532 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000533 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000534 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000535 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000536 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000537 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000538 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000539
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000540 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000541 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000542 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000543
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000544 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
545 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000546}
547
David Majnemerdad0a642014-06-27 18:19:56 +0000548bool LLParser::parseComdat() {
549 assert(Lex.getKind() == lltok::ComdatVar);
550 std::string Name = Lex.getStrVal();
551 LocTy NameLoc = Lex.getLoc();
552 Lex.Lex();
553
554 if (ParseToken(lltok::equal, "expected '=' here"))
555 return true;
556
557 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
558 return TokError("expected comdat type");
559
560 Comdat::SelectionKind SK;
561 switch (Lex.getKind()) {
562 default:
563 return TokError("unknown selection kind");
564 case lltok::kw_any:
565 SK = Comdat::Any;
566 break;
567 case lltok::kw_exactmatch:
568 SK = Comdat::ExactMatch;
569 break;
570 case lltok::kw_largest:
571 SK = Comdat::Largest;
572 break;
573 case lltok::kw_noduplicates:
574 SK = Comdat::NoDuplicates;
575 break;
576 case lltok::kw_samesize:
577 SK = Comdat::SameSize;
578 break;
579 }
580 Lex.Lex();
581
582 // See if the comdat was forward referenced, if so, use the comdat.
583 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
584 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
585 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
586 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
587
588 Comdat *C;
589 if (I != ComdatSymTab.end())
590 C = &I->second;
591 else
592 C = M->getOrInsertComdat(Name);
593 C->setSelectionKind(SK);
594
595 return false;
596}
597
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000598// MDString:
599// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000600bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000601 std::string Str;
602 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000603 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000604 return false;
605}
606
607// MDNode:
608// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000609bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000610 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000611 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000613 if (ParseUInt32(MID))
614 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000615
Chris Lattner8eff0152010-04-01 05:14:45 +0000616 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000617 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000618 Result = NumberedMetadata[MID];
619 return false;
620 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000621
Chris Lattner8eff0152010-04-01 05:14:45 +0000622 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000623 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000624 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000625
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000626 Result = FwdRef.first.get();
627 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000628 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000629}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000630
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000631/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000632/// !foo = !{ !1, !2 }
633bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000634 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000635 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000636 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000637
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000638 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000639 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000640 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000641 return true;
642
Dan Gohman2637cc12010-07-21 23:38:33 +0000643 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000644 if (Lex.getKind() != lltok::rbrace)
645 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 if (ParseToken(lltok::exclaim, "Expected '!' here"))
647 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000648
Craig Topper2617dcc2014-04-15 06:32:26 +0000649 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000650 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000651 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000652 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000653
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000654 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000655}
656
Devang Patel39e64d42009-07-01 19:21:12 +0000657/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000658/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000659bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000660 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000661 Lex.Lex();
662 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000663
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000665 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000666 ParseToken(lltok::equal, "expected '=' here"))
667 return true;
668
669 // Detect common error, from old metadata syntax.
670 if (Lex.getKind() == lltok::Type)
671 return TokError("unexpected type in metadata definition");
672
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000673 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000674 if (Lex.getKind() == lltok::MetadataVar) {
675 if (ParseSpecializedMDNode(Init, IsDistinct))
676 return true;
677 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
678 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000679 return true;
680
Chris Lattnerfc58af22009-12-30 04:51:58 +0000681 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000683 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000684 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000685 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000686
Chris Lattnerfc58af22009-12-30 04:51:58 +0000687 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
688 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000689 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000690 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000691 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000692 }
693
Devang Patel39e64d42009-07-01 19:21:12 +0000694 return false;
695}
696
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000697static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
698 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
699 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
700}
701
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000702/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000703/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
704/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000705/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000706///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000707/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000708/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709///
Eric Christopher536f0a92015-05-28 23:07:39 +0000710/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000712bool LLParser::parseIndirectSymbol(
713 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
714 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
715 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000716 bool IsAlias;
717 if (Lex.getKind() == lltok::kw_alias)
718 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000719 else if (Lex.getKind() == lltok::kw_ifunc)
720 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000721 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000722 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000723 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724
Rafael Espindola78527052013-10-06 15:10:43 +0000725 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
726
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000727 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000728 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000729
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000730 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000731 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000732 "symbol with local linkage must have default visibility");
733
David Blaikie2f408302015-09-11 03:22:04 +0000734 Type *Ty;
735 LocTy ExplicitTypeLoc = Lex.getLoc();
736 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000737 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000738 return true;
739
Rafael Espindola64c1e182014-06-03 02:41:57 +0000740 Constant *Aliasee;
741 LocTy AliaseeLoc = Lex.getLoc();
742 if (Lex.getKind() != lltok::kw_bitcast &&
743 Lex.getKind() != lltok::kw_getelementptr &&
744 Lex.getKind() != lltok::kw_addrspacecast &&
745 Lex.getKind() != lltok::kw_inttoptr) {
746 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000747 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000749 // The bitcast dest type is not present, it is implied by the dest type.
750 ValID ID;
751 if (ParseValID(ID))
752 return true;
753 if (ID.Kind != ValID::t_Constant)
754 return Error(AliaseeLoc, "invalid aliasee");
755 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757
Rafael Espindola64c1e182014-06-03 02:41:57 +0000758 Type *AliaseeType = Aliasee->getType();
759 auto *PTy = dyn_cast<PointerType>(AliaseeType);
760 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000761 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000762 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000763
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000764 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000765 return Error(
766 ExplicitTypeLoc,
767 "explicit pointee type doesn't match operand's pointee type");
768
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000769 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
770 return Error(
771 ExplicitTypeLoc,
772 "explicit pointee type should be a function type");
773
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000774 GlobalValue *GVal = nullptr;
775
776 // See if the alias was forward referenced, if so, prepare to replace the
777 // forward reference.
778 if (!Name.empty()) {
779 GVal = M->getNamedValue(Name);
780 if (GVal) {
781 if (!ForwardRefVals.erase(Name))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
783 }
784 } else {
785 auto I = ForwardRefValIDs.find(NumberedVals.size());
786 if (I != ForwardRefValIDs.end()) {
787 GVal = I->second.first;
788 ForwardRefValIDs.erase(I);
789 }
790 }
791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000793 std::unique_ptr<GlobalIndirectSymbol> GA;
794 if (IsAlias)
795 GA.reset(GlobalAlias::create(Ty, AddrSpace,
796 (GlobalValue::LinkageTypes)Linkage, Name,
797 Aliasee, /*Parent*/ nullptr));
798 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000799 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
800 (GlobalValue::LinkageTypes)Linkage, Name,
801 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000802 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000803 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000804 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000805 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Rafael Espindola54fc2982015-06-17 17:53:31 +0000807 if (Name.empty())
808 NumberedVals.push_back(GA.get());
809
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000810 if (GVal) {
811 // Verify that types agree.
812 if (GVal->getType() != GA->getType())
813 return Error(
814 ExplicitTypeLoc,
815 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 // If they agree, just RAUW the old value with the alias and remove the
818 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000819 GVal->replaceAllUsesWith(GA.get());
820 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000821 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000822
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000824 if (IsAlias)
825 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
826 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000827 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000828 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Rafael Espindolaaa273822014-05-09 21:49:17 +0000830 // The module owns this now
831 GA.release();
832
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833 return false;
834}
835
836/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000837/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000838/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000839/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000840/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000841/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000842/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843///
Eric Christopher536f0a92015-05-28 23:07:39 +0000844/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000845/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846///
847bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
848 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000849 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000850 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000851 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000852 if (!isValidVisibilityForLinkage(Visibility, Linkage))
853 return Error(NameLoc,
854 "symbol with local linkage must have default visibility");
855
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000857 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000858 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000860
Craig Topper2617dcc2014-04-15 06:32:26 +0000861 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000862 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000863 ParseOptionalToken(lltok::kw_externally_initialized,
864 IsExternallyInitialized,
865 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 ParseGlobalType(IsConstant) ||
867 ParseType(Ty, TyLoc))
868 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
Chris Lattnerac161bf2009-01-02 07:01:27 +0000870 // If the linkage is specified and is external, then no initializer is
871 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000872 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000873 if (!HasLinkage ||
874 !GlobalValue::isValidDeclarationLinkage(
875 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000876 if (ParseGlobalValue(Ty, Init))
877 return true;
878 }
879
David Majnemer49b3d9b2015-02-16 08:41:08 +0000880 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000881 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
David Majnemer598bd052014-12-09 05:56:09 +0000883 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884
885 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000886 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000887 GVal = M->getNamedValue(Name);
888 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000889 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000890 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000891 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000893 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000895 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000896 ForwardRefValIDs.erase(I);
897 }
898 }
899
David Majnemer598bd052014-12-09 05:56:09 +0000900 GlobalVariable *GV;
901 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000902 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
903 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000904 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000906 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 return Error(TyLoc,
908 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000909
David Majnemer598bd052014-12-09 05:56:09 +0000910 GV = cast<GlobalVariable>(GVal);
911
Chris Lattnerac161bf2009-01-02 07:01:27 +0000912 // Move the forward-reference to the correct spot in the module.
913 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
914 }
915
916 if (Name.empty())
917 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000918
Chris Lattnerac161bf2009-01-02 07:01:27 +0000919 // Set the parsed properties on the global.
920 if (Init)
921 GV->setInitializer(Init);
922 GV->setConstant(IsConstant);
923 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
924 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000925 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000926 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000927 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000928 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000929
Chris Lattnerac161bf2009-01-02 07:01:27 +0000930 // Parse attributes on the global.
931 while (Lex.getKind() == lltok::comma) {
932 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000933
Chris Lattnerac161bf2009-01-02 07:01:27 +0000934 if (Lex.getKind() == lltok::kw_section) {
935 Lex.Lex();
936 GV->setSection(Lex.getStrVal());
937 if (ParseToken(lltok::StringConstant, "expected global section string"))
938 return true;
939 } else if (Lex.getKind() == lltok::kw_align) {
940 unsigned Alignment;
941 if (ParseOptionalAlignment(Alignment)) return true;
942 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000943 } else if (Lex.getKind() == lltok::MetadataVar) {
944 if (ParseGlobalObjectMetadataAttachment(*GV))
945 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000946 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000947 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000948 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000949 return true;
950 if (C)
951 GV->setComdat(C);
952 else
953 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000954 }
955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000956
Chris Lattnerac161bf2009-01-02 07:01:27 +0000957 return false;
958}
959
Bill Wendling63b88192013-02-06 06:52:58 +0000960/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000961/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000962bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000963 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000964 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000965 Lex.Lex();
966
David Majnemerb39e22b2014-12-09 18:33:57 +0000967 if (Lex.getKind() != lltok::AttrGrpID)
968 return TokError("expected attribute group id");
969
Bill Wendling63b88192013-02-06 06:52:58 +0000970 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000971 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000972 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000973 Lex.Lex();
974
975 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000976 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000977 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000978 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000979 ParseToken(lltok::rbrace, "expected end of attribute group"))
980 return true;
981
Bill Wendlingb32b0412013-02-08 06:32:06 +0000982 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000983 return Error(AttrGrpLoc, "attribute group has no attributes");
984
985 return false;
986}
987
Bill Wendling8b0321d2013-02-08 00:52:31 +0000988/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000989/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000990bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
991 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000992 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000993 bool HaveError = false;
994
995 B.clear();
996
Bill Wendling63b88192013-02-06 06:52:58 +0000997 while (true) {
998 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000999 if (Token == lltok::kw_builtin)
1000 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001001 switch (Token) {
1002 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001003 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001004 return Error(Lex.getLoc(), "unterminated attribute group");
1005 case lltok::rbrace:
1006 // Finished.
1007 return false;
1008
Bill Wendlingb32b0412013-02-08 06:32:06 +00001009 case lltok::AttrGrpID: {
1010 // Allow a function to reference an attribute group:
1011 //
1012 // define void @foo() #1 { ... }
1013 if (inAttrGrp)
1014 HaveError |=
1015 Error(Lex.getLoc(),
1016 "cannot have an attribute group reference in an attribute group");
1017
1018 unsigned AttrGrpNum = Lex.getUIntVal();
1019 if (inAttrGrp) break;
1020
1021 // Save the reference to the attribute group. We'll fill it in later.
1022 FwdRefAttrGrps.push_back(AttrGrpNum);
1023 break;
1024 }
Bill Wendling63b88192013-02-06 06:52:58 +00001025 // Target-dependent attributes:
1026 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001027 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001028 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001029 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001030 }
1031
1032 // Target-independent attributes:
1033 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001034 // As a hack, we allow function alignment to be initially parsed as an
1035 // attribute on a function declaration/definition or added to an attribute
1036 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001037 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001038 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001039 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001040 if (ParseToken(lltok::equal, "expected '=' here") ||
1041 ParseUInt32(Alignment))
1042 return true;
1043 } else {
1044 if (ParseOptionalAlignment(Alignment))
1045 return true;
1046 }
Bill Wendling63b88192013-02-06 06:52:58 +00001047 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001048 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001049 }
1050 case lltok::kw_alignstack: {
1051 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001052 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001053 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001054 if (ParseToken(lltok::equal, "expected '=' here") ||
1055 ParseUInt32(Alignment))
1056 return true;
1057 } else {
1058 if (ParseOptionalStackAlignment(Alignment))
1059 return true;
1060 }
Bill Wendling63b88192013-02-06 06:52:58 +00001061 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001062 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001063 }
George Burgess IV278199f2016-04-12 01:05:35 +00001064 case lltok::kw_allocsize: {
1065 unsigned ElemSizeArg;
1066 Optional<unsigned> NumElemsArg;
1067 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1068 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1069 return true;
1070 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1071 continue;
1072 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001073 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1074 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1075 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1076 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1077 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001078 case lltok::kw_inaccessiblememonly:
1079 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1080 case lltok::kw_inaccessiblemem_or_argmemonly:
1081 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001082 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1083 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1084 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1085 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1086 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1087 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1088 case lltok::kw_noimplicitfloat:
1089 B.addAttribute(Attribute::NoImplicitFloat); break;
1090 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1091 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1092 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1093 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001094 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001095 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1096 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1097 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1098 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1099 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1100 case lltok::kw_returns_twice:
1101 B.addAttribute(Attribute::ReturnsTwice); break;
1102 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1103 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1104 case lltok::kw_sspstrong:
1105 B.addAttribute(Attribute::StackProtectStrong); break;
1106 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1107 case lltok::kw_sanitize_address:
1108 B.addAttribute(Attribute::SanitizeAddress); break;
1109 case lltok::kw_sanitize_thread:
1110 B.addAttribute(Attribute::SanitizeThread); break;
1111 case lltok::kw_sanitize_memory:
1112 B.addAttribute(Attribute::SanitizeMemory); break;
1113 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001114 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001115
1116 // Error handling.
1117 case lltok::kw_inreg:
1118 case lltok::kw_signext:
1119 case lltok::kw_zeroext:
1120 HaveError |=
1121 Error(Lex.getLoc(),
1122 "invalid use of attribute on a function");
1123 break;
1124 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001125 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001126 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001127 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001128 case lltok::kw_nest:
1129 case lltok::kw_noalias:
1130 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001131 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001132 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001133 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001134 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001135 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001136 HaveError |=
1137 Error(Lex.getLoc(),
1138 "invalid use of parameter-only attribute on a function");
1139 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001140 }
1141
1142 Lex.Lex();
1143 }
1144}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145
1146//===----------------------------------------------------------------------===//
1147// GlobalValue Reference/Resolution Routines.
1148//===----------------------------------------------------------------------===//
1149
Karl Schimpf77729782015-09-03 18:06:44 +00001150static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1151 const std::string &Name) {
1152 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1153 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1154 else
1155 return new GlobalVariable(*M, PTy->getElementType(), false,
1156 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1157 nullptr, GlobalVariable::NotThreadLocal,
1158 PTy->getAddressSpace());
1159}
1160
Chris Lattnerac161bf2009-01-02 07:01:27 +00001161/// GetGlobalVal - Get a value with the specified name or ID, creating a
1162/// forward reference record if needed. This can return null if the value
1163/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001164GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001165 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001166 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001167 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001168 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001169 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001171
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172 // Look this name up in the normal function symbol table.
1173 GlobalValue *Val =
1174 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001175
Chris Lattnerac161bf2009-01-02 07:01:27 +00001176 // If this is a forward reference for the value, see if we already created a
1177 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001178 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001179 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001180 if (I != ForwardRefVals.end())
1181 Val = I->second.first;
1182 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001183
Chris Lattnerac161bf2009-01-02 07:01:27 +00001184 // If we have the value in the symbol table or fwd-ref table, return it.
1185 if (Val) {
1186 if (Val->getType() == Ty) return Val;
1187 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001188 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001189 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001191
Chris Lattnerac161bf2009-01-02 07:01:27 +00001192 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001193 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1195 return FwdVal;
1196}
1197
Chris Lattner229907c2011-07-18 04:54:35 +00001198GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1199 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001200 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001202 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001204
Craig Topper2617dcc2014-04-15 06:32:26 +00001205 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001206
Chris Lattnerac161bf2009-01-02 07:01:27 +00001207 // If this is a forward reference for the value, see if we already created a
1208 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001209 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001210 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001211 if (I != ForwardRefValIDs.end())
1212 Val = I->second.first;
1213 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001214
Chris Lattnerac161bf2009-01-02 07:01:27 +00001215 // If we have the value in the symbol table or fwd-ref table, return it.
1216 if (Val) {
1217 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001218 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001219 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001220 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001221 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001222
Chris Lattnerac161bf2009-01-02 07:01:27 +00001223 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001224 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1226 return FwdVal;
1227}
1228
Chris Lattnerac161bf2009-01-02 07:01:27 +00001229//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001230// Comdat Reference/Resolution Routines.
1231//===----------------------------------------------------------------------===//
1232
1233Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1234 // Look this name up in the comdat symbol table.
1235 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1236 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1237 if (I != ComdatSymTab.end())
1238 return &I->second;
1239
1240 // Otherwise, create a new forward reference for this value and remember it.
1241 Comdat *C = M->getOrInsertComdat(Name);
1242 ForwardRefComdats[Name] = Loc;
1243 return C;
1244}
1245
David Majnemerdad0a642014-06-27 18:19:56 +00001246//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001247// Helper Routines.
1248//===----------------------------------------------------------------------===//
1249
1250/// ParseToken - If the current token has the specified kind, eat it and return
1251/// success. Otherwise, emit the specified error and return failure.
1252bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1253 if (Lex.getKind() != T)
1254 return TokError(ErrMsg);
1255 Lex.Lex();
1256 return false;
1257}
1258
Chris Lattner3822f632009-01-02 08:05:26 +00001259/// ParseStringConstant
1260/// ::= StringConstant
1261bool LLParser::ParseStringConstant(std::string &Result) {
1262 if (Lex.getKind() != lltok::StringConstant)
1263 return TokError("expected string constant");
1264 Result = Lex.getStrVal();
1265 Lex.Lex();
1266 return false;
1267}
1268
1269/// ParseUInt32
1270/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001271bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001272 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1273 return TokError("expected integer");
1274 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1275 if (Val64 != unsigned(Val64))
1276 return TokError("expected 32-bit integer (too large)");
1277 Val = Val64;
1278 Lex.Lex();
1279 return false;
1280}
1281
Hal Finkelb0407ba2014-07-18 15:51:28 +00001282/// ParseUInt64
1283/// ::= uint64
1284bool LLParser::ParseUInt64(uint64_t &Val) {
1285 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1286 return TokError("expected integer");
1287 Val = Lex.getAPSIntVal().getLimitedValue();
1288 Lex.Lex();
1289 return false;
1290}
1291
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001292/// ParseTLSModel
1293/// := 'localdynamic'
1294/// := 'initialexec'
1295/// := 'localexec'
1296bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1297 switch (Lex.getKind()) {
1298 default:
1299 return TokError("expected localdynamic, initialexec or localexec");
1300 case lltok::kw_localdynamic:
1301 TLM = GlobalVariable::LocalDynamicTLSModel;
1302 break;
1303 case lltok::kw_initialexec:
1304 TLM = GlobalVariable::InitialExecTLSModel;
1305 break;
1306 case lltok::kw_localexec:
1307 TLM = GlobalVariable::LocalExecTLSModel;
1308 break;
1309 }
1310
1311 Lex.Lex();
1312 return false;
1313}
1314
1315/// ParseOptionalThreadLocal
1316/// := /*empty*/
1317/// := 'thread_local'
1318/// := 'thread_local' '(' tlsmodel ')'
1319bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1320 TLM = GlobalVariable::NotThreadLocal;
1321 if (!EatIfPresent(lltok::kw_thread_local))
1322 return false;
1323
1324 TLM = GlobalVariable::GeneralDynamicTLSModel;
1325 if (Lex.getKind() == lltok::lparen) {
1326 Lex.Lex();
1327 return ParseTLSModel(TLM) ||
1328 ParseToken(lltok::rparen, "expected ')' after thread local model");
1329 }
1330 return false;
1331}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001332
1333/// ParseOptionalAddrSpace
1334/// := /*empty*/
1335/// := 'addrspace' '(' uint32 ')'
1336bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1337 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001338 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001339 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001340 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001341 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001342 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001343}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001344
Artur Pilipenko17376c42015-08-03 14:31:49 +00001345/// ParseStringAttribute
1346/// := StringConstant
1347/// := StringConstant '=' StringConstant
1348bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1349 std::string Attr = Lex.getStrVal();
1350 Lex.Lex();
1351 std::string Val;
1352 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1353 return true;
1354 B.addAttribute(Attr, Val);
1355 return false;
1356}
1357
Bill Wendling34c2eb22012-12-04 23:40:58 +00001358/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1359bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1360 bool HaveError = false;
1361
1362 B.clear();
1363
Eugene Zelenko1804a772016-08-25 00:45:04 +00001364 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001365 lltok::Kind Token = Lex.getKind();
1366 switch (Token) {
1367 default: // End of attributes.
1368 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001369 case lltok::StringConstant: {
1370 if (ParseStringAttribute(B))
1371 return true;
1372 continue;
1373 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001374 case lltok::kw_align: {
1375 unsigned Alignment;
1376 if (ParseOptionalAlignment(Alignment))
1377 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001378 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001379 continue;
1380 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001381 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001382 case lltok::kw_dereferenceable: {
1383 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001384 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001385 return true;
1386 B.addDereferenceableAttr(Bytes);
1387 continue;
1388 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001389 case lltok::kw_dereferenceable_or_null: {
1390 uint64_t Bytes;
1391 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1392 return true;
1393 B.addDereferenceableOrNullAttr(Bytes);
1394 continue;
1395 }
Reid Klecknera534a382013-12-19 02:14:12 +00001396 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001397 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1398 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1399 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1400 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001401 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001402 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1403 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001404 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001405 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1406 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001407 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001408 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001409 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001410 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001411
Stephen Lin7577ed52013-04-20 13:16:13 +00001412 case lltok::kw_alignstack:
1413 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001414 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001415 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001416 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001417 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001418 case lltok::kw_minsize:
1419 case lltok::kw_naked:
1420 case lltok::kw_nobuiltin:
1421 case lltok::kw_noduplicate:
1422 case lltok::kw_noimplicitfloat:
1423 case lltok::kw_noinline:
1424 case lltok::kw_nonlazybind:
1425 case lltok::kw_noredzone:
1426 case lltok::kw_noreturn:
1427 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001428 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001429 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001430 case lltok::kw_returns_twice:
1431 case lltok::kw_sanitize_address:
1432 case lltok::kw_sanitize_memory:
1433 case lltok::kw_sanitize_thread:
1434 case lltok::kw_ssp:
1435 case lltok::kw_sspreq:
1436 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001437 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001438 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001439 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1440 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001441 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001442
Bill Wendling34c2eb22012-12-04 23:40:58 +00001443 Lex.Lex();
1444 }
1445}
1446
1447/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1448bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1449 bool HaveError = false;
1450
1451 B.clear();
1452
Eugene Zelenko1804a772016-08-25 00:45:04 +00001453 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001454 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001455 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001456 default: // End of attributes.
1457 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001458 case lltok::StringConstant: {
1459 if (ParseStringAttribute(B))
1460 return true;
1461 continue;
1462 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001463 case lltok::kw_dereferenceable: {
1464 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001465 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001466 return true;
1467 B.addDereferenceableAttr(Bytes);
1468 continue;
1469 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001470 case lltok::kw_dereferenceable_or_null: {
1471 uint64_t Bytes;
1472 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1473 return true;
1474 B.addDereferenceableOrNullAttr(Bytes);
1475 continue;
1476 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001477 case lltok::kw_align: {
1478 unsigned Alignment;
1479 if (ParseOptionalAlignment(Alignment))
1480 return true;
1481 B.addAlignmentAttr(Alignment);
1482 continue;
1483 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001484 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1485 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001486 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001487 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1488 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001489
Bill Wendling34c2eb22012-12-04 23:40:58 +00001490 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001491 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001492 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001493 case lltok::kw_nest:
1494 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001495 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001496 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001497 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001498 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001499 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001500 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001501
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001502 case lltok::kw_alignstack:
1503 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001504 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001505 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001506 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001507 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001508 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001509 case lltok::kw_minsize:
1510 case lltok::kw_naked:
1511 case lltok::kw_nobuiltin:
1512 case lltok::kw_noduplicate:
1513 case lltok::kw_noimplicitfloat:
1514 case lltok::kw_noinline:
1515 case lltok::kw_nonlazybind:
1516 case lltok::kw_noredzone:
1517 case lltok::kw_noreturn:
1518 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001519 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001520 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001521 case lltok::kw_returns_twice:
1522 case lltok::kw_sanitize_address:
1523 case lltok::kw_sanitize_memory:
1524 case lltok::kw_sanitize_thread:
1525 case lltok::kw_ssp:
1526 case lltok::kw_sspreq:
1527 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001528 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001529 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001530 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001531 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001532
1533 case lltok::kw_readnone:
1534 case lltok::kw_readonly:
1535 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001536 }
1537
Chris Lattnerac161bf2009-01-02 07:01:27 +00001538 Lex.Lex();
1539 }
1540}
1541
Rafael Espindolac6269912016-05-10 17:16:45 +00001542static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1543 HasLinkage = true;
1544 switch (Kind) {
1545 default:
1546 HasLinkage = false;
1547 return GlobalValue::ExternalLinkage;
1548 case lltok::kw_private:
1549 return GlobalValue::PrivateLinkage;
1550 case lltok::kw_internal:
1551 return GlobalValue::InternalLinkage;
1552 case lltok::kw_weak:
1553 return GlobalValue::WeakAnyLinkage;
1554 case lltok::kw_weak_odr:
1555 return GlobalValue::WeakODRLinkage;
1556 case lltok::kw_linkonce:
1557 return GlobalValue::LinkOnceAnyLinkage;
1558 case lltok::kw_linkonce_odr:
1559 return GlobalValue::LinkOnceODRLinkage;
1560 case lltok::kw_available_externally:
1561 return GlobalValue::AvailableExternallyLinkage;
1562 case lltok::kw_appending:
1563 return GlobalValue::AppendingLinkage;
1564 case lltok::kw_common:
1565 return GlobalValue::CommonLinkage;
1566 case lltok::kw_extern_weak:
1567 return GlobalValue::ExternalWeakLinkage;
1568 case lltok::kw_external:
1569 return GlobalValue::ExternalLinkage;
1570 }
1571}
1572
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573/// ParseOptionalLinkage
1574/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001575/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001576/// ::= 'internal'
1577/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001578/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001579/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001580/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001581/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001582/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001583/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584/// ::= 'extern_weak'
1585/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001586bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1587 unsigned &Visibility,
1588 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001589 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1590 if (HasLinkage)
1591 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001592 ParseOptionalVisibility(Visibility);
1593 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001594 return false;
1595}
1596
1597/// ParseOptionalVisibility
1598/// ::= /*empty*/
1599/// ::= 'default'
1600/// ::= 'hidden'
1601/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001602///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001603void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001604 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001605 default:
1606 Res = GlobalValue::DefaultVisibility;
1607 return;
1608 case lltok::kw_default:
1609 Res = GlobalValue::DefaultVisibility;
1610 break;
1611 case lltok::kw_hidden:
1612 Res = GlobalValue::HiddenVisibility;
1613 break;
1614 case lltok::kw_protected:
1615 Res = GlobalValue::ProtectedVisibility;
1616 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001617 }
1618 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001619}
1620
Nico Rieck7157bb72014-01-14 15:22:47 +00001621/// ParseOptionalDLLStorageClass
1622/// ::= /*empty*/
1623/// ::= 'dllimport'
1624/// ::= 'dllexport'
1625///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001626void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001627 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001628 default:
1629 Res = GlobalValue::DefaultStorageClass;
1630 return;
1631 case lltok::kw_dllimport:
1632 Res = GlobalValue::DLLImportStorageClass;
1633 break;
1634 case lltok::kw_dllexport:
1635 Res = GlobalValue::DLLExportStorageClass;
1636 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001637 }
1638 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001639}
1640
Chris Lattnerac161bf2009-01-02 07:01:27 +00001641/// ParseOptionalCallingConv
1642/// ::= /*empty*/
1643/// ::= 'ccc'
1644/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001645/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646/// ::= 'coldcc'
1647/// ::= 'x86_stdcallcc'
1648/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001649/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001650/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001651/// ::= 'arm_apcscc'
1652/// ::= 'arm_aapcscc'
1653/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001654/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001655/// ::= 'avr_intrcc'
1656/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001657/// ::= 'ptx_kernel'
1658/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001659/// ::= 'spir_func'
1660/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001661/// ::= 'x86_64_sysvcc'
1662/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001663/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001664/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001665/// ::= 'preserve_mostcc'
1666/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001667/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001668/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001669/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001670/// ::= 'hhvmcc'
1671/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001672/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001673/// ::= 'amdgpu_vs'
1674/// ::= 'amdgpu_tcs'
1675/// ::= 'amdgpu_tes'
1676/// ::= 'amdgpu_gs'
1677/// ::= 'amdgpu_ps'
1678/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001679/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001680/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001681///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001682bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001683 switch (Lex.getKind()) {
1684 default: CC = CallingConv::C; return false;
1685 case lltok::kw_ccc: CC = CallingConv::C; break;
1686 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1687 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1688 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1689 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001690 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001691 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001692 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001693 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1694 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1695 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001696 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001697 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1698 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001699 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1700 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001701 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1702 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001703 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001704 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1705 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001706 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001707 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001708 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1709 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001710 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001711 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001712 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001713 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1714 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001715 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001716 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1717 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1718 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1719 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001720 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001721 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001722 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001723 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001724 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001725 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001726
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727 Lex.Lex();
1728 return false;
1729}
1730
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001731/// ParseMetadataAttachment
1732/// ::= !dbg !42
1733bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1734 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1735
1736 std::string Name = Lex.getStrVal();
1737 Kind = M->getMDKindID(Name);
1738 Lex.Lex();
1739
1740 return ParseMDNode(MD);
1741}
1742
Chris Lattner5c427632009-12-30 05:31:19 +00001743/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001744/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001745bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001746 do {
1747 if (Lex.getKind() != lltok::MetadataVar)
1748 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001749
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001750 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001751 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001752 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001753 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001754
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001755 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001756 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001757 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001758
Chris Lattner596760d2009-12-29 21:25:40 +00001759 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001760 } while (EatIfPresent(lltok::comma));
1761 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001762}
1763
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001764/// ParseGlobalObjectMetadataAttachment
1765/// ::= !dbg !57
1766bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1767 unsigned MDK;
1768 MDNode *N;
1769 if (ParseMetadataAttachment(MDK, N))
1770 return true;
1771
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001772 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001773 return false;
1774}
1775
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001776/// ParseOptionalFunctionMetadata
1777/// ::= (!dbg !57)*
1778bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001779 while (Lex.getKind() == lltok::MetadataVar)
1780 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001781 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001782 return false;
1783}
1784
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785/// ParseOptionalAlignment
1786/// ::= /* empty */
1787/// ::= 'align' 4
1788bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1789 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001790 if (!EatIfPresent(lltok::kw_align))
1791 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001792 LocTy AlignLoc = Lex.getLoc();
1793 if (ParseUInt32(Alignment)) return true;
1794 if (!isPowerOf2_32(Alignment))
1795 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001796 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001797 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001798 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001799}
1800
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001801/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001802/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001803/// ::= AttrKind '(' 4 ')'
1804///
1805/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1806bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1807 uint64_t &Bytes) {
1808 assert((AttrKind == lltok::kw_dereferenceable ||
1809 AttrKind == lltok::kw_dereferenceable_or_null) &&
1810 "contract!");
1811
Hal Finkelb0407ba2014-07-18 15:51:28 +00001812 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001813 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001814 return false;
1815 LocTy ParenLoc = Lex.getLoc();
1816 if (!EatIfPresent(lltok::lparen))
1817 return Error(ParenLoc, "expected '('");
1818 LocTy DerefLoc = Lex.getLoc();
1819 if (ParseUInt64(Bytes)) return true;
1820 ParenLoc = Lex.getLoc();
1821 if (!EatIfPresent(lltok::rparen))
1822 return Error(ParenLoc, "expected ')'");
1823 if (!Bytes)
1824 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1825 return false;
1826}
1827
Chris Lattnerb2f39502009-12-30 05:44:30 +00001828/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001829/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001830/// ::= ',' align 4
1831///
1832/// This returns with AteExtraComma set to true if it ate an excess comma at the
1833/// end.
1834bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1835 bool &AteExtraComma) {
1836 AteExtraComma = false;
1837 while (EatIfPresent(lltok::comma)) {
1838 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001839 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001840 AteExtraComma = true;
1841 return false;
1842 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001843
Chris Lattner95b0ff42010-04-23 00:50:50 +00001844 if (Lex.getKind() != lltok::kw_align)
1845 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001846
Chris Lattner95b0ff42010-04-23 00:50:50 +00001847 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001848 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001849
Devang Patelea8a4b92009-09-17 23:04:48 +00001850 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001851}
1852
George Burgess IV278199f2016-04-12 01:05:35 +00001853bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1854 Optional<unsigned> &HowManyArg) {
1855 Lex.Lex();
1856
1857 auto StartParen = Lex.getLoc();
1858 if (!EatIfPresent(lltok::lparen))
1859 return Error(StartParen, "expected '('");
1860
1861 if (ParseUInt32(BaseSizeArg))
1862 return true;
1863
1864 if (EatIfPresent(lltok::comma)) {
1865 auto HowManyAt = Lex.getLoc();
1866 unsigned HowMany;
1867 if (ParseUInt32(HowMany))
1868 return true;
1869 if (HowMany == BaseSizeArg)
1870 return Error(HowManyAt,
1871 "'allocsize' indices can't refer to the same parameter");
1872 HowManyArg = HowMany;
1873 } else
1874 HowManyArg = None;
1875
1876 auto EndParen = Lex.getLoc();
1877 if (!EatIfPresent(lltok::rparen))
1878 return Error(EndParen, "expected ')'");
1879 return false;
1880}
1881
Eli Friedmanfee02c62011-07-25 23:16:38 +00001882/// ParseScopeAndOrdering
1883/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1884/// else: ::=
1885///
1886/// This sets Scope and Ordering to the parsed values.
1887bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1888 AtomicOrdering &Ordering) {
1889 if (!isAtomic)
1890 return false;
1891
1892 Scope = CrossThread;
1893 if (EatIfPresent(lltok::kw_singlethread))
1894 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001895
1896 return ParseOrdering(Ordering);
1897}
1898
1899/// ParseOrdering
1900/// ::= AtomicOrdering
1901///
1902/// This sets Ordering to the parsed value.
1903bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001904 switch (Lex.getKind()) {
1905 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001906 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1907 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1908 // Not specified yet:
1909 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1910 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1911 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1912 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1913 case lltok::kw_seq_cst:
1914 Ordering = AtomicOrdering::SequentiallyConsistent;
1915 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001916 }
1917 Lex.Lex();
1918 return false;
1919}
1920
Charles Davisbe5557e2010-02-12 00:31:15 +00001921/// ParseOptionalStackAlignment
1922/// ::= /* empty */
1923/// ::= 'alignstack' '(' 4 ')'
1924bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1925 Alignment = 0;
1926 if (!EatIfPresent(lltok::kw_alignstack))
1927 return false;
1928 LocTy ParenLoc = Lex.getLoc();
1929 if (!EatIfPresent(lltok::lparen))
1930 return Error(ParenLoc, "expected '('");
1931 LocTy AlignLoc = Lex.getLoc();
1932 if (ParseUInt32(Alignment)) return true;
1933 ParenLoc = Lex.getLoc();
1934 if (!EatIfPresent(lltok::rparen))
1935 return Error(ParenLoc, "expected ')'");
1936 if (!isPowerOf2_32(Alignment))
1937 return Error(AlignLoc, "stack alignment is not a power of two");
1938 return false;
1939}
Devang Patelea8a4b92009-09-17 23:04:48 +00001940
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001941/// ParseIndexList - This parses the index list for an insert/extractvalue
1942/// instruction. This sets AteExtraComma in the case where we eat an extra
1943/// comma at the end of the line and find that it is followed by metadata.
1944/// Clients that don't allow metadata can call the version of this function that
1945/// only takes one argument.
1946///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001947/// ParseIndexList
1948/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001949///
1950bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1951 bool &AteExtraComma) {
1952 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001953
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954 if (Lex.getKind() != lltok::comma)
1955 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001956
Chris Lattner3822f632009-01-02 08:05:26 +00001957 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001958 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001959 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001960 AteExtraComma = true;
1961 return false;
1962 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001963 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001964 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 Indices.push_back(Idx);
1966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001967
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968 return false;
1969}
1970
1971//===----------------------------------------------------------------------===//
1972// Type Parsing.
1973//===----------------------------------------------------------------------===//
1974
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001975/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001976bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001977 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 switch (Lex.getKind()) {
1979 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001980 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001984 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001986 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 // Type ::= StructType
1988 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 return true;
1990 break;
1991 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001992 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001993 Lex.Lex(); // eat the lsquare.
1994 if (ParseArrayVectorType(Result, false))
1995 return true;
1996 break;
1997 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001998 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001999 Lex.Lex();
2000 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002002 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002003 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 } else if (ParseArrayVectorType(Result, true))
2005 return true;
2006 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 case lltok::LocalVar: {
2008 // Type ::= %foo
2009 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002010
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002011 // If the type hasn't been defined yet, create a forward definition and
2012 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002013 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002014 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002016 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018 Lex.Lex();
2019 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002020 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002021
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 case lltok::LocalVarID: {
2023 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002025
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 // If the type hasn't been defined yet, create a forward definition and
2027 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002028 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002029 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 Lex.Lex();
2034 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002035 }
2036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002037
2038 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002039 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002040 switch (Lex.getKind()) {
2041 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042 default:
2043 if (!AllowVoid && Result->isVoidTy())
2044 return Error(TypeLoc, "void type only allowed for function results");
2045 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (Result->isVoidTy())
2052 return TokError("pointers to void are invalid - use i8* instead");
2053 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002054 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002055 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002056 Lex.Lex();
2057 break;
2058
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002060 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002064 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002066 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 unsigned AddrSpace;
2068 if (ParseOptionalAddrSpace(AddrSpace) ||
2069 ParseToken(lltok::star, "expected '*' in address space"))
2070 return true;
2071
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002072 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002073 break;
2074 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2077 case lltok::lparen:
2078 if (ParseFunctionType(Result))
2079 return true;
2080 break;
2081 }
2082 }
2083}
2084
2085/// ParseParameterList
2086/// ::= '(' ')'
2087/// ::= '(' Arg (',' Arg)* ')'
2088/// Arg
2089/// ::= Type OptionalAttributes Value OptionalAttributes
2090bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002091 PerFunctionState &PFS, bool IsMustTailCall,
2092 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 if (ParseToken(lltok::lparen, "expected '(' in call"))
2094 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002095
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 while (Lex.getKind() != lltok::rparen) {
2097 // If this isn't the first argument, we need a comma.
2098 if (!ArgList.empty() &&
2099 ParseToken(lltok::comma, "expected ',' in argument list"))
2100 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Reid Kleckner83498642014-08-26 00:33:28 +00002102 // Parse an ellipsis if this is a musttail call in a variadic function.
2103 if (Lex.getKind() == lltok::dotdotdot) {
2104 const char *Msg = "unexpected ellipsis in argument list for ";
2105 if (!IsMustTailCall)
2106 return TokError(Twine(Msg) + "non-musttail call");
2107 if (!InVarArgsFunc)
2108 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2109 Lex.Lex(); // Lex the '...', it is purely for readability.
2110 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2111 }
2112
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113 // Parse the argument.
2114 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002115 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002116 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002118 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002120
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002121 if (ArgTy->isMetadataTy()) {
2122 if (ParseMetadataAsValue(V, PFS))
2123 return true;
2124 } else {
2125 // Otherwise, handle normal operands.
2126 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2127 return true;
2128 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002129 ArgList.push_back(ParamInfo(
Reid Kleckner324c99d2017-04-10 20:18:10 +00002130 ArgLoc, V, AttributeSetNode::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002131 }
2132
Reid Kleckner83498642014-08-26 00:33:28 +00002133 if (IsMustTailCall && InVarArgsFunc)
2134 return TokError("expected '...' at end of argument list for musttail call "
2135 "in varargs function");
2136
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 Lex.Lex(); // Lex the ')'.
2138 return false;
2139}
2140
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002141/// ParseOptionalOperandBundles
2142/// ::= /*empty*/
2143/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2144///
2145/// OperandBundle
2146/// ::= bundle-tag '(' ')'
2147/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2148///
2149/// bundle-tag ::= String Constant
2150bool LLParser::ParseOptionalOperandBundles(
2151 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2152 LocTy BeginLoc = Lex.getLoc();
2153 if (!EatIfPresent(lltok::lsquare))
2154 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002156 while (Lex.getKind() != lltok::rsquare) {
2157 // If this isn't the first operand bundle, we need a comma.
2158 if (!BundleList.empty() &&
2159 ParseToken(lltok::comma, "expected ',' in input list"))
2160 return true;
2161
2162 std::string Tag;
2163 if (ParseStringConstant(Tag))
2164 return true;
2165
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002166 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2167 return true;
2168
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002169 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002170 while (Lex.getKind() != lltok::rparen) {
2171 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002172 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002173 ParseToken(lltok::comma, "expected ',' in input list"))
2174 return true;
2175
2176 Type *Ty = nullptr;
2177 Value *Input = nullptr;
2178 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2179 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002180 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002181 }
2182
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002183 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2184
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002185 Lex.Lex(); // Lex the ')'.
2186 }
2187
2188 if (BundleList.empty())
2189 return Error(BeginLoc, "operand bundle set must not be empty");
2190
2191 Lex.Lex(); // Lex the ']'.
2192 return false;
2193}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194
Chris Lattner2ed06b42009-01-05 18:34:07 +00002195/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002196/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197/// ::= '(' ArgTypeListI ')'
2198/// ArgTypeListI
2199/// ::= /*empty*/
2200/// ::= '...'
2201/// ::= ArgTypeList ',' '...'
2202/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002203///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002204bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2205 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 isVarArg = false;
2207 assert(Lex.getKind() == lltok::lparen);
2208 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002209
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 if (Lex.getKind() == lltok::rparen) {
2211 // empty
2212 } else if (Lex.getKind() == lltok::dotdotdot) {
2213 isVarArg = true;
2214 Lex.Lex();
2215 } else {
2216 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002217 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002218 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002219 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002220
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002221 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002222 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002223
Chris Lattnerfdd87902009-10-05 05:54:46 +00002224 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002225 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattnerdef19492011-06-17 06:36:20 +00002227 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 Name = Lex.getStrVal();
2229 Lex.Lex();
2230 }
Chris Lattner3822f632009-01-02 08:05:26 +00002231
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002232 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002233 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Reid Kleckner324c99d2017-04-10 20:18:10 +00002235 ArgList.emplace_back(TypeLoc, ArgTy,
2236 AttributeSetNode::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002237 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238
Chris Lattner3822f632009-01-02 08:05:26 +00002239 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002240 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002241 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002242 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002243 break;
2244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002245
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 // Otherwise must be an argument type.
2247 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002248 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002249
Chris Lattnerfdd87902009-10-05 05:54:46 +00002250 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002251 return Error(TypeLoc, "argument can not have void type");
2252
Chris Lattnerdef19492011-06-17 06:36:20 +00002253 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 Name = Lex.getStrVal();
2255 Lex.Lex();
2256 } else {
2257 Name = "";
2258 }
Chris Lattner3822f632009-01-02 08:05:26 +00002259
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002260 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002261 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002262
Reid Kleckner324c99d2017-04-10 20:18:10 +00002263 ArgList.emplace_back(TypeLoc, ArgTy,
2264 AttributeSetNode::get(ArgTy->getContext(), Attrs),
2265 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002266 }
2267 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002268
Chris Lattner3822f632009-01-02 08:05:26 +00002269 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002271
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272/// ParseFunctionType
2273/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002274bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 assert(Lex.getKind() == lltok::lparen);
2276
Chris Lattnerce473c72009-01-05 08:04:33 +00002277 if (!FunctionType::isValidReturnType(Result))
2278 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002279
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002282 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 // Reject names on the arguments lists.
2286 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2287 if (!ArgList[i].Name.empty())
2288 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Kleckner324c99d2017-04-10 20:18:10 +00002289 if (ArgList[i].Attrs)
Chris Lattner6bc5c892011-06-17 17:37:13 +00002290 return Error(ArgList[i].Loc,
2291 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Jay Foadb804a2b2011-07-12 14:06:48 +00002294 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002296 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002297
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002298 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 return false;
2300}
2301
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002302/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2303/// other structs.
2304bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2305 SmallVector<Type*, 8> Elts;
2306 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002307
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308 Result = StructType::get(Context, Elts, Packed);
2309 return false;
2310}
2311
2312/// ParseStructDefinition - Parse a struct in a 'type' definition.
2313bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2314 std::pair<Type*, LocTy> &Entry,
2315 Type *&ResultTy) {
2316 // If the type was already defined, diagnose the redefinition.
2317 if (Entry.first && !Entry.second.isValid())
2318 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002319
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002320 // If we have opaque, just return without filling in the definition for the
2321 // struct. This counts as a definition as far as the .ll file goes.
2322 if (EatIfPresent(lltok::kw_opaque)) {
2323 // This type is being defined, so clear the location to indicate this.
2324 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002325
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002327 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002328 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002329 ResultTy = Entry.first;
2330 return false;
2331 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002333 // If the type starts with '<', then it is either a packed struct or a vector.
2334 bool isPacked = EatIfPresent(lltok::less);
2335
2336 // If we don't have a struct, then we have a random type alias, which we
2337 // accept for compatibility with old files. These types are not allowed to be
2338 // forward referenced and not allowed to be recursive.
2339 if (Lex.getKind() != lltok::lbrace) {
2340 if (Entry.first)
2341 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002342
Craig Topper2617dcc2014-04-15 06:32:26 +00002343 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002344 if (isPacked)
2345 return ParseArrayVectorType(ResultTy, true);
2346 return ParseType(ResultTy);
2347 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002348
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002349 // This type is being defined, so clear the location to indicate this.
2350 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002351
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002352 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002353 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002354 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002355
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002356 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002358 SmallVector<Type*, 8> Body;
2359 if (ParseStructBody(Body) ||
2360 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2361 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002362
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002363 STy->setBody(Body, isPacked);
2364 ResultTy = STy;
2365 return false;
2366}
2367
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002369/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002371/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002373/// ::= '<' '{' Type (',' Type)* '}' '>'
2374bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 assert(Lex.getKind() == lltok::lbrace);
2376 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002377
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002378 // Handle the empty struct.
2379 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002381
Chris Lattnerf880ca22009-03-09 04:49:14 +00002382 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002383 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002384 if (ParseType(Ty)) return true;
2385 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002387 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002388 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002389
Chris Lattner3822f632009-01-02 08:05:26 +00002390 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002391 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002392 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002393
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002394 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002395 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002396
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002397 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002399
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002400 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401}
2402
2403/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2404/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002405/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406/// ::= '[' APSINTVAL 'x' Types ']'
2407/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002408bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002409 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2410 Lex.getAPSIntVal().getBitWidth() > 64)
2411 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002412
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 LocTy SizeLoc = Lex.getLoc();
2414 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002415 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattner3822f632009-01-02 08:05:26 +00002417 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2418 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419
2420 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002421 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002422 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002423
Chris Lattner3822f632009-01-02 08:05:26 +00002424 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2425 "expected end of sequential type"))
2426 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002427
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002429 if (Size == 0)
2430 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 if ((unsigned)Size != Size)
2432 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002433 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002434 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002435 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002437 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002439 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 }
2441 return false;
2442}
2443
2444//===----------------------------------------------------------------------===//
2445// Function Semantic Analysis.
2446//===----------------------------------------------------------------------===//
2447
Chris Lattner3432c622009-10-28 03:39:23 +00002448LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2449 int functionNumber)
2450 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451
2452 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002453 for (Argument &A : F.args())
2454 if (!A.hasName())
2455 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456}
2457
2458LLParser::PerFunctionState::~PerFunctionState() {
2459 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
David Blaikie9ebdc692015-09-21 21:07:50 +00002461 for (const auto &P : ForwardRefVals) {
2462 if (isa<BasicBlock>(P.second.first))
2463 continue;
2464 P.second.first->replaceAllUsesWith(
2465 UndefValue::get(P.second.first->getType()));
2466 delete P.second.first;
2467 }
2468
2469 for (const auto &P : ForwardRefValIDs) {
2470 if (isa<BasicBlock>(P.second.first))
2471 continue;
2472 P.second.first->replaceAllUsesWith(
2473 UndefValue::get(P.second.first->getType()));
2474 delete P.second.first;
2475 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476}
2477
Chris Lattner3432c622009-10-28 03:39:23 +00002478bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479 if (!ForwardRefVals.empty())
2480 return P.Error(ForwardRefVals.begin()->second.second,
2481 "use of undefined value '%" + ForwardRefVals.begin()->first +
2482 "'");
2483 if (!ForwardRefValIDs.empty())
2484 return P.Error(ForwardRefValIDs.begin()->second.second,
2485 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002486 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002487 return false;
2488}
2489
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490/// GetVal - Get a value with the specified name or ID, creating a
2491/// forward reference record if needed. This can return null if the value
2492/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002493Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002494 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002496 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002497
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498 // If this is a forward reference for the value, see if we already created a
2499 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002500 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002501 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502 if (I != ForwardRefVals.end())
2503 Val = I->second.first;
2504 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505
Chris Lattnerac161bf2009-01-02 07:01:27 +00002506 // If we have the value in the symbol table or fwd-ref table, return it.
2507 if (Val) {
2508 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002509 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002510 P.Error(Loc, "'%" + Name + "' is not a basic block");
2511 else
2512 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002513 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002514 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002516
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002518 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002520 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 // Otherwise, create a new forward reference for this value and remember it.
2524 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002525 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002526 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002527 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002528 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2532 return FwdVal;
2533}
2534
David Majnemer8a1c45d2015-12-12 05:38:55 +00002535Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002536 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002537 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 // If this is a forward reference for the value, see if we already created a
2540 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002541 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002542 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002543 if (I != ForwardRefValIDs.end())
2544 Val = I->second.first;
2545 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002546
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547 // If we have the value in the symbol table or fwd-ref table, return it.
2548 if (Val) {
2549 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002550 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002551 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002553 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002554 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002555 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002557
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002558 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002560 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002562
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 // Otherwise, create a new forward reference for this value and remember it.
2564 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002565 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002566 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002567 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002568 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002570
Chris Lattnerac161bf2009-01-02 07:01:27 +00002571 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2572 return FwdVal;
2573}
2574
2575/// SetInstName - After an instruction is parsed and inserted into its
2576/// basic block, this installs its name.
2577bool LLParser::PerFunctionState::SetInstName(int NameID,
2578 const std::string &NameStr,
2579 LocTy NameLoc, Instruction *Inst) {
2580 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002581 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 if (NameID != -1 || !NameStr.empty())
2583 return P.Error(NameLoc, "instructions returning void cannot have a name");
2584 return false;
2585 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002586
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 // If this was a numbered instruction, verify that the instruction is the
2588 // expected value and resolve any forward references.
2589 if (NameStr.empty()) {
2590 // If neither a name nor an ID was specified, just use the next ID.
2591 if (NameID == -1)
2592 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002593
Chris Lattnerac161bf2009-01-02 07:01:27 +00002594 if (unsigned(NameID) != NumberedVals.size())
2595 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002596 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002597
David Blaikie9ebdc692015-09-21 21:07:50 +00002598 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002600 Value *Sentinel = FI->second.first;
2601 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002602 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002603 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002604
2605 Sentinel->replaceAllUsesWith(Inst);
2606 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002607 ForwardRefValIDs.erase(FI);
2608 }
2609
2610 NumberedVals.push_back(Inst);
2611 return false;
2612 }
2613
2614 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002615 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002616 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002617 Value *Sentinel = FI->second.first;
2618 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002619 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002620 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002621
2622 Sentinel->replaceAllUsesWith(Inst);
2623 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 ForwardRefVals.erase(FI);
2625 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 // Set the name on the instruction.
2628 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002629
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002630 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002631 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 NameStr + "'");
2633 return false;
2634}
2635
2636/// GetBB - Get a basic block with the specified name or ID, creating a
2637/// forward reference record if needed.
2638BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2639 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002640 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2641 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002642}
2643
2644BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002645 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2646 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647}
2648
2649/// DefineBB - Define the specified basic block, which is either named or
2650/// unnamed. If there is an error, this returns null otherwise it returns
2651/// the block being defined.
2652BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2653 LocTy Loc) {
2654 BasicBlock *BB;
2655 if (Name.empty())
2656 BB = GetBB(NumberedVals.size(), Loc);
2657 else
2658 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002659 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002660
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 // Move the block to the end of the function. Forward ref'd blocks are
2662 // inserted wherever they happen to be referenced.
2663 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002664
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 // Remove the block from forward ref sets.
2666 if (Name.empty()) {
2667 ForwardRefValIDs.erase(NumberedVals.size());
2668 NumberedVals.push_back(BB);
2669 } else {
2670 // BB forward references are already in the function symbol table.
2671 ForwardRefVals.erase(Name);
2672 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 return BB;
2675}
2676
2677//===----------------------------------------------------------------------===//
2678// Constants.
2679//===----------------------------------------------------------------------===//
2680
2681/// ParseValID - Parse an abstract value that doesn't necessarily have a
2682/// type implied. For example, if we parse "4" we don't know what integer type
2683/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002684/// sanity. PFS is used to convert function-local operands of metadata (since
2685/// metadata operands are not just parsed here but also converted to values).
2686/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002687bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 ID.Loc = Lex.getLoc();
2689 switch (Lex.getKind()) {
2690 default: return TokError("expected value token");
2691 case lltok::GlobalID: // @42
2692 ID.UIntVal = Lex.getUIntVal();
2693 ID.Kind = ValID::t_GlobalID;
2694 break;
2695 case lltok::GlobalVar: // @foo
2696 ID.StrVal = Lex.getStrVal();
2697 ID.Kind = ValID::t_GlobalName;
2698 break;
2699 case lltok::LocalVarID: // %42
2700 ID.UIntVal = Lex.getUIntVal();
2701 ID.Kind = ValID::t_LocalID;
2702 break;
2703 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 ID.StrVal = Lex.getStrVal();
2705 ID.Kind = ValID::t_LocalName;
2706 break;
2707 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 ID.Kind = ValID::t_APSInt;
2710 break;
2711 case lltok::APFloat:
2712 ID.APFloatVal = Lex.getAPFloatVal();
2713 ID.Kind = ValID::t_APFloat;
2714 break;
2715 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002716 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002717 ID.Kind = ValID::t_Constant;
2718 break;
2719 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002720 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002721 ID.Kind = ValID::t_Constant;
2722 break;
2723 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2724 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2725 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002726 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002727
Chris Lattnerac161bf2009-01-02 07:01:27 +00002728 case lltok::lbrace: {
2729 // ValID ::= '{' ConstVector '}'
2730 Lex.Lex();
2731 SmallVector<Constant*, 16> Elts;
2732 if (ParseGlobalValueVector(Elts) ||
2733 ParseToken(lltok::rbrace, "expected end of struct constant"))
2734 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002735
David Blaikieadbda4b2015-08-03 20:08:41 +00002736 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002737 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002738 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2739 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002740 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 return false;
2742 }
2743 case lltok::less: {
2744 // ValID ::= '<' ConstVector '>' --> Vector.
2745 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2746 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002747 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002748
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 SmallVector<Constant*, 16> Elts;
2750 LocTy FirstEltLoc = Lex.getLoc();
2751 if (ParseGlobalValueVector(Elts) ||
2752 (isPackedStruct &&
2753 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2754 ParseToken(lltok::greater, "expected end of constant"))
2755 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002756
Chris Lattnerac161bf2009-01-02 07:01:27 +00002757 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002758 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2759 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2760 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002761 ID.UIntVal = Elts.size();
2762 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002763 return false;
2764 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002765
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 if (Elts.empty())
2767 return Error(ID.Loc, "constant vector must not be empty");
2768
Duncan Sands9dff9be2010-02-15 16:12:20 +00002769 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002770 !Elts[0]->getType()->isFloatingPointTy() &&
2771 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002773 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 // Verify that all the vector elements have the same type.
2776 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2777 if (Elts[i]->getType() != Elts[0]->getType())
2778 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002779 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002780 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781
Chris Lattner69229312011-02-15 00:14:00 +00002782 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002783 ID.Kind = ValID::t_Constant;
2784 return false;
2785 }
2786 case lltok::lsquare: { // Array Constant
2787 Lex.Lex();
2788 SmallVector<Constant*, 16> Elts;
2789 LocTy FirstEltLoc = Lex.getLoc();
2790 if (ParseGlobalValueVector(Elts) ||
2791 ParseToken(lltok::rsquare, "expected end of array constant"))
2792 return true;
2793
2794 // Handle empty element.
2795 if (Elts.empty()) {
2796 // Use undef instead of an array because it's inconvenient to determine
2797 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002798 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 return false;
2800 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002801
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002803 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002804 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002805
Owen Anderson4056ca92009-07-29 22:17:13 +00002806 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002809 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 if (Elts[i]->getType() != Elts[0]->getType())
2811 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002812 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002813 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002814 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002815
Jay Foad83be3612011-06-22 09:24:39 +00002816 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 ID.Kind = ValID::t_Constant;
2818 return false;
2819 }
2820 case lltok::kw_c: // c "foo"
2821 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002822 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2823 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2825 ID.Kind = ValID::t_Constant;
2826 return false;
2827
2828 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002829 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2830 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002831 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 Lex.Lex();
2833 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002834 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002835 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002836 ParseStringConstant(ID.StrVal) ||
2837 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002838 ParseToken(lltok::StringConstant, "expected constraint string"))
2839 return true;
2840 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002841 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002842 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 ID.Kind = ValID::t_InlineAsm;
2844 return false;
2845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002846
Chris Lattner3432c622009-10-28 03:39:23 +00002847 case lltok::kw_blockaddress: {
2848 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2849 Lex.Lex();
2850
2851 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002852
Chris Lattner3432c622009-10-28 03:39:23 +00002853 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2854 ParseValID(Fn) ||
2855 ParseToken(lltok::comma, "expected comma in block address expression")||
2856 ParseValID(Label) ||
2857 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2858 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002859
Chris Lattner3432c622009-10-28 03:39:23 +00002860 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2861 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002862 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002863 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002864
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002865 // Try to find the function (but skip it if it's forward-referenced).
2866 GlobalValue *GV = nullptr;
2867 if (Fn.Kind == ValID::t_GlobalID) {
2868 if (Fn.UIntVal < NumberedVals.size())
2869 GV = NumberedVals[Fn.UIntVal];
2870 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2871 GV = M->getNamedValue(Fn.StrVal);
2872 }
2873 Function *F = nullptr;
2874 if (GV) {
2875 // Confirm that it's actually a function with a definition.
2876 if (!isa<Function>(GV))
2877 return Error(Fn.Loc, "expected function name in blockaddress");
2878 F = cast<Function>(GV);
2879 if (F->isDeclaration())
2880 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2881 }
2882
2883 if (!F) {
2884 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002885 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002886 ForwardRefBlockAddresses.insert(std::make_pair(
2887 std::move(Fn),
2888 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002889 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2890 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002891 if (!FwdRef)
2892 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2893 GlobalValue::InternalLinkage, nullptr, "");
2894 ID.ConstantVal = FwdRef;
2895 ID.Kind = ValID::t_Constant;
2896 return false;
2897 }
2898
2899 // We found the function; now find the basic block. Don't use PFS, since we
2900 // might be inside a constant expression.
2901 BasicBlock *BB;
2902 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2903 if (Label.Kind == ValID::t_LocalID)
2904 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2905 else
2906 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2907 if (!BB)
2908 return Error(Label.Loc, "referenced value is not a basic block");
2909 } else {
2910 if (Label.Kind == ValID::t_LocalID)
2911 return Error(Label.Loc, "cannot take address of numeric label after "
2912 "the function is defined");
2913 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002914 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002915 if (!BB)
2916 return Error(Label.Loc, "referenced value is not a basic block");
2917 }
2918
2919 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002920 ID.Kind = ValID::t_Constant;
2921 return false;
2922 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002923
Chris Lattnerac161bf2009-01-02 07:01:27 +00002924 case lltok::kw_trunc:
2925 case lltok::kw_zext:
2926 case lltok::kw_sext:
2927 case lltok::kw_fptrunc:
2928 case lltok::kw_fpext:
2929 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002930 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 case lltok::kw_uitofp:
2932 case lltok::kw_sitofp:
2933 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002934 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002935 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002936 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002937 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002938 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002939 Constant *SrcVal;
2940 Lex.Lex();
2941 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2942 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002943 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 ParseType(DestTy) ||
2945 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2946 return true;
2947 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2948 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002949 getTypeString(SrcVal->getType()) + "' to '" +
2950 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002951 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002952 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002953 ID.Kind = ValID::t_Constant;
2954 return false;
2955 }
2956 case lltok::kw_extractvalue: {
2957 Lex.Lex();
2958 Constant *Val;
2959 SmallVector<unsigned, 4> Indices;
2960 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2961 ParseGlobalTypeAndValue(Val) ||
2962 ParseIndexList(Indices) ||
2963 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2964 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002965
Chris Lattner392be582010-02-12 20:49:41 +00002966 if (!Val->getType()->isAggregateType())
2967 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002968 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002970 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002971 ID.Kind = ValID::t_Constant;
2972 return false;
2973 }
2974 case lltok::kw_insertvalue: {
2975 Lex.Lex();
2976 Constant *Val0, *Val1;
2977 SmallVector<unsigned, 4> Indices;
2978 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2979 ParseGlobalTypeAndValue(Val0) ||
2980 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2981 ParseGlobalTypeAndValue(Val1) ||
2982 ParseIndexList(Indices) ||
2983 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2984 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002985 if (!Val0->getType()->isAggregateType())
2986 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002987 Type *IndexedType =
2988 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2989 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002990 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002991 if (IndexedType != Val1->getType())
2992 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2993 getTypeString(Val1->getType()) +
2994 "' instead of '" + getTypeString(IndexedType) +
2995 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002996 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002997 ID.Kind = ValID::t_Constant;
2998 return false;
2999 }
3000 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003001 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003002 unsigned PredVal, Opc = Lex.getUIntVal();
3003 Constant *Val0, *Val1;
3004 Lex.Lex();
3005 if (ParseCmpPredicate(PredVal, Opc) ||
3006 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3007 ParseGlobalTypeAndValue(Val0) ||
3008 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3009 ParseGlobalTypeAndValue(Val1) ||
3010 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3011 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 if (Val0->getType() != Val1->getType())
3014 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003015
Chris Lattnerac161bf2009-01-02 07:01:27 +00003016 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003017
Chris Lattnerac161bf2009-01-02 07:01:27 +00003018 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003019 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003021 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003022 } else {
3023 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003024 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003025 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003026 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003027 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003028 }
3029 ID.Kind = ValID::t_Constant;
3030 return false;
3031 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003032
Chris Lattnerac161bf2009-01-02 07:01:27 +00003033 // Binary Operators.
3034 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003035 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003036 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003037 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003039 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003040 case lltok::kw_udiv:
3041 case lltok::kw_sdiv:
3042 case lltok::kw_fdiv:
3043 case lltok::kw_urem:
3044 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003045 case lltok::kw_frem:
3046 case lltok::kw_shl:
3047 case lltok::kw_lshr:
3048 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003049 bool NUW = false;
3050 bool NSW = false;
3051 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003052 unsigned Opc = Lex.getUIntVal();
3053 Constant *Val0, *Val1;
3054 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003055 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003056 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3057 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003058 if (EatIfPresent(lltok::kw_nuw))
3059 NUW = true;
3060 if (EatIfPresent(lltok::kw_nsw)) {
3061 NSW = true;
3062 if (EatIfPresent(lltok::kw_nuw))
3063 NUW = true;
3064 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003065 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3066 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003067 if (EatIfPresent(lltok::kw_exact))
3068 Exact = true;
3069 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003070 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3071 ParseGlobalTypeAndValue(Val0) ||
3072 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3073 ParseGlobalTypeAndValue(Val1) ||
3074 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3075 return true;
3076 if (Val0->getType() != Val1->getType())
3077 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003078 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003079 if (NUW)
3080 return Error(ModifierLoc, "nuw only applies to integer operations");
3081 if (NSW)
3082 return Error(ModifierLoc, "nsw only applies to integer operations");
3083 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003084 // Check that the type is valid for the operator.
3085 switch (Opc) {
3086 case Instruction::Add:
3087 case Instruction::Sub:
3088 case Instruction::Mul:
3089 case Instruction::UDiv:
3090 case Instruction::SDiv:
3091 case Instruction::URem:
3092 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003093 case Instruction::Shl:
3094 case Instruction::AShr:
3095 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003096 if (!Val0->getType()->isIntOrIntVectorTy())
3097 return Error(ID.Loc, "constexpr requires integer operands");
3098 break;
3099 case Instruction::FAdd:
3100 case Instruction::FSub:
3101 case Instruction::FMul:
3102 case Instruction::FDiv:
3103 case Instruction::FRem:
3104 if (!Val0->getType()->isFPOrFPVectorTy())
3105 return Error(ID.Loc, "constexpr requires fp operands");
3106 break;
3107 default: llvm_unreachable("Unknown binary operator!");
3108 }
Dan Gohman1b849082009-09-07 23:54:19 +00003109 unsigned Flags = 0;
3110 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3111 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003112 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003113 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003114 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003115 ID.Kind = ValID::t_Constant;
3116 return false;
3117 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003118
Chris Lattnerac161bf2009-01-02 07:01:27 +00003119 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003120 case lltok::kw_and:
3121 case lltok::kw_or:
3122 case lltok::kw_xor: {
3123 unsigned Opc = Lex.getUIntVal();
3124 Constant *Val0, *Val1;
3125 Lex.Lex();
3126 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3127 ParseGlobalTypeAndValue(Val0) ||
3128 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3129 ParseGlobalTypeAndValue(Val1) ||
3130 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3131 return true;
3132 if (Val0->getType() != Val1->getType())
3133 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003134 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003135 return Error(ID.Loc,
3136 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003137 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003138 ID.Kind = ValID::t_Constant;
3139 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003140 }
3141
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142 case lltok::kw_getelementptr:
3143 case lltok::kw_shufflevector:
3144 case lltok::kw_insertelement:
3145 case lltok::kw_extractelement:
3146 case lltok::kw_select: {
3147 unsigned Opc = Lex.getUIntVal();
3148 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003149 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003150 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003151 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003152
Dan Gohman1639c392009-07-27 21:53:46 +00003153 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003154 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003155
3156 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3157 return true;
3158
3159 LocTy ExplicitTypeLoc = Lex.getLoc();
3160 if (Opc == Instruction::GetElementPtr) {
3161 if (ParseType(Ty) ||
3162 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3163 return true;
3164 }
3165
Peter Collingbourned93620b2016-11-10 22:34:55 +00003166 Optional<unsigned> InRangeOp;
3167 if (ParseGlobalValueVector(
3168 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003169 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3170 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003171
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003173 if (Elts.size() == 0 ||
3174 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003175 return Error(ID.Loc, "base of getelementptr must be a pointer");
3176
3177 Type *BaseType = Elts[0]->getType();
3178 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003179 if (Ty != BasePointerType->getElementType())
3180 return Error(
3181 ExplicitTypeLoc,
3182 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003183
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003184 unsigned GEPWidth =
3185 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3186
Jay Foaded8db7d2011-07-21 14:31:17 +00003187 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003188 for (Constant *Val : Indices) {
3189 Type *ValTy = Val->getType();
3190 if (!ValTy->getScalarType()->isIntegerTy())
3191 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003192 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003193 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003194 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003195 return Error(
3196 ID.Loc,
3197 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003198 // GEPWidth may have been unknown because the base is a scalar,
3199 // but it is known now.
3200 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003201 }
3202 }
3203
Craig Toppere3dcce92015-08-01 22:20:21 +00003204 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003205 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003206 return Error(ID.Loc, "base element of getelementptr must be sized");
3207
David Blaikie4a2e73b2015-04-02 18:55:32 +00003208 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003209 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003210
3211 if (InRangeOp) {
3212 if (*InRangeOp == 0)
3213 return Error(ID.Loc,
3214 "inrange keyword may not appear on pointer operand");
3215 --*InRangeOp;
3216 }
3217
3218 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3219 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003220 } else if (Opc == Instruction::Select) {
3221 if (Elts.size() != 3)
3222 return Error(ID.Loc, "expected three operands to select");
3223 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3224 Elts[2]))
3225 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003226 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003227 } else if (Opc == Instruction::ShuffleVector) {
3228 if (Elts.size() != 3)
3229 return Error(ID.Loc, "expected three operands to shufflevector");
3230 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3231 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003232 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003233 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003234 } else if (Opc == Instruction::ExtractElement) {
3235 if (Elts.size() != 2)
3236 return Error(ID.Loc, "expected two operands to extractelement");
3237 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3238 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003239 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003240 } else {
3241 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3242 if (Elts.size() != 3)
3243 return Error(ID.Loc, "expected three operands to insertelement");
3244 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3245 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003246 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003247 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003249
Chris Lattnerac161bf2009-01-02 07:01:27 +00003250 ID.Kind = ValID::t_Constant;
3251 return false;
3252 }
3253 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003254
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 Lex.Lex();
3256 return false;
3257}
3258
3259/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003260bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003261 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003262 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003263 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003264 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003265 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003266 if (V && !(C = dyn_cast<Constant>(V)))
3267 return Error(ID.Loc, "global values must be constants");
3268 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003269}
3270
Victor Hernandez9d75c962010-01-11 22:31:58 +00003271bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003272 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003273 return ParseType(Ty) ||
3274 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003275}
3276
Rafael Espindola83a362c2015-01-06 22:55:16 +00003277bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003278 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003279
3280 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003281 if (!EatIfPresent(lltok::kw_comdat))
3282 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003283
3284 if (EatIfPresent(lltok::lparen)) {
3285 if (Lex.getKind() != lltok::ComdatVar)
3286 return TokError("expected comdat variable");
3287 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3288 Lex.Lex();
3289 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3290 return true;
3291 } else {
3292 if (GlobalName.empty())
3293 return TokError("comdat cannot be unnamed");
3294 C = getComdat(GlobalName, KwLoc);
3295 }
3296
David Majnemerdad0a642014-06-27 18:19:56 +00003297 return false;
3298}
3299
Victor Hernandez9d75c962010-01-11 22:31:58 +00003300/// ParseGlobalValueVector
3301/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003302/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3303bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3304 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003305 // Empty list.
3306 if (Lex.getKind() == lltok::rbrace ||
3307 Lex.getKind() == lltok::rsquare ||
3308 Lex.getKind() == lltok::greater ||
3309 Lex.getKind() == lltok::rparen)
3310 return false;
3311
Peter Collingbourned93620b2016-11-10 22:34:55 +00003312 do {
3313 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3314 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003315
Peter Collingbourned93620b2016-11-10 22:34:55 +00003316 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003317 if (ParseGlobalTypeAndValue(C)) return true;
3318 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003319 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003320
3321 return false;
3322}
3323
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003324bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003325 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003326 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003327 return true;
3328
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003329 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003330 return false;
3331}
3332
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003333/// MDNode:
3334/// ::= !{ ... }
3335/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003336/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003337bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003338 if (Lex.getKind() == lltok::MetadataVar)
3339 return ParseSpecializedMDNode(N);
3340
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003341 return ParseToken(lltok::exclaim, "expected '!' here") ||
3342 ParseMDNodeTail(N);
3343}
3344
3345bool LLParser::ParseMDNodeTail(MDNode *&N) {
3346 // !{ ... }
3347 if (Lex.getKind() == lltok::lbrace)
3348 return ParseMDTuple(N);
3349
3350 // !42
3351 return ParseMDNodeID(N);
3352}
3353
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003354namespace {
3355
3356/// Structure to represent an optional metadata field.
3357template <class FieldTy> struct MDFieldImpl {
3358 typedef MDFieldImpl ImplTy;
3359 FieldTy Val;
3360 bool Seen;
3361
3362 void assign(FieldTy Val) {
3363 Seen = true;
3364 this->Val = std::move(Val);
3365 }
3366
3367 explicit MDFieldImpl(FieldTy Default)
3368 : Val(std::move(Default)), Seen(false) {}
3369};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003370
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003371struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3372 uint64_t Max;
3373
3374 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3375 : ImplTy(Default), Max(Max) {}
3376};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003377
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003378struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003379 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003380};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003381
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003382struct ColumnField : public MDUnsignedField {
3383 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3384};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003385
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003386struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003387 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003388 DwarfTagField(dwarf::Tag DefaultTag)
3389 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003390};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003391
Amjad Abouda9bcf162015-12-10 12:56:35 +00003392struct DwarfMacinfoTypeField : public MDUnsignedField {
3393 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3394 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3395 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3396};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003397
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003398struct DwarfAttEncodingField : public MDUnsignedField {
3399 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3400};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003401
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003402struct DwarfVirtualityField : public MDUnsignedField {
3403 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3404};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003405
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003406struct DwarfLangField : public MDUnsignedField {
3407 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3408};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003409
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003410struct DwarfCCField : public MDUnsignedField {
3411 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3412};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003413
Adrian Prantlb939a252016-03-31 23:56:58 +00003414struct EmissionKindField : public MDUnsignedField {
3415 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3416};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003417
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003418struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3419 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003420};
3421
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003422struct MDSignedField : public MDFieldImpl<int64_t> {
3423 int64_t Min;
3424 int64_t Max;
3425
3426 MDSignedField(int64_t Default = 0)
3427 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3428 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3429 : ImplTy(Default), Min(Min), Max(Max) {}
3430};
3431
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003432struct MDBoolField : public MDFieldImpl<bool> {
3433 MDBoolField(bool Default = false) : ImplTy(Default) {}
3434};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003435
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003436struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003437 bool AllowNull;
3438
3439 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003440};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003441
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003442struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3443 MDConstant() : ImplTy(nullptr) {}
3444};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003445
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003446struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003447 bool AllowEmpty;
3448 MDStringField(bool AllowEmpty = true)
3449 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003450};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003451
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003452struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3453 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3454};
3455
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003456struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3457 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3458 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3459};
3460
Eugene Zelenko1804a772016-08-25 00:45:04 +00003461} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003462
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003463namespace llvm {
3464
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003465template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003466bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003467 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003468 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3469 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003470
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003471 auto &U = Lex.getAPSIntVal();
3472 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003473 return TokError("value for '" + Name + "' too large, limit is " +
3474 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003475 Result.assign(U.getZExtValue());
3476 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003477 Lex.Lex();
3478 return false;
3479}
3480
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003481template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003482bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3483 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3484}
3485template <>
3486bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3487 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3488}
3489
3490template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003491bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3492 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003493 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003494
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003495 if (Lex.getKind() != lltok::DwarfTag)
3496 return TokError("expected DWARF tag");
3497
3498 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3499 if (Tag == dwarf::DW_TAG_invalid)
3500 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003501 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003502
3503 Result.assign(Tag);
3504 Lex.Lex();
3505 return false;
3506}
3507
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003508template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003509bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003510 DwarfMacinfoTypeField &Result) {
3511 if (Lex.getKind() == lltok::APSInt)
3512 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3513
3514 if (Lex.getKind() != lltok::DwarfMacinfo)
3515 return TokError("expected DWARF macinfo type");
3516
3517 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3518 if (Macinfo == dwarf::DW_MACINFO_invalid)
3519 return TokError(
3520 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3521 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3522
3523 Result.assign(Macinfo);
3524 Lex.Lex();
3525 return false;
3526}
3527
3528template <>
3529bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003530 DwarfVirtualityField &Result) {
3531 if (Lex.getKind() == lltok::APSInt)
3532 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3533
3534 if (Lex.getKind() != lltok::DwarfVirtuality)
3535 return TokError("expected DWARF virtuality code");
3536
3537 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003538 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003539 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3540 Lex.getStrVal() + "'");
3541 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3542 Result.assign(Virtuality);
3543 Lex.Lex();
3544 return false;
3545}
3546
3547template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003548bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3549 if (Lex.getKind() == lltok::APSInt)
3550 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3551
3552 if (Lex.getKind() != lltok::DwarfLang)
3553 return TokError("expected DWARF language");
3554
3555 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3556 if (!Lang)
3557 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3558 "'");
3559 assert(Lang <= Result.Max && "Expected valid DWARF language");
3560 Result.assign(Lang);
3561 Lex.Lex();
3562 return false;
3563}
3564
3565template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003566bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3567 if (Lex.getKind() == lltok::APSInt)
3568 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3569
3570 if (Lex.getKind() != lltok::DwarfCC)
3571 return TokError("expected DWARF calling convention");
3572
3573 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3574 if (!CC)
3575 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3576 "'");
3577 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3578 Result.assign(CC);
3579 Lex.Lex();
3580 return false;
3581}
3582
3583template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003584bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3585 if (Lex.getKind() == lltok::APSInt)
3586 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3587
3588 if (Lex.getKind() != lltok::EmissionKind)
3589 return TokError("expected emission kind");
3590
3591 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3592 if (!Kind)
3593 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3594 "'");
3595 assert(*Kind <= Result.Max && "Expected valid emission kind");
3596 Result.assign(*Kind);
3597 Lex.Lex();
3598 return false;
3599}
3600
3601template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003602bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003603 DwarfAttEncodingField &Result) {
3604 if (Lex.getKind() == lltok::APSInt)
3605 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3606
3607 if (Lex.getKind() != lltok::DwarfAttEncoding)
3608 return TokError("expected DWARF type attribute encoding");
3609
3610 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3611 if (!Encoding)
3612 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3613 Lex.getStrVal() + "'");
3614 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3615 Result.assign(Encoding);
3616 Lex.Lex();
3617 return false;
3618}
3619
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003620/// DIFlagField
3621/// ::= uint32
3622/// ::= DIFlagVector
3623/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3624template <>
3625bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003626
3627 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003628 auto parseFlag = [&](DINode::DIFlags &Val) {
3629 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3630 uint32_t TempVal = static_cast<uint32_t>(Val);
3631 bool Res = ParseUInt32(TempVal);
3632 Val = static_cast<DINode::DIFlags>(TempVal);
3633 return Res;
3634 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003635
3636 if (Lex.getKind() != lltok::DIFlag)
3637 return TokError("expected debug info flag");
3638
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003639 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003640 if (!Val)
3641 return TokError(Twine("invalid debug info flag flag '") +
3642 Lex.getStrVal() + "'");
3643 Lex.Lex();
3644 return false;
3645 };
3646
3647 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003648 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003649 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003650 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003651 if (parseFlag(Val))
3652 return true;
3653 Combined |= Val;
3654 } while (EatIfPresent(lltok::bar));
3655
3656 Result.assign(Combined);
3657 return false;
3658}
3659
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003660template <>
3661bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003662 MDSignedField &Result) {
3663 if (Lex.getKind() != lltok::APSInt)
3664 return TokError("expected signed integer");
3665
3666 auto &S = Lex.getAPSIntVal();
3667 if (S < Result.Min)
3668 return TokError("value for '" + Name + "' too small, limit is " +
3669 Twine(Result.Min));
3670 if (S > Result.Max)
3671 return TokError("value for '" + Name + "' too large, limit is " +
3672 Twine(Result.Max));
3673 Result.assign(S.getExtValue());
3674 assert(Result.Val >= Result.Min && "Expected value in range");
3675 assert(Result.Val <= Result.Max && "Expected value in range");
3676 Lex.Lex();
3677 return false;
3678}
3679
3680template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003681bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3682 switch (Lex.getKind()) {
3683 default:
3684 return TokError("expected 'true' or 'false'");
3685 case lltok::kw_true:
3686 Result.assign(true);
3687 break;
3688 case lltok::kw_false:
3689 Result.assign(false);
3690 break;
3691 }
3692 Lex.Lex();
3693 return false;
3694}
3695
3696template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003697bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003698 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003699 if (!Result.AllowNull)
3700 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003701 Lex.Lex();
3702 Result.assign(nullptr);
3703 return false;
3704 }
3705
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003706 Metadata *MD;
3707 if (ParseMetadata(MD, nullptr))
3708 return true;
3709
3710 Result.assign(MD);
3711 return false;
3712}
3713
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003714template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003715bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003716 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003717 std::string S;
3718 if (ParseStringConstant(S))
3719 return true;
3720
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003721 if (!Result.AllowEmpty && S.empty())
3722 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3723
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003724 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003725 return false;
3726}
3727
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003728template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003729bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3730 SmallVector<Metadata *, 4> MDs;
3731 if (ParseMDNodeVector(MDs))
3732 return true;
3733
3734 Result.assign(std::move(MDs));
3735 return false;
3736}
3737
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003738template <>
3739bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3740 ChecksumKindField &Result) {
3741 if (Lex.getKind() != lltok::ChecksumKind)
3742 return TokError(
3743 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3744
3745 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3746
3747 Result.assign(CSKind);
3748 Lex.Lex();
3749 return false;
3750}
3751
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003752} // end namespace llvm
3753
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003754template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003755bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003756 do {
3757 if (Lex.getKind() != lltok::LabelStr)
3758 return TokError("expected field label here");
3759
3760 if (parseField())
3761 return true;
3762 } while (EatIfPresent(lltok::comma));
3763
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003764 return false;
3765}
3766
3767template <class ParserTy>
3768bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3769 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3770 Lex.Lex();
3771
3772 if (ParseToken(lltok::lparen, "expected '(' here"))
3773 return true;
3774 if (Lex.getKind() != lltok::rparen)
3775 if (ParseMDFieldsImplBody(parseField))
3776 return true;
3777
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003778 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003779 return ParseToken(lltok::rparen, "expected ')' here");
3780}
3781
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003782template <class FieldTy>
3783bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3784 if (Result.Seen)
3785 return TokError("field '" + Name + "' cannot be specified more than once");
3786
3787 LocTy Loc = Lex.getLoc();
3788 Lex.Lex();
3789 return ParseMDField(Loc, Name, Result);
3790}
3791
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003792bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3793 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003794
3795#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003796 if (Lex.getStrVal() == #CLASS) \
3797 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003798#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003799
3800 return TokError("expected metadata type");
3801}
3802
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003803#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3804#define NOP_FIELD(NAME, TYPE, INIT)
3805#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3806 if (!NAME.Seen) \
3807 return Error(ClosingLoc, "missing required field '" #NAME "'");
3808#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003809 if (Lex.getStrVal() == #NAME) \
3810 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003811#define PARSE_MD_FIELDS() \
3812 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3813 do { \
3814 LocTy ClosingLoc; \
3815 if (ParseMDFieldsImpl([&]() -> bool { \
3816 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3817 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3818 }, ClosingLoc)) \
3819 return true; \
3820 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3821 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003822#define GET_OR_DISTINCT(CLASS, ARGS) \
3823 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003824
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003825/// ParseDILocationFields:
3826/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3827bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003828#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003829 OPTIONAL(line, LineField, ); \
3830 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003831 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003832 OPTIONAL(inlinedAt, MDField, );
3833 PARSE_MD_FIELDS();
3834#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003835
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003836 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003837 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003838 return false;
3839}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003840
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003841/// ParseGenericDINode:
3842/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3843bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003844#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003845 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003846 OPTIONAL(header, MDStringField, ); \
3847 OPTIONAL(operands, MDFieldList, );
3848 PARSE_MD_FIELDS();
3849#undef VISIT_MD_FIELDS
3850
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003851 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003852 (Context, tag.Val, header.Val, operands.Val));
3853 return false;
3854}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003855
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003856/// ParseDISubrange:
3857/// ::= !DISubrange(count: 30, lowerBound: 2)
3858bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003859#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003860 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003861 OPTIONAL(lowerBound, MDSignedField, );
3862 PARSE_MD_FIELDS();
3863#undef VISIT_MD_FIELDS
3864
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003865 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003866 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003867}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003868
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003869/// ParseDIEnumerator:
3870/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3871bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003872#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003873 REQUIRED(name, MDStringField, ); \
3874 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003875 PARSE_MD_FIELDS();
3876#undef VISIT_MD_FIELDS
3877
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003878 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003879 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003880}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003881
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003882/// ParseDIBasicType:
3883/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3884bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003885#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003886 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003887 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003888 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003889 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003890 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003891 PARSE_MD_FIELDS();
3892#undef VISIT_MD_FIELDS
3893
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003894 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003895 align.Val, encoding.Val));
3896 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003897}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003898
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003899/// ParseDIDerivedType:
3900/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003901/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003902/// align: 32, offset: 0, flags: 0, extraData: !3,
3903/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003904bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003905#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3906 REQUIRED(tag, DwarfTagField, ); \
3907 OPTIONAL(name, MDStringField, ); \
3908 OPTIONAL(file, MDField, ); \
3909 OPTIONAL(line, LineField, ); \
3910 OPTIONAL(scope, MDField, ); \
3911 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003912 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003913 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003914 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003915 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003916 OPTIONAL(extraData, MDField, ); \
3917 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003918 PARSE_MD_FIELDS();
3919#undef VISIT_MD_FIELDS
3920
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003921 Optional<unsigned> DWARFAddressSpace;
3922 if (dwarfAddressSpace.Val != UINT32_MAX)
3923 DWARFAddressSpace = dwarfAddressSpace.Val;
3924
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003925 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003926 (Context, tag.Val, name.Val, file.Val, line.Val,
3927 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003928 offset.Val, DWARFAddressSpace, flags.Val,
3929 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003930 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003931}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003932
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003933bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003934#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3935 REQUIRED(tag, DwarfTagField, ); \
3936 OPTIONAL(name, MDStringField, ); \
3937 OPTIONAL(file, MDField, ); \
3938 OPTIONAL(line, LineField, ); \
3939 OPTIONAL(scope, MDField, ); \
3940 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003941 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003942 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003943 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003944 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003945 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003946 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003947 OPTIONAL(vtableHolder, MDField, ); \
3948 OPTIONAL(templateParams, MDField, ); \
3949 OPTIONAL(identifier, MDStringField, );
3950 PARSE_MD_FIELDS();
3951#undef VISIT_MD_FIELDS
3952
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003953 // If this has an identifier try to build an ODR type.
3954 if (identifier.Val)
3955 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003956 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3957 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3958 elements.Val, runtimeLang.Val, vtableHolder.Val,
3959 templateParams.Val)) {
3960 Result = CT;
3961 return false;
3962 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003963
3964 // Create a new node, and save it in the context if it belongs in the type
3965 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003966 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003967 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003968 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3969 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3970 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3971 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003972}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003973
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003974bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003975#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003976 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003977 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003978 REQUIRED(types, MDField, );
3979 PARSE_MD_FIELDS();
3980#undef VISIT_MD_FIELDS
3981
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003982 Result = GET_OR_DISTINCT(DISubroutineType,
3983 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003984 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003985}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003986
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003987/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003988/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
3989/// checksumkind: CSK_MD5,
3990/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003991bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003992#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3993 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003994 REQUIRED(directory, MDStringField, ); \
3995 OPTIONAL(checksumkind, ChecksumKindField, ); \
3996 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003997 PARSE_MD_FIELDS();
3998#undef VISIT_MD_FIELDS
3999
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004000 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4001 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004002 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004003}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004004
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004005/// ParseDICompileUnit:
4006/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004007/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004008/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004009/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004010/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004011bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004012 if (!IsDistinct)
4013 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4014
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004015#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4016 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004017 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004018 OPTIONAL(producer, MDStringField, ); \
4019 OPTIONAL(isOptimized, MDBoolField, ); \
4020 OPTIONAL(flags, MDStringField, ); \
4021 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4022 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004023 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004024 OPTIONAL(enums, MDField, ); \
4025 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004026 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004027 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004028 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004029 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004030 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4031 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004032 PARSE_MD_FIELDS();
4033#undef VISIT_MD_FIELDS
4034
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004035 Result = DICompileUnit::getDistinct(
4036 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4037 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004038 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004039 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004040 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004041}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004042
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004043/// ParseDISubprogram:
4044/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004045/// file: !1, line: 7, type: !2, isLocal: false,
4046/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004047/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004048/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004049/// isOptimized: false, templateParams: !4, declaration: !5,
4050/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004051bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004052 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004053#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4054 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004055 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004056 OPTIONAL(linkageName, MDStringField, ); \
4057 OPTIONAL(file, MDField, ); \
4058 OPTIONAL(line, LineField, ); \
4059 OPTIONAL(type, MDField, ); \
4060 OPTIONAL(isLocal, MDBoolField, ); \
4061 OPTIONAL(isDefinition, MDBoolField, (true)); \
4062 OPTIONAL(scopeLine, LineField, ); \
4063 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004064 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004065 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004066 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004067 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004068 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004069 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004070 OPTIONAL(templateParams, MDField, ); \
4071 OPTIONAL(declaration, MDField, ); \
4072 OPTIONAL(variables, MDField, );
4073 PARSE_MD_FIELDS();
4074#undef VISIT_MD_FIELDS
4075
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004076 if (isDefinition.Val && !IsDistinct)
4077 return Lex.Error(
4078 Loc,
4079 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4080
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004081 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004082 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4083 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4084 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004085 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4086 isOptimized.Val, unit.Val, templateParams.Val,
4087 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004088 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004089}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004090
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004091/// ParseDILexicalBlock:
4092/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4093bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004094#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004095 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004096 OPTIONAL(file, MDField, ); \
4097 OPTIONAL(line, LineField, ); \
4098 OPTIONAL(column, ColumnField, );
4099 PARSE_MD_FIELDS();
4100#undef VISIT_MD_FIELDS
4101
4102 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004103 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004104 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004105}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004106
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004107/// ParseDILexicalBlockFile:
4108/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4109bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004110#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004111 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004112 OPTIONAL(file, MDField, ); \
4113 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4114 PARSE_MD_FIELDS();
4115#undef VISIT_MD_FIELDS
4116
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004117 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004118 (Context, scope.Val, file.Val, discriminator.Val));
4119 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004120}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004121
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004122/// ParseDINamespace:
4123/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4124bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004125#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4126 REQUIRED(scope, MDField, ); \
4127 OPTIONAL(file, MDField, ); \
4128 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004129 OPTIONAL(line, LineField, ); \
4130 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004131 PARSE_MD_FIELDS();
4132#undef VISIT_MD_FIELDS
4133
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004134 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantldbfda632016-11-03 19:42:02 +00004135 (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004136 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004137}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004138
Amjad Abouda9bcf162015-12-10 12:56:35 +00004139/// ParseDIMacro:
4140/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4141bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4142#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4143 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004144 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004145 REQUIRED(name, MDStringField, ); \
4146 OPTIONAL(value, MDStringField, );
4147 PARSE_MD_FIELDS();
4148#undef VISIT_MD_FIELDS
4149
4150 Result = GET_OR_DISTINCT(DIMacro,
4151 (Context, type.Val, line.Val, name.Val, value.Val));
4152 return false;
4153}
4154
4155/// ParseDIMacroFile:
4156/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4157bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4158#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4159 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004160 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004161 REQUIRED(file, MDField, ); \
4162 OPTIONAL(nodes, MDField, );
4163 PARSE_MD_FIELDS();
4164#undef VISIT_MD_FIELDS
4165
4166 Result = GET_OR_DISTINCT(DIMacroFile,
4167 (Context, type.Val, line.Val, file.Val, nodes.Val));
4168 return false;
4169}
4170
Adrian Prantlab1243f2015-06-29 23:03:47 +00004171/// ParseDIModule:
4172/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4173/// includePath: "/usr/include", isysroot: "/")
4174bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4175#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4176 REQUIRED(scope, MDField, ); \
4177 REQUIRED(name, MDStringField, ); \
4178 OPTIONAL(configMacros, MDStringField, ); \
4179 OPTIONAL(includePath, MDStringField, ); \
4180 OPTIONAL(isysroot, MDStringField, );
4181 PARSE_MD_FIELDS();
4182#undef VISIT_MD_FIELDS
4183
4184 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4185 configMacros.Val, includePath.Val, isysroot.Val));
4186 return false;
4187}
4188
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004189/// ParseDITemplateTypeParameter:
4190/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4191bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004192#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004193 OPTIONAL(name, MDStringField, ); \
4194 REQUIRED(type, MDField, );
4195 PARSE_MD_FIELDS();
4196#undef VISIT_MD_FIELDS
4197
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004198 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004199 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004200 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004201}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004202
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004203/// ParseDITemplateValueParameter:
4204/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004205/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004206bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004207#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004208 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004209 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004210 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004211 REQUIRED(value, MDField, );
4212 PARSE_MD_FIELDS();
4213#undef VISIT_MD_FIELDS
4214
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004215 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004216 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004217 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004218}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004219
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004220/// ParseDIGlobalVariable:
4221/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004222/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004223/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004224bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004225#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004226 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004227 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004228 OPTIONAL(linkageName, MDStringField, ); \
4229 OPTIONAL(file, MDField, ); \
4230 OPTIONAL(line, LineField, ); \
4231 OPTIONAL(type, MDField, ); \
4232 OPTIONAL(isLocal, MDBoolField, ); \
4233 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004234 OPTIONAL(declaration, MDField, ); \
4235 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004236 PARSE_MD_FIELDS();
4237#undef VISIT_MD_FIELDS
4238
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004239 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004240 (Context, scope.Val, name.Val, linkageName.Val,
4241 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004242 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004243 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004244}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004245
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004246/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004247/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004248/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4249/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004250/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004251/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4252/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004253bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004254#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004255 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004256 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004257 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004258 OPTIONAL(file, MDField, ); \
4259 OPTIONAL(line, LineField, ); \
4260 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004261 OPTIONAL(flags, DIFlagField, ); \
4262 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004263 PARSE_MD_FIELDS();
4264#undef VISIT_MD_FIELDS
4265
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004266 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004267 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004268 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004269 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004270}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004271
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004272/// ParseDIExpression:
4273/// ::= !DIExpression(0, 7, -1)
4274bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004275 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4276 Lex.Lex();
4277
4278 if (ParseToken(lltok::lparen, "expected '(' here"))
4279 return true;
4280
4281 SmallVector<uint64_t, 8> Elements;
4282 if (Lex.getKind() != lltok::rparen)
4283 do {
4284 if (Lex.getKind() == lltok::DwarfOp) {
4285 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4286 Lex.Lex();
4287 Elements.push_back(Op);
4288 continue;
4289 }
4290 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4291 }
4292
4293 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4294 return TokError("expected unsigned integer");
4295
4296 auto &U = Lex.getAPSIntVal();
4297 if (U.ugt(UINT64_MAX))
4298 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4299 Elements.push_back(U.getZExtValue());
4300 Lex.Lex();
4301 } while (EatIfPresent(lltok::comma));
4302
4303 if (ParseToken(lltok::rparen, "expected ')' here"))
4304 return true;
4305
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004306 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004307 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004308}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004309
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004310/// ParseDIGlobalVariableExpression:
4311/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4312bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4313 bool IsDistinct) {
4314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4315 REQUIRED(var, MDField, ); \
4316 OPTIONAL(expr, MDField, );
4317 PARSE_MD_FIELDS();
4318#undef VISIT_MD_FIELDS
4319
4320 Result =
4321 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4322 return false;
4323}
4324
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004325/// ParseDIObjCProperty:
4326/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004327/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004328bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004329#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004330 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004331 OPTIONAL(file, MDField, ); \
4332 OPTIONAL(line, LineField, ); \
4333 OPTIONAL(setter, MDStringField, ); \
4334 OPTIONAL(getter, MDStringField, ); \
4335 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4336 OPTIONAL(type, MDField, );
4337 PARSE_MD_FIELDS();
4338#undef VISIT_MD_FIELDS
4339
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004340 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004341 (Context, name.Val, file.Val, line.Val, setter.Val,
4342 getter.Val, attributes.Val, type.Val));
4343 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004344}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004345
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004346/// ParseDIImportedEntity:
4347/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004348/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004349bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004350#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4351 REQUIRED(tag, DwarfTagField, ); \
4352 REQUIRED(scope, MDField, ); \
4353 OPTIONAL(entity, MDField, ); \
4354 OPTIONAL(line, LineField, ); \
4355 OPTIONAL(name, MDStringField, );
4356 PARSE_MD_FIELDS();
4357#undef VISIT_MD_FIELDS
4358
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004359 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004360 entity.Val, line.Val, name.Val));
4361 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004362}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004363
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004364#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004365#undef NOP_FIELD
4366#undef REQUIRE_FIELD
4367#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004368
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004369/// ParseMetadataAsValue
4370/// ::= metadata i32 %local
4371/// ::= metadata i32 @global
4372/// ::= metadata i32 7
4373/// ::= metadata !0
4374/// ::= metadata !{...}
4375/// ::= metadata !"string"
4376bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4377 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004378 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004379 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004380 return true;
4381
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004382 V = MetadataAsValue::get(Context, MD);
4383 return false;
4384}
4385
4386/// ParseValueAsMetadata
4387/// ::= i32 %local
4388/// ::= i32 @global
4389/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004390bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4391 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004392 Type *Ty;
4393 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004394 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004395 return true;
4396 if (Ty->isMetadataTy())
4397 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4398
4399 Value *V;
4400 if (ParseValue(Ty, V, PFS))
4401 return true;
4402
4403 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004404 return false;
4405}
4406
4407/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004408/// ::= i32 %local
4409/// ::= i32 @global
4410/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004411/// ::= !42
4412/// ::= !{...}
4413/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004414/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004415bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004416 if (Lex.getKind() == lltok::MetadataVar) {
4417 MDNode *N;
4418 if (ParseSpecializedMDNode(N))
4419 return true;
4420 MD = N;
4421 return false;
4422 }
4423
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004424 // ValueAsMetadata:
4425 // <type> <value>
4426 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004427 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004428
4429 // '!'.
4430 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4431 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004432
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004433 // MDString:
4434 // ::= '!' STRINGCONSTANT
4435 if (Lex.getKind() == lltok::StringConstant) {
4436 MDString *S;
4437 if (ParseMDString(S))
4438 return true;
4439 MD = S;
4440 return false;
4441 }
4442
Dan Gohman8939ba332010-07-14 18:26:50 +00004443 // MDNode:
4444 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004445 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004446 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004447 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004448 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004449 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004450 return false;
4451}
4452
Victor Hernandez9d75c962010-01-11 22:31:58 +00004453//===----------------------------------------------------------------------===//
4454// Function Parsing.
4455//===----------------------------------------------------------------------===//
4456
Chris Lattner229907c2011-07-18 04:54:35 +00004457bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004458 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004459 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004460 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004461
Chris Lattnerac161bf2009-01-02 07:01:27 +00004462 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004464 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004465 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004466 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004467 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004468 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004469 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004470 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004471 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004472 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004473 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004474 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4475 (ID.UIntVal >> 1) & 1,
4476 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004477 return false;
4478 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004479 case ValID::t_GlobalName:
4480 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004481 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 case ValID::t_GlobalID:
4483 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004484 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004485 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004486 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004488 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004489 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 return false;
4491 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004492 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004493 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4494 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004495
Dan Gohman518cda42011-12-17 00:04:22 +00004496 // The lexer has no type info, so builds all half, float, and double FP
4497 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004498 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004500 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004501 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004502 &Ignored);
4503 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004504 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004505 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004506 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004507 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004508
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004509 if (V->getType() != Ty)
4510 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004511 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004512
Chris Lattnerac161bf2009-01-02 07:01:27 +00004513 return false;
4514 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004515 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004516 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004517 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 return false;
4519 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004520 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004521 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004522 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004523 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004525 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004526 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004527 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004528 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004529 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004531 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004532 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004534 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004535 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004536 case ValID::t_None:
4537 if (!Ty->isTokenTy())
4538 return Error(ID.Loc, "invalid type for none constant");
4539 V = Constant::getNullValue(Ty);
4540 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004542 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004543 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004544
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 V = ID.ConstantVal;
4546 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004547 case ValID::t_ConstantStruct:
4548 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004549 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004550 if (ST->getNumElements() != ID.UIntVal)
4551 return Error(ID.Loc,
4552 "initializer with struct type has wrong # elements");
4553 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4554 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004555
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004556 // Verify that the elements are compatible with the structtype.
4557 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4558 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4559 return Error(ID.Loc, "element " + Twine(i) +
4560 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004561
David Blaikieadbda4b2015-08-03 20:08:41 +00004562 V = ConstantStruct::get(
4563 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004564 } else
4565 return Error(ID.Loc, "constant expression type mismatch");
4566 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004567 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004568 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004570
Alex Lorenzd2255952015-07-17 22:07:03 +00004571bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4572 C = nullptr;
4573 ValID ID;
4574 auto Loc = Lex.getLoc();
4575 if (ParseValID(ID, /*PFS=*/nullptr))
4576 return true;
4577 switch (ID.Kind) {
4578 case ValID::t_APSInt:
4579 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004580 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004581 case ValID::t_Constant:
4582 case ValID::t_ConstantStruct:
4583 case ValID::t_PackedConstantStruct: {
4584 Value *V;
4585 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4586 return true;
4587 assert(isa<Constant>(V) && "Expected a constant value");
4588 C = cast<Constant>(V);
4589 return false;
4590 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004591 case ValID::t_Null:
4592 C = Constant::getNullValue(Ty);
4593 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004594 default:
4595 return Error(Loc, "expected a constant value");
4596 }
4597}
4598
David Majnemer8a1c45d2015-12-12 05:38:55 +00004599bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004600 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004602 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603}
4604
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004605bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004606 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004607 return ParseType(Ty) ||
4608 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609}
4610
Chris Lattner3ed871f2009-10-27 19:13:16 +00004611bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4612 PerFunctionState &PFS) {
4613 Value *V;
4614 Loc = Lex.getLoc();
4615 if (ParseTypeAndValue(V, PFS)) return true;
4616 if (!isa<BasicBlock>(V))
4617 return Error(Loc, "expected a basic block");
4618 BB = cast<BasicBlock>(V);
4619 return false;
4620}
4621
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622/// FunctionHeader
4623/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004624/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004625/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004626bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4627 // Parse the linkage.
4628 LocTy LinkageLoc = Lex.getLoc();
4629 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004630
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004631 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004632 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004633 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004634 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004635 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004636 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004638 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4639 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004640 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004641 return true;
4642
4643 // Verify that the linkage is ok.
4644 switch ((GlobalValue::LinkageTypes)Linkage) {
4645 case GlobalValue::ExternalLinkage:
4646 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004647 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 if (isDefine)
4649 return Error(LinkageLoc, "invalid linkage for function definition");
4650 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004651 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004653 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004654 case GlobalValue::LinkOnceAnyLinkage:
4655 case GlobalValue::LinkOnceODRLinkage:
4656 case GlobalValue::WeakAnyLinkage:
4657 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658 if (!isDefine)
4659 return Error(LinkageLoc, "invalid linkage for function declaration");
4660 break;
4661 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004662 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004663 return Error(LinkageLoc, "invalid function linkage type");
4664 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004665
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004666 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4667 return Error(LinkageLoc,
4668 "symbol with local linkage must have default visibility");
4669
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004670 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004671 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004672
Chris Lattnerac161bf2009-01-02 07:01:27 +00004673 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004674
4675 std::string FunctionName;
4676 if (Lex.getKind() == lltok::GlobalVar) {
4677 FunctionName = Lex.getStrVal();
4678 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4679 unsigned NameID = Lex.getUIntVal();
4680
4681 if (NameID != NumberedVals.size())
4682 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004683 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004684 } else {
4685 return TokError("expected function name");
4686 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004687
Chris Lattner3822f632009-01-02 08:05:26 +00004688 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004689
Chris Lattner3822f632009-01-02 08:05:26 +00004690 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004691 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004692
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004693 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004694 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004695 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004696 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004697 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004698 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004699 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004700 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004701 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004702 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004703 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004704 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004705 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004706 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004707
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004708 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004709 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004710 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004711 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004712 (EatIfPresent(lltok::kw_section) &&
4713 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004714 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004715 ParseOptionalAlignment(Alignment) ||
4716 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004717 ParseStringConstant(GC)) ||
4718 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004719 ParseGlobalTypeAndValue(Prefix)) ||
4720 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004721 ParseGlobalTypeAndValue(Prologue)) ||
4722 (EatIfPresent(lltok::kw_personality) &&
4723 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004724 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004725
Michael Gottesman41748d72013-06-27 00:25:01 +00004726 if (FuncAttrs.contains(Attribute::Builtin))
4727 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004728
Chris Lattnerac161bf2009-01-02 07:01:27 +00004729 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004730 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004731 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004732 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004733 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004734
Chris Lattnerac161bf2009-01-02 07:01:27 +00004735 // Okay, if we got here, the function is syntactically valid. Convert types
4736 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004737 std::vector<Type*> ParamTypeList;
Reid Kleckner324c99d2017-04-10 20:18:10 +00004738 SmallVector<AttributeSetNode *, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004739
Reid Kleckner324c99d2017-04-10 20:18:10 +00004740 Attrs.push_back(AttributeSetNode::get(Context, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004741
Chris Lattnerac161bf2009-01-02 07:01:27 +00004742 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004743 ParamTypeList.push_back(ArgList[i].Ty);
Reid Kleckner324c99d2017-04-10 20:18:10 +00004744 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004745 }
4746
Reid Kleckner324c99d2017-04-10 20:18:10 +00004747 Attrs.push_back(AttributeSetNode::get(Context, FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004748
Reid Klecknerb5180542017-03-21 16:57:19 +00004749 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004750
Bill Wendling749a43d2012-12-30 13:50:49 +00004751 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004752 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4753
Chris Lattner229907c2011-07-18 04:54:35 +00004754 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004755 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004756 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004757
Craig Topper2617dcc2014-04-15 06:32:26 +00004758 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 if (!FunctionName.empty()) {
4760 // If this was a definition of a forward reference, remove the definition
4761 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004762 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763 if (FRVI != ForwardRefVals.end()) {
4764 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004765 if (!Fn)
4766 return Error(FRVI->second.second, "invalid forward reference to "
4767 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004768 if (Fn->getType() != PFT)
4769 return Error(FRVI->second.second, "invalid forward reference to "
4770 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004771
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772 ForwardRefVals.erase(FRVI);
4773 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004774 // Reject redefinitions.
4775 return Error(NameLoc, "invalid redefinition of function '" +
4776 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004777 } else if (M->getNamedValue(FunctionName)) {
4778 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004779 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004780
Dan Gohman399d6ae2009-08-29 23:37:49 +00004781 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004782 // If this is a definition of a forward referenced function, make sure the
4783 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004784 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 if (I != ForwardRefValIDs.end()) {
4786 Fn = cast<Function>(I->second.first);
4787 if (Fn->getType() != PFT)
4788 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004789 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 ForwardRefValIDs.erase(I);
4791 }
4792 }
4793
Craig Topper2617dcc2014-04-15 06:32:26 +00004794 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004795 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4796 else // Move the forward-reference to the correct spot in the module.
4797 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4798
4799 if (FunctionName.empty())
4800 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004801
Chris Lattnerac161bf2009-01-02 07:01:27 +00004802 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4803 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004804 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805 Fn->setCallingConv(CC);
4806 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004807 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808 Fn->setAlignment(Alignment);
4809 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004810 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004811 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004812 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004813 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004814 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004815 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004816
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 // Add all of the arguments we parsed to the function.
4818 Function::arg_iterator ArgIt = Fn->arg_begin();
4819 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4820 // If the argument has a name, insert it into the argument symbol table.
4821 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004822
Chris Lattnerac161bf2009-01-02 07:01:27 +00004823 // Set the name, if it conflicted, it will be auto-renamed.
4824 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004825
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004826 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4828 ArgList[i].Name + "'");
4829 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004830
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004831 if (isDefine)
4832 return false;
4833
Robin Morisset039781e2014-08-29 21:53:01 +00004834 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004835 ValID ID;
4836 if (FunctionName.empty()) {
4837 ID.Kind = ValID::t_GlobalID;
4838 ID.UIntVal = NumberedVals.size() - 1;
4839 } else {
4840 ID.Kind = ValID::t_GlobalName;
4841 ID.StrVal = FunctionName;
4842 }
4843 auto Blocks = ForwardRefBlockAddresses.find(ID);
4844 if (Blocks != ForwardRefBlockAddresses.end())
4845 return Error(Blocks->first.Loc,
4846 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004847 return false;
4848}
4849
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004850bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4851 ValID ID;
4852 if (FunctionNumber == -1) {
4853 ID.Kind = ValID::t_GlobalName;
4854 ID.StrVal = F.getName();
4855 } else {
4856 ID.Kind = ValID::t_GlobalID;
4857 ID.UIntVal = FunctionNumber;
4858 }
4859
4860 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4861 if (Blocks == P.ForwardRefBlockAddresses.end())
4862 return false;
4863
4864 for (const auto &I : Blocks->second) {
4865 const ValID &BBID = I.first;
4866 GlobalValue *GV = I.second;
4867
4868 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4869 "Expected local id or name");
4870 BasicBlock *BB;
4871 if (BBID.Kind == ValID::t_LocalName)
4872 BB = GetBB(BBID.StrVal, BBID.Loc);
4873 else
4874 BB = GetBB(BBID.UIntVal, BBID.Loc);
4875 if (!BB)
4876 return P.Error(BBID.Loc, "referenced value is not a basic block");
4877
4878 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4879 GV->eraseFromParent();
4880 }
4881
4882 P.ForwardRefBlockAddresses.erase(Blocks);
4883 return false;
4884}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885
4886/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004887/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004888bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004889 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004890 return TokError("expected '{' in function body");
4891 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004892
Chris Lattner3432c622009-10-28 03:39:23 +00004893 int FunctionNumber = -1;
4894 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004895
Chris Lattner3432c622009-10-28 03:39:23 +00004896 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004897
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004898 // Resolve block addresses and allow basic blocks to be forward-declared
4899 // within this function.
4900 if (PFS.resolveForwardRefBlockAddresses())
4901 return true;
4902 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4903
Chris Lattnerbbddd962010-01-09 19:20:07 +00004904 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004905 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004906 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004907
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004908 while (Lex.getKind() != lltok::rbrace &&
4909 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004910 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004911
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004912 while (Lex.getKind() != lltok::rbrace)
4913 if (ParseUseListOrder(&PFS))
4914 return true;
4915
Chris Lattnerac161bf2009-01-02 07:01:27 +00004916 // Eat the }.
4917 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004918
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004920 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004921}
4922
4923/// ParseBasicBlock
4924/// ::= LabelStr? Instruction*
4925bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4926 // If this basic block starts out with a name, remember it.
4927 std::string Name;
4928 LocTy NameLoc = Lex.getLoc();
4929 if (Lex.getKind() == lltok::LabelStr) {
4930 Name = Lex.getStrVal();
4931 Lex.Lex();
4932 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004933
Chris Lattnerac161bf2009-01-02 07:01:27 +00004934 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004935 if (!BB)
4936 return Error(NameLoc,
4937 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004938
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 // Parse the instructions in this block until we get a terminator.
4942 Instruction *Inst;
4943 do {
4944 // This instruction may have three possibilities for a name: a) none
4945 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4946 LocTy NameLoc = Lex.getLoc();
4947 int NameID = -1;
4948 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004949
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 if (Lex.getKind() == lltok::LocalVarID) {
4951 NameID = Lex.getUIntVal();
4952 Lex.Lex();
4953 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4954 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004955 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 NameStr = Lex.getStrVal();
4957 Lex.Lex();
4958 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4959 return true;
4960 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004961
Chris Lattner77b89dc2009-12-30 05:23:43 +00004962 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004963 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004964 case InstError: return true;
4965 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004966 BB->getInstList().push_back(Inst);
4967
Chris Lattner77b89dc2009-12-30 05:23:43 +00004968 // With a normal result, we check to see if the instruction is followed by
4969 // a comma and metadata.
4970 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004971 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004972 return true;
4973 break;
4974 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004975 BB->getInstList().push_back(Inst);
4976
Chris Lattner77b89dc2009-12-30 05:23:43 +00004977 // If the instruction parser ate an extra comma at the end of it, it
4978 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004979 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004980 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004981 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004982 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004983
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984 // Set the name on the instruction.
4985 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4986 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004987
Chris Lattnerac161bf2009-01-02 07:01:27 +00004988 return false;
4989}
4990
4991//===----------------------------------------------------------------------===//
4992// Instruction Parsing.
4993//===----------------------------------------------------------------------===//
4994
4995/// ParseInstruction - Parse one of the many different instructions.
4996///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004997int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4998 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004999 lltok::Kind Token = Lex.getKind();
5000 if (Token == lltok::Eof)
5001 return TokError("found end of file when expecting more instructions");
5002 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005003 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005004 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 switch (Token) {
5007 default: return Error(Loc, "expected instruction opcode");
5008 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005009 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005010 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5011 case lltok::kw_br: return ParseBr(Inst, PFS);
5012 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005013 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005015 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005016 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5017 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005018 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5019 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005020 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 // Binary Operators.
5022 case lltok::kw_add:
5023 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005024 case lltok::kw_mul:
5025 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005026 bool NUW = EatIfPresent(lltok::kw_nuw);
5027 bool NSW = EatIfPresent(lltok::kw_nsw);
5028 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005029
Chris Lattnera676c0f2011-02-07 16:40:21 +00005030 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005031
Chris Lattnera676c0f2011-02-07 16:40:21 +00005032 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5033 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5034 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005035 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005036 case lltok::kw_fadd:
5037 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005038 case lltok::kw_fmul:
5039 case lltok::kw_fdiv:
5040 case lltok::kw_frem: {
5041 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5042 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5043 if (Res != 0)
5044 return Res;
5045 if (FMF.any())
5046 Inst->setFastMathFlags(FMF);
5047 return 0;
5048 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005049
Chris Lattner35315d02011-02-06 21:44:57 +00005050 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005051 case lltok::kw_udiv:
5052 case lltok::kw_lshr:
5053 case lltok::kw_ashr: {
5054 bool Exact = EatIfPresent(lltok::kw_exact);
5055
5056 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5057 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5058 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005059 }
5060
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005062 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005063 case lltok::kw_and:
5064 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005065 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005066 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5067 case lltok::kw_fcmp: {
5068 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5069 int Res = ParseCompare(Inst, PFS, KeywordVal);
5070 if (Res != 0)
5071 return Res;
5072 if (FMF.any())
5073 Inst->setFastMathFlags(FMF);
5074 return 0;
5075 }
5076
Chris Lattnerac161bf2009-01-02 07:01:27 +00005077 // Casts.
5078 case lltok::kw_trunc:
5079 case lltok::kw_zext:
5080 case lltok::kw_sext:
5081 case lltok::kw_fptrunc:
5082 case lltok::kw_fpext:
5083 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005084 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085 case lltok::kw_uitofp:
5086 case lltok::kw_sitofp:
5087 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005088 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005089 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005090 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005091 // Other.
5092 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005093 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005094 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5095 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5096 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5097 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005098 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005099 // Call.
5100 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5101 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5102 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005103 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005104 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005105 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005106 case lltok::kw_load: return ParseLoad(Inst, PFS);
5107 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005108 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5109 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005110 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005111 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5112 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5113 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5114 }
5115}
5116
5117/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5118bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005119 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005120 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005121 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005122 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5123 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5124 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5125 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5126 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5127 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5128 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5129 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5130 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5131 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5132 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5133 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5134 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5135 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5136 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5137 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5138 }
5139 } else {
5140 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005141 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5143 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5144 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5145 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5146 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5147 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5148 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5149 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5150 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5151 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5152 }
5153 }
5154 Lex.Lex();
5155 return false;
5156}
5157
5158//===----------------------------------------------------------------------===//
5159// Terminator Instructions.
5160//===----------------------------------------------------------------------===//
5161
5162/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005163/// ::= 'ret' void (',' !dbg, !1)*
5164/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005165bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005166 PerFunctionState &PFS) {
5167 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005168 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005169 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005170
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005171 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005172
Chris Lattnerfdd87902009-10-05 05:54:46 +00005173 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005174 if (!ResType->isVoidTy())
5175 return Error(TypeLoc, "value doesn't match function result type '" +
5176 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005177
Owen Anderson55f1c092009-08-13 21:58:54 +00005178 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005179 return false;
5180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005181
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 Value *RV;
5183 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005184
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005185 if (ResType != RV->getType())
5186 return Error(TypeLoc, "value doesn't match function result type '" +
5187 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005188
Owen Anderson55f1c092009-08-13 21:58:54 +00005189 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005190 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191}
5192
Chris Lattnerac161bf2009-01-02 07:01:27 +00005193/// ParseBr
5194/// ::= 'br' TypeAndValue
5195/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5196bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5197 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005198 Value *Op0;
5199 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005201
Chris Lattnerac161bf2009-01-02 07:01:27 +00005202 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5203 Inst = BranchInst::Create(BB);
5204 return false;
5205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Owen Anderson55f1c092009-08-13 21:58:54 +00005207 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005209
Chris Lattnerac161bf2009-01-02 07:01:27 +00005210 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005211 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005212 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005213 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005214 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005215
Chris Lattner3ed871f2009-10-27 19:13:16 +00005216 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005217 return false;
5218}
5219
5220/// ParseSwitch
5221/// Instruction
5222/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5223/// JumpTable
5224/// ::= (TypeAndValue ',' TypeAndValue)*
5225bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5226 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005227 Value *Cond;
5228 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005229 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5230 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005231 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5233 return true;
5234
Duncan Sands19d0b472010-02-16 11:11:14 +00005235 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005236 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005237
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 // Parse the jump table pairs.
5239 SmallPtrSet<Value*, 32> SeenCases;
5240 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5241 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005242 Value *Constant;
5243 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005244
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5246 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005247 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005249
David Blaikie70573dc2014-11-19 07:49:26 +00005250 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005251 return Error(CondLoc, "duplicate case value in switch");
5252 if (!isa<ConstantInt>(Constant))
5253 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005254
Chris Lattner3ed871f2009-10-27 19:13:16 +00005255 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005257
Chris Lattnerac161bf2009-01-02 07:01:27 +00005258 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
Chris Lattner3ed871f2009-10-27 19:13:16 +00005260 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005261 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5262 SI->addCase(Table[i].first, Table[i].second);
5263 Inst = SI;
5264 return false;
5265}
5266
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005267/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005268/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005269/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5270bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005271 LocTy AddrLoc;
5272 Value *Address;
5273 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005274 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5275 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005276 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005277
Duncan Sands19d0b472010-02-16 11:11:14 +00005278 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005279 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005280
Chris Lattner3ed871f2009-10-27 19:13:16 +00005281 // Parse the destination list.
5282 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005283
Chris Lattner3ed871f2009-10-27 19:13:16 +00005284 if (Lex.getKind() != lltok::rsquare) {
5285 BasicBlock *DestBB;
5286 if (ParseTypeAndBasicBlock(DestBB, PFS))
5287 return true;
5288 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005289
Chris Lattner3ed871f2009-10-27 19:13:16 +00005290 while (EatIfPresent(lltok::comma)) {
5291 if (ParseTypeAndBasicBlock(DestBB, PFS))
5292 return true;
5293 DestList.push_back(DestBB);
5294 }
5295 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005296
Chris Lattner3ed871f2009-10-27 19:13:16 +00005297 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5298 return true;
5299
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005300 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005301 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5302 IBI->addDestination(DestList[i]);
5303 Inst = IBI;
5304 return false;
5305}
5306
Chris Lattnerac161bf2009-01-02 07:01:27 +00005307/// ParseInvoke
5308/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5309/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5310bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5311 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005312 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005313 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005314 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005315 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005316 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005317 LocTy RetTypeLoc;
5318 ValID CalleeID;
5319 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005320 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005321
Chris Lattner3ed871f2009-10-27 19:13:16 +00005322 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005323 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005324 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005325 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005326 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5327 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005328 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005329 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005330 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005331 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005332 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005333 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005334
Chris Lattnerac161bf2009-01-02 07:01:27 +00005335 // If RetType is a non-function pointer type, then this is the short syntax
5336 // for the call, which means that RetType is just the return type. Infer the
5337 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005338 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5339 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005341 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005342 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5343 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005344
Chris Lattnerac161bf2009-01-02 07:01:27 +00005345 if (!FunctionType::isValidReturnType(RetType))
5346 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005347
Owen Anderson4056ca92009-07-29 22:17:13 +00005348 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005349 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005350
David Blaikie41ba2b42015-07-27 23:32:19 +00005351 CalleeID.FTy = Ty;
5352
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 // Look up the callee.
5354 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005355 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5356 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005357
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005358 // Set up the Attribute for the function.
Reid Kleckner324c99d2017-04-10 20:18:10 +00005359 SmallVector<AttributeSetNode *, 8> Attrs;
5360 Attrs.push_back(AttributeSetNode::get(Context, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005361
Chris Lattnerac161bf2009-01-02 07:01:27 +00005362 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005363
Chris Lattnerac161bf2009-01-02 07:01:27 +00005364 // Loop through FunctionType's arguments and ensure they are specified
5365 // correctly. Also, gather any parameter attributes.
5366 FunctionType::param_iterator I = Ty->param_begin();
5367 FunctionType::param_iterator E = Ty->param_end();
5368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005369 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005370 if (I != E) {
5371 ExpectedTy = *I++;
5372 } else if (!Ty->isVarArg()) {
5373 return Error(ArgList[i].Loc, "too many arguments specified");
5374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005375
Chris Lattnerac161bf2009-01-02 07:01:27 +00005376 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5377 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005378 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005379 Args.push_back(ArgList[i].V);
Reid Kleckner324c99d2017-04-10 20:18:10 +00005380 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005382
Chris Lattnerac161bf2009-01-02 07:01:27 +00005383 if (I != E)
5384 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005385
Reid Kleckner324c99d2017-04-10 20:18:10 +00005386 if (FnAttrs.hasAlignmentAttr())
5387 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005388
Reid Kleckner324c99d2017-04-10 20:18:10 +00005389 Attrs.push_back(AttributeSetNode::get(Context, FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005390
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005391 // Finish off the Attribute and check them
Reid Klecknerb5180542017-03-21 16:57:19 +00005392 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005393
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005394 InvokeInst *II =
5395 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005396 II->setCallingConv(CC);
5397 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005398 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005399 Inst = II;
5400 return false;
5401}
5402
Bill Wendlingf891bf82011-07-31 06:30:59 +00005403/// ParseResume
5404/// ::= 'resume' TypeAndValue
5405bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5406 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005407 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5408 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005409
Bill Wendlingf891bf82011-07-31 06:30:59 +00005410 ResumeInst *RI = ResumeInst::Create(Exn);
5411 Inst = RI;
5412 return false;
5413}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005414
David Majnemer654e1302015-07-31 17:58:14 +00005415bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5416 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005417 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005418 return true;
5419
5420 while (Lex.getKind() != lltok::rsquare) {
5421 // If this isn't the first argument, we need a comma.
5422 if (!Args.empty() &&
5423 ParseToken(lltok::comma, "expected ',' in argument list"))
5424 return true;
5425
5426 // Parse the argument.
5427 LocTy ArgLoc;
5428 Type *ArgTy = nullptr;
5429 if (ParseType(ArgTy, ArgLoc))
5430 return true;
5431
5432 Value *V;
5433 if (ArgTy->isMetadataTy()) {
5434 if (ParseMetadataAsValue(V, PFS))
5435 return true;
5436 } else {
5437 if (ParseValue(ArgTy, V, PFS))
5438 return true;
5439 }
5440 Args.push_back(V);
5441 }
5442
5443 Lex.Lex(); // Lex the ']'.
5444 return false;
5445}
5446
5447/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005448/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005449bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005450 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005451
David Majnemer8a1c45d2015-12-12 05:38:55 +00005452 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5453 return true;
5454
5455 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005456 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005457
5458 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5459 return true;
5460
5461 BasicBlock *UnwindBB = nullptr;
5462 if (Lex.getKind() == lltok::kw_to) {
5463 Lex.Lex();
5464 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5465 return true;
5466 } else {
5467 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5468 return true;
5469 }
5470 }
5471
David Majnemer8a1c45d2015-12-12 05:38:55 +00005472 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005473 return false;
5474}
5475
5476/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005477/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005478bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005479 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005480
David Majnemer8a1c45d2015-12-12 05:38:55 +00005481 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5482 return true;
5483
5484 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005485 return true;
5486
David Majnemer0bc0eef2015-08-15 02:46:08 +00005487 BasicBlock *BB;
5488 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5489 ParseTypeAndBasicBlock(BB, PFS))
5490 return true;
5491
David Majnemer8a1c45d2015-12-12 05:38:55 +00005492 Inst = CatchReturnInst::Create(CatchPad, BB);
5493 return false;
5494}
5495
5496/// ParseCatchSwitch
5497/// ::= 'catchswitch' within Parent
5498bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5499 Value *ParentPad;
5500 LocTy BBLoc;
5501
5502 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5503 return true;
5504
5505 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5506 Lex.getKind() != lltok::LocalVarID)
5507 return TokError("expected scope value for catchswitch");
5508
5509 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5510 return true;
5511
5512 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5513 return true;
5514
5515 SmallVector<BasicBlock *, 32> Table;
5516 do {
5517 BasicBlock *DestBB;
5518 if (ParseTypeAndBasicBlock(DestBB, PFS))
5519 return true;
5520 Table.push_back(DestBB);
5521 } while (EatIfPresent(lltok::comma));
5522
5523 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5524 return true;
5525
5526 if (ParseToken(lltok::kw_unwind,
5527 "expected 'unwind' after catchswitch scope"))
5528 return true;
5529
5530 BasicBlock *UnwindBB = nullptr;
5531 if (EatIfPresent(lltok::kw_to)) {
5532 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5533 return true;
5534 } else {
5535 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5536 return true;
5537 }
5538
5539 auto *CatchSwitch =
5540 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5541 for (BasicBlock *DestBB : Table)
5542 CatchSwitch->addHandler(DestBB);
5543 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005544 return false;
5545}
5546
5547/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005548/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005549bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005550 Value *CatchSwitch = nullptr;
5551
5552 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5553 return true;
5554
5555 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5556 return TokError("expected scope value for catchpad");
5557
5558 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5559 return true;
5560
David Majnemer654e1302015-07-31 17:58:14 +00005561 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005562 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005563 return true;
5564
David Majnemer8a1c45d2015-12-12 05:38:55 +00005565 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005566 return false;
5567}
5568
David Majnemer654e1302015-07-31 17:58:14 +00005569/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005570/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005571bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005572 Value *ParentPad = nullptr;
5573
5574 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5575 return true;
5576
5577 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5578 Lex.getKind() != lltok::LocalVarID)
5579 return TokError("expected scope value for cleanuppad");
5580
5581 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5582 return true;
5583
David Majnemer654e1302015-07-31 17:58:14 +00005584 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005585 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005586 return true;
5587
David Majnemer8a1c45d2015-12-12 05:38:55 +00005588 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005589 return false;
5590}
5591
Chris Lattnerac161bf2009-01-02 07:01:27 +00005592//===----------------------------------------------------------------------===//
5593// Binary Operators.
5594//===----------------------------------------------------------------------===//
5595
5596/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005597/// ::= ArithmeticOps TypeAndValue ',' Value
5598///
5599/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5600/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005601bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005602 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005603 LocTy Loc; Value *LHS, *RHS;
5604 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5605 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5606 ParseValue(LHS->getType(), RHS, PFS))
5607 return true;
5608
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005609 bool Valid;
5610 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005611 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005612 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005613 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5614 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005615 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005616 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5617 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005619
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005620 if (!Valid)
5621 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005622
Chris Lattnerac161bf2009-01-02 07:01:27 +00005623 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5624 return false;
5625}
5626
5627/// ParseLogical
5628/// ::= ArithmeticOps TypeAndValue ',' Value {
5629bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5630 unsigned Opc) {
5631 LocTy Loc; Value *LHS, *RHS;
5632 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5633 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5634 ParseValue(LHS->getType(), RHS, PFS))
5635 return true;
5636
Duncan Sands9dff9be2010-02-15 16:12:20 +00005637 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005638 return Error(Loc,"instruction requires integer or integer vector operands");
5639
5640 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5641 return false;
5642}
5643
Chris Lattnerac161bf2009-01-02 07:01:27 +00005644/// ParseCompare
5645/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5646/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5648 unsigned Opc) {
5649 // Parse the integer/fp comparison predicate.
5650 LocTy Loc;
5651 unsigned Pred;
5652 Value *LHS, *RHS;
5653 if (ParseCmpPredicate(Pred, Opc) ||
5654 ParseTypeAndValue(LHS, Loc, PFS) ||
5655 ParseToken(lltok::comma, "expected ',' after compare value") ||
5656 ParseValue(LHS->getType(), RHS, PFS))
5657 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005658
Chris Lattnerac161bf2009-01-02 07:01:27 +00005659 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005660 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005662 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005663 } else {
5664 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005665 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005666 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005668 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005669 }
5670 return false;
5671}
5672
5673//===----------------------------------------------------------------------===//
5674// Other Instructions.
5675//===----------------------------------------------------------------------===//
5676
5677
5678/// ParseCast
5679/// ::= CastOpc TypeAndValue 'to' Type
5680bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5681 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005682 LocTy Loc;
5683 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005684 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005685 if (ParseTypeAndValue(Op, Loc, PFS) ||
5686 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5687 ParseType(DestTy))
5688 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005689
Chris Lattner89d856e2009-03-01 00:53:13 +00005690 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5691 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005693 getTypeString(Op->getType()) + "' to '" +
5694 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005695 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005696 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5697 return false;
5698}
5699
5700/// ParseSelect
5701/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5702bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5703 LocTy Loc;
5704 Value *Op0, *Op1, *Op2;
5705 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5706 ParseToken(lltok::comma, "expected ',' after select condition") ||
5707 ParseTypeAndValue(Op1, PFS) ||
5708 ParseToken(lltok::comma, "expected ',' after select value") ||
5709 ParseTypeAndValue(Op2, PFS))
5710 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005711
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5713 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005714
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 Inst = SelectInst::Create(Op0, Op1, Op2);
5716 return false;
5717}
5718
Chris Lattnerb55ab542009-01-05 08:18:44 +00005719/// ParseVA_Arg
5720/// ::= 'va_arg' TypeAndValue ',' Type
5721bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005722 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005723 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005724 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005725 if (ParseTypeAndValue(Op, PFS) ||
5726 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005727 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005728 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005729
Chris Lattnerb55ab542009-01-05 08:18:44 +00005730 if (!EltTy->isFirstClassType())
5731 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005732
5733 Inst = new VAArgInst(Op, EltTy);
5734 return false;
5735}
5736
5737/// ParseExtractElement
5738/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5739bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5740 LocTy Loc;
5741 Value *Op0, *Op1;
5742 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5743 ParseToken(lltok::comma, "expected ',' after extract value") ||
5744 ParseTypeAndValue(Op1, PFS))
5745 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005746
Chris Lattnerac161bf2009-01-02 07:01:27 +00005747 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5748 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005749
Eric Christopherc9742252009-07-25 02:28:41 +00005750 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005751 return false;
5752}
5753
5754/// ParseInsertElement
5755/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5756bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5757 LocTy Loc;
5758 Value *Op0, *Op1, *Op2;
5759 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5760 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5761 ParseTypeAndValue(Op1, PFS) ||
5762 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5763 ParseTypeAndValue(Op2, PFS))
5764 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005765
Chris Lattnerac161bf2009-01-02 07:01:27 +00005766 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005767 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005768
Chris Lattnerac161bf2009-01-02 07:01:27 +00005769 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5770 return false;
5771}
5772
5773/// ParseShuffleVector
5774/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5775bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5776 LocTy Loc;
5777 Value *Op0, *Op1, *Op2;
5778 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5779 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5780 ParseTypeAndValue(Op1, PFS) ||
5781 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5782 ParseTypeAndValue(Op2, PFS))
5783 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005784
Chris Lattnerac161bf2009-01-02 07:01:27 +00005785 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005786 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005787
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5789 return false;
5790}
5791
5792/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005793/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005794int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005795 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005796 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005797
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005798 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005799 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5800 ParseValue(Ty, Op0, PFS) ||
5801 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005802 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5804 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005805
Chris Lattnerf4f03422009-12-30 05:27:33 +00005806 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005807 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005808
5809 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005810 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005811
Chris Lattner3822f632009-01-02 08:05:26 +00005812 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 break;
5814
Chris Lattnerf4f03422009-12-30 05:27:33 +00005815 if (Lex.getKind() == lltok::MetadataVar) {
5816 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005817 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005818 }
Devang Patel8f842d32009-10-16 18:45:49 +00005819
Chris Lattner3822f632009-01-02 08:05:26 +00005820 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005821 ParseValue(Ty, Op0, PFS) ||
5822 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005823 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005824 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5825 return true;
5826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005827
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 if (!Ty->isFirstClassType())
5829 return Error(TypeLoc, "phi node must have first class type");
5830
Jay Foad52131342011-03-30 11:28:46 +00005831 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005832 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5833 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5834 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005835 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836}
5837
Bill Wendlingfae14752011-08-12 20:24:12 +00005838/// ParseLandingPad
5839/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5840/// Clause
5841/// ::= 'catch' TypeAndValue
5842/// ::= 'filter'
5843/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5844bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005845 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005846
David Majnemer7fddecc2015-06-17 20:52:32 +00005847 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005848 return true;
5849
David Majnemer7fddecc2015-06-17 20:52:32 +00005850 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005851 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5852
5853 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5854 LandingPadInst::ClauseType CT;
5855 if (EatIfPresent(lltok::kw_catch))
5856 CT = LandingPadInst::Catch;
5857 else if (EatIfPresent(lltok::kw_filter))
5858 CT = LandingPadInst::Filter;
5859 else
5860 return TokError("expected 'catch' or 'filter' clause type");
5861
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005862 Value *V;
5863 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005864 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005865 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005866
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005867 // A 'catch' type expects a non-array constant. A filter clause expects an
5868 // array constant.
5869 if (CT == LandingPadInst::Catch) {
5870 if (isa<ArrayType>(V->getType()))
5871 Error(VLoc, "'catch' clause has an invalid type");
5872 } else {
5873 if (!isa<ArrayType>(V->getType()))
5874 Error(VLoc, "'filter' clause has an invalid type");
5875 }
5876
Owen Andersonf8f259d2015-03-09 07:13:42 +00005877 Constant *CV = dyn_cast<Constant>(V);
5878 if (!CV)
5879 return Error(VLoc, "clause argument must be a constant");
5880 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005881 }
5882
Owen Andersonf8f259d2015-03-09 07:13:42 +00005883 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005884 return false;
5885}
5886
Chris Lattnerac161bf2009-01-02 07:01:27 +00005887/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005888/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5889/// OptionalAttrs Type Value ParameterList OptionalAttrs
5890/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5891/// OptionalAttrs Type Value ParameterList OptionalAttrs
5892/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5893/// OptionalAttrs Type Value ParameterList OptionalAttrs
5894/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5895/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005896bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005897 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005898 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005899 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005900 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005901 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005902 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005903 LocTy RetTypeLoc;
5904 ValID CalleeID;
5905 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005906 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005907 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005908
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005909 if (TCK != CallInst::TCK_None &&
5910 ParseToken(lltok::kw_call,
5911 "expected 'tail call', 'musttail call', or 'notail call'"))
5912 return true;
5913
5914 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5915
5916 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005917 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005918 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005919 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5920 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005921 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5922 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005923 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005924
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005925 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5926 return Error(CallLoc, "fast-math-flags specified for call without "
5927 "floating-point scalar or vector return type");
5928
Chris Lattnerac161bf2009-01-02 07:01:27 +00005929 // If RetType is a non-function pointer type, then this is the short syntax
5930 // for the call, which means that RetType is just the return type. Infer the
5931 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005932 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5933 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005934 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005935 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005936 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5937 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005938
Chris Lattnerac161bf2009-01-02 07:01:27 +00005939 if (!FunctionType::isValidReturnType(RetType))
5940 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005941
Owen Anderson4056ca92009-07-29 22:17:13 +00005942 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005943 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005944
David Blaikie41ba2b42015-07-27 23:32:19 +00005945 CalleeID.FTy = Ty;
5946
Chris Lattnerac161bf2009-01-02 07:01:27 +00005947 // Look up the callee.
5948 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005949 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5950 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005951
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005952 // Set up the Attribute for the function.
Reid Kleckner324c99d2017-04-10 20:18:10 +00005953 SmallVector<AttributeSetNode *, 8> Attrs;
5954 Attrs.push_back(AttributeSetNode::get(Context, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005955
Chris Lattnerac161bf2009-01-02 07:01:27 +00005956 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005957
Chris Lattnerac161bf2009-01-02 07:01:27 +00005958 // Loop through FunctionType's arguments and ensure they are specified
5959 // correctly. Also, gather any parameter attributes.
5960 FunctionType::param_iterator I = Ty->param_begin();
5961 FunctionType::param_iterator E = Ty->param_end();
5962 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005963 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005964 if (I != E) {
5965 ExpectedTy = *I++;
5966 } else if (!Ty->isVarArg()) {
5967 return Error(ArgList[i].Loc, "too many arguments specified");
5968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005969
Chris Lattnerac161bf2009-01-02 07:01:27 +00005970 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5971 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005972 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005973 Args.push_back(ArgList[i].V);
Reid Kleckner324c99d2017-04-10 20:18:10 +00005974 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005975 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005976
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977 if (I != E)
5978 return Error(CallLoc, "not enough parameters specified for call");
5979
Reid Kleckner324c99d2017-04-10 20:18:10 +00005980 if (FnAttrs.hasAlignmentAttr())
5981 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005982
Reid Kleckner324c99d2017-04-10 20:18:10 +00005983 Attrs.push_back(AttributeSetNode::get(Context, FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005984
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005985 // Finish off the Attribute and check them
Reid Klecknerb5180542017-03-21 16:57:19 +00005986 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005987
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005988 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005989 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005990 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005991 if (FMF.any())
5992 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005993 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005994 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005995 Inst = CI;
5996 return false;
5997}
5998
5999//===----------------------------------------------------------------------===//
6000// Memory Instructions.
6001//===----------------------------------------------------------------------===//
6002
6003/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006004/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6005/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006006int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006007 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00006008 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006009 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006010 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006011
6012 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006013 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006014
David Majnemera3b0eb22015-02-16 08:38:03 +00006015 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006016
David Majnemera3b0eb22015-02-16 08:38:03 +00006017 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6018 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006019
Chris Lattnerb2f39502009-12-30 05:44:30 +00006020 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006021 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006022 if (Lex.getKind() == lltok::kw_align) {
6023 if (ParseOptionalAlignment(Alignment)) return true;
6024 } else if (Lex.getKind() == lltok::MetadataVar) {
6025 AteExtraComma = true;
6026 } else {
6027 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6028 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6029 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006030 }
6031 }
6032
Dan Gohman2140a742010-05-28 01:14:11 +00006033 if (Size && !Size->getType()->isIntegerTy())
6034 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006035
Reid Kleckner436c42e2014-01-17 23:58:17 +00006036 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
6037 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006038 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006039 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006040 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006041}
6042
6043/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006044/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006045/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006046/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006047int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006048 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006049 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006050 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006051 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006052 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006053 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006054
6055 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006056 isAtomic = true;
6057 Lex.Lex();
6058 }
6059
Chris Lattnerbc639292011-11-27 06:56:53 +00006060 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006061 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006062 isVolatile = true;
6063 Lex.Lex();
6064 }
6065
David Blaikie15d9a4c2015-04-06 20:59:48 +00006066 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006067 LocTy ExplicitTypeLoc = Lex.getLoc();
6068 if (ParseType(Ty) ||
6069 ParseToken(lltok::comma, "expected comma after load's type") ||
6070 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006071 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006072 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6073 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006074
David Blaikie15d9a4c2015-04-06 20:59:48 +00006075 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006076 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006077 if (isAtomic && !Alignment)
6078 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006079 if (Ordering == AtomicOrdering::Release ||
6080 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006081 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006082
David Blaikiea79ac142015-02-27 21:17:42 +00006083 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6084 return Error(ExplicitTypeLoc,
6085 "explicit pointee type doesn't match operand's pointee type");
6086
David Blaikie15d9a4c2015-04-06 20:59:48 +00006087 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006088 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006089}
6090
6091/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006092
6093/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6094/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006095/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006096int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006097 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006098 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006099 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006100 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006101 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006102 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006103
6104 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006105 isAtomic = true;
6106 Lex.Lex();
6107 }
6108
Chris Lattnerbc639292011-11-27 06:56:53 +00006109 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006110 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006111 isVolatile = true;
6112 Lex.Lex();
6113 }
6114
Chris Lattnerac161bf2009-01-02 07:01:27 +00006115 if (ParseTypeAndValue(Val, Loc, PFS) ||
6116 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006117 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006118 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006119 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006120 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006121
Duncan Sands19d0b472010-02-16 11:11:14 +00006122 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006123 return Error(PtrLoc, "store operand must be a pointer");
6124 if (!Val->getType()->isFirstClassType())
6125 return Error(Loc, "store operand must be a first class value");
6126 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6127 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006128 if (isAtomic && !Alignment)
6129 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006130 if (Ordering == AtomicOrdering::Acquire ||
6131 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006132 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006133
Eli Friedman59b66882011-08-09 23:02:53 +00006134 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006135 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006136}
6137
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006138/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006139/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6140/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006141int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006142 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6143 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006144 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6145 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006146 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006147 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006148 bool isWeak = false;
6149
6150 if (EatIfPresent(lltok::kw_weak))
6151 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006152
6153 if (EatIfPresent(lltok::kw_volatile))
6154 isVolatile = true;
6155
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006156 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6157 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6158 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6159 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6160 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006161 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6162 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006163 return true;
6164
JF Bastien800f87a2016-04-06 21:19:33 +00006165 if (SuccessOrdering == AtomicOrdering::Unordered ||
6166 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006167 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006168 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6169 return TokError("cmpxchg failure argument shall be no stronger than the "
6170 "success argument");
6171 if (FailureOrdering == AtomicOrdering::Release ||
6172 FailureOrdering == AtomicOrdering::AcquireRelease)
6173 return TokError(
6174 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006175 if (!Ptr->getType()->isPointerTy())
6176 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6177 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6178 return Error(CmpLoc, "compare value and pointer type do not match");
6179 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6180 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006181 if (!New->getType()->isFirstClassType())
6182 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006183 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6184 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006185 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006186 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006187 Inst = CXI;
6188 return AteExtraComma ? InstExtraComma : InstNormal;
6189}
6190
6191/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006192/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6193/// 'singlethread'? AtomicOrdering
6194int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006195 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6196 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006197 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006198 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006199 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006200 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006201
6202 if (EatIfPresent(lltok::kw_volatile))
6203 isVolatile = true;
6204
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006205 switch (Lex.getKind()) {
6206 default: return TokError("expected binary operation in atomicrmw");
6207 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6208 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6209 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6210 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6211 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6212 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6213 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6214 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6215 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6216 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6217 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6218 }
6219 Lex.Lex(); // Eat the operation.
6220
6221 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6222 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6223 ParseTypeAndValue(Val, ValLoc, PFS) ||
6224 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6225 return true;
6226
JF Bastien800f87a2016-04-06 21:19:33 +00006227 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006228 return TokError("atomicrmw cannot be unordered");
6229 if (!Ptr->getType()->isPointerTy())
6230 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6231 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6232 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6233 if (!Val->getType()->isIntegerTy())
6234 return Error(ValLoc, "atomicrmw operand must be an integer");
6235 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6236 if (Size < 8 || (Size & (Size - 1)))
6237 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6238 " integer");
6239
6240 AtomicRMWInst *RMWI =
6241 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6242 RMWI->setVolatile(isVolatile);
6243 Inst = RMWI;
6244 return AteExtraComma ? InstExtraComma : InstNormal;
6245}
6246
Eli Friedmanfee02c62011-07-25 23:16:38 +00006247/// ParseFence
6248/// ::= 'fence' 'singlethread'? AtomicOrdering
6249int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006250 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006251 SynchronizationScope Scope = CrossThread;
6252 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6253 return true;
6254
JF Bastien800f87a2016-04-06 21:19:33 +00006255 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006256 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006257 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006258 return TokError("fence cannot be monotonic");
6259
6260 Inst = new FenceInst(Context, Ordering, Scope);
6261 return InstNormal;
6262}
6263
Chris Lattnerac161bf2009-01-02 07:01:27 +00006264/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006265/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006266int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006267 Value *Ptr = nullptr;
6268 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006269 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006270
Dan Gohman16cbbe42009-07-29 15:58:36 +00006271 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006272
David Blaikie79e6c742015-02-27 19:29:02 +00006273 Type *Ty = nullptr;
6274 LocTy ExplicitTypeLoc = Lex.getLoc();
6275 if (ParseType(Ty) ||
6276 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6277 ParseTypeAndValue(Ptr, Loc, PFS))
6278 return true;
6279
Eli Benderskyd9806682013-04-22 17:03:42 +00006280 Type *BaseType = Ptr->getType();
6281 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6282 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006283 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006284
David Blaikie8d757942015-03-09 23:08:44 +00006285 if (Ty != BasePointerType->getElementType())
6286 return Error(ExplicitTypeLoc,
6287 "explicit pointee type doesn't match operand's pointee type");
6288
Chris Lattnerac161bf2009-01-02 07:01:27 +00006289 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006290 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006291 // GEP returns a vector of pointers if at least one of parameters is a vector.
6292 // All vector parameters should have the same vector width.
6293 unsigned GEPWidth = BaseType->isVectorTy() ?
6294 BaseType->getVectorNumElements() : 0;
6295
Chris Lattner3822f632009-01-02 08:05:26 +00006296 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006297 if (Lex.getKind() == lltok::MetadataVar) {
6298 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006299 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006300 }
Chris Lattner3822f632009-01-02 08:05:26 +00006301 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006302 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006303 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006304
Nadav Rotem3924cb02011-12-05 06:29:09 +00006305 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006306 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6307 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006308 return Error(EltLoc,
6309 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006310 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006311 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006312 Indices.push_back(Val);
6313 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006314
Craig Toppere3dcce92015-08-01 22:20:21 +00006315 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006316 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006317 return Error(Loc, "base element of getelementptr must be sized");
6318
David Blaikied33bad32015-04-17 22:32:13 +00006319 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006320 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006321 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006322 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006323 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006324 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006325}
6326
6327/// ParseExtractValue
6328/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006329int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006330 Value *Val; LocTy Loc;
6331 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006332 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006333 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006334 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006335 return true;
6336
Chris Lattner392be582010-02-12 20:49:41 +00006337 if (!Val->getType()->isAggregateType())
6338 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006339
Jay Foad57aa6362011-07-13 10:26:04 +00006340 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006341 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006342 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006343 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006344}
6345
6346/// ParseInsertValue
6347/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006348int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006349 Value *Val0, *Val1; LocTy Loc0, Loc1;
6350 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006351 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006352 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6353 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6354 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006355 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006356 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006357
Chris Lattner392be582010-02-12 20:49:41 +00006358 if (!Val0->getType()->isAggregateType())
6359 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006360
David Majnemer30074532015-02-11 07:43:58 +00006361 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6362 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006363 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006364 if (IndexedType != Val1->getType())
6365 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6366 getTypeString(Val1->getType()) + "' instead of '" +
6367 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006368 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006369 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006370}
Nick Lewycky49f89192009-04-04 07:22:01 +00006371
6372//===----------------------------------------------------------------------===//
6373// Embedded metadata.
6374//===----------------------------------------------------------------------===//
6375
6376/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006377/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006378/// Element
6379/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006380bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006381 if (ParseToken(lltok::lbrace, "expected '{' here"))
6382 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006383
Dan Gohman1e0213a2010-07-13 19:33:27 +00006384 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006385 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006386 return false;
6387
Nick Lewycky49f89192009-04-04 07:22:01 +00006388 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006389 // Null is a special case since it is typeless.
6390 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006391 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006392 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006393 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006394
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006395 Metadata *MD;
6396 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006397 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006398 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006399 } while (EatIfPresent(lltok::comma));
6400
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006401 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006402}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006403
6404//===----------------------------------------------------------------------===//
6405// Use-list order directives.
6406//===----------------------------------------------------------------------===//
6407bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6408 SMLoc Loc) {
6409 if (V->use_empty())
6410 return Error(Loc, "value has no uses");
6411
6412 unsigned NumUses = 0;
6413 SmallDenseMap<const Use *, unsigned, 16> Order;
6414 for (const Use &U : V->uses()) {
6415 if (++NumUses > Indexes.size())
6416 break;
6417 Order[&U] = Indexes[NumUses - 1];
6418 }
6419 if (NumUses < 2)
6420 return Error(Loc, "value only has one use");
6421 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6422 return Error(Loc, "wrong number of indexes, expected " +
6423 Twine(std::distance(V->use_begin(), V->use_end())));
6424
6425 V->sortUseList([&](const Use &L, const Use &R) {
6426 return Order.lookup(&L) < Order.lookup(&R);
6427 });
6428 return false;
6429}
6430
6431/// ParseUseListOrderIndexes
6432/// ::= '{' uint32 (',' uint32)+ '}'
6433bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6434 SMLoc Loc = Lex.getLoc();
6435 if (ParseToken(lltok::lbrace, "expected '{' here"))
6436 return true;
6437 if (Lex.getKind() == lltok::rbrace)
6438 return Lex.Error("expected non-empty list of uselistorder indexes");
6439
6440 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6441 // indexes should be distinct numbers in the range [0, size-1], and should
6442 // not be in order.
6443 unsigned Offset = 0;
6444 unsigned Max = 0;
6445 bool IsOrdered = true;
6446 assert(Indexes.empty() && "Expected empty order vector");
6447 do {
6448 unsigned Index;
6449 if (ParseUInt32(Index))
6450 return true;
6451
6452 // Update consistency checks.
6453 Offset += Index - Indexes.size();
6454 Max = std::max(Max, Index);
6455 IsOrdered &= Index == Indexes.size();
6456
6457 Indexes.push_back(Index);
6458 } while (EatIfPresent(lltok::comma));
6459
6460 if (ParseToken(lltok::rbrace, "expected '}' here"))
6461 return true;
6462
6463 if (Indexes.size() < 2)
6464 return Error(Loc, "expected >= 2 uselistorder indexes");
6465 if (Offset != 0 || Max >= Indexes.size())
6466 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6467 if (IsOrdered)
6468 return Error(Loc, "expected uselistorder indexes to change the order");
6469
6470 return false;
6471}
6472
6473/// ParseUseListOrder
6474/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6475bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6476 SMLoc Loc = Lex.getLoc();
6477 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6478 return true;
6479
6480 Value *V;
6481 SmallVector<unsigned, 16> Indexes;
6482 if (ParseTypeAndValue(V, PFS) ||
6483 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6484 ParseUseListOrderIndexes(Indexes))
6485 return true;
6486
6487 return sortUseListOrder(V, Indexes, Loc);
6488}
6489
6490/// ParseUseListOrderBB
6491/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6492bool LLParser::ParseUseListOrderBB() {
6493 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6494 SMLoc Loc = Lex.getLoc();
6495 Lex.Lex();
6496
6497 ValID Fn, Label;
6498 SmallVector<unsigned, 16> Indexes;
6499 if (ParseValID(Fn) ||
6500 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6501 ParseValID(Label) ||
6502 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6503 ParseUseListOrderIndexes(Indexes))
6504 return true;
6505
6506 // Check the function.
6507 GlobalValue *GV;
6508 if (Fn.Kind == ValID::t_GlobalName)
6509 GV = M->getNamedValue(Fn.StrVal);
6510 else if (Fn.Kind == ValID::t_GlobalID)
6511 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6512 else
6513 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6514 if (!GV)
6515 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6516 auto *F = dyn_cast<Function>(GV);
6517 if (!F)
6518 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6519 if (F->isDeclaration())
6520 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6521
6522 // Check the basic block.
6523 if (Label.Kind == ValID::t_LocalID)
6524 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6525 if (Label.Kind != ValID::t_LocalName)
6526 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006527 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006528 if (!V)
6529 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6530 if (!isa<BasicBlock>(V))
6531 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6532
6533 return sortUseListOrder(V, Indexes, Loc);
6534}