blob: 4dc5d81cd088f401e268f6579a0de09f243fe6c1 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000127 AttrBuilder B;
128
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000131
132 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000133 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136
137 FnAttrs.merge(B);
138
139 // If the alignment was parsed as an attribute, move to the alignment
140 // field.
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
144 }
145
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000150 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000153 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000158 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000161 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000164 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
167 Attrs.merge(B);
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000169 } else {
170 llvm_unreachable("invalid object with forward attribute group reference");
171 }
172 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000173
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000179
David Majnemer19b51052015-02-11 07:43:56 +0000180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
195
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
199 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000204 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Devang Pateld2541152009-07-08 19:23:54 +0000206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
215 }
Devang Pateld2541152009-07-08 19:23:54 +0000216
Mehdi Aminie4709272016-09-14 22:29:59 +0000217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000224
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000228
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
237 }
238 }
239
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000240 if (UpgradeDebugInfo)
241 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000242
Manman Renb5d7ff42016-05-25 23:14:48 +0000243 UpgradeModuleFlags(*M);
244
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000245 if (!Slots)
246 return false;
247 // Initialize the slot mapping.
248 // Because by this point we've parsed and validated everything, we can "steal"
249 // the mapping from LLParser as it doesn't need it anymore.
250 Slots->GlobalValues = std::move(NumberedVals);
251 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000252 for (const auto &I : NamedTypes)
253 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
254 for (const auto &I : NumberedTypes)
255 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000256
Chris Lattnerac161bf2009-01-02 07:01:27 +0000257 return false;
258}
259
260//===----------------------------------------------------------------------===//
261// Top-Level Entities
262//===----------------------------------------------------------------------===//
263
264bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000265 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 switch (Lex.getKind()) {
267 default: return TokError("expected top-level entity");
268 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000269 case lltok::kw_declare: if (ParseDeclare()) return true; break;
270 case lltok::kw_define: if (ParseDefine()) return true; break;
271 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
272 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000273 case lltok::kw_source_filename:
274 if (ParseSourceFileName())
275 return true;
276 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000277 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000278 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000279 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000280 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000281 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000282 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000283 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000284 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000285 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000286 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
287 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000288 if (ParseUseListOrderBB())
289 return true;
290 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000291 }
292 }
293}
294
Chris Lattnerac161bf2009-01-02 07:01:27 +0000295/// toplevelentity
296/// ::= 'module' 'asm' STRINGCONSTANT
297bool LLParser::ParseModuleAsm() {
298 assert(Lex.getKind() == lltok::kw_module);
299 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000300
301 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000302 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
303 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000304
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000305 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000306 return false;
307}
308
309/// toplevelentity
310/// ::= 'target' 'triple' '=' STRINGCONSTANT
311/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
312bool LLParser::ParseTargetDefinition() {
313 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000314 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000315 switch (Lex.Lex()) {
316 default: return TokError("unknown target property");
317 case lltok::kw_triple:
318 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000319 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
320 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000321 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000322 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323 return false;
324 case lltok::kw_datalayout:
325 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000326 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
327 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000328 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000329 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000330 return false;
331 }
332}
333
Bill Wendling706d3d62012-11-28 08:41:48 +0000334/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000335/// ::= 'source_filename' '=' STRINGCONSTANT
336bool LLParser::ParseSourceFileName() {
337 assert(Lex.getKind() == lltok::kw_source_filename);
338 std::string Str;
339 Lex.Lex();
340 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
341 ParseStringConstant(Str))
342 return true;
343 M->setSourceFileName(Str);
344 return false;
345}
346
347/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000348/// ::= 'deplibs' '=' '[' ']'
349/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
350/// FIXME: Remove in 4.0. Currently parse, but ignore.
351bool LLParser::ParseDepLibs() {
352 assert(Lex.getKind() == lltok::kw_deplibs);
353 Lex.Lex();
354 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
355 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
356 return true;
357
358 if (EatIfPresent(lltok::rsquare))
359 return false;
360
361 do {
362 std::string Str;
363 if (ParseStringConstant(Str)) return true;
364 } while (EatIfPresent(lltok::comma));
365
366 return ParseToken(lltok::rsquare, "expected ']' at end of list");
367}
368
Dan Gohman466876b2009-08-12 23:32:33 +0000369/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000370/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000372 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000373 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000374 Lex.Lex(); // eat LocalVarID;
375
376 if (ParseToken(lltok::equal, "expected '=' after name") ||
377 ParseToken(lltok::kw_type, "expected 'type' after '='"))
378 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000379
Craig Topper2617dcc2014-04-15 06:32:26 +0000380 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000381 if (ParseStructDefinition(TypeLoc, "",
382 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000383
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000384 if (!isa<StructType>(Result)) {
385 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
386 if (Entry.first)
387 return Error(TypeLoc, "non-struct types may not be recursive");
388 Entry.first = Result;
389 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000390 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000391
Chris Lattnerac161bf2009-01-02 07:01:27 +0000392 return false;
393}
394
395/// toplevelentity
396/// ::= LocalVar '=' 'type' type
397bool LLParser::ParseNamedType() {
398 std::string Name = Lex.getStrVal();
399 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000400 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000401
Chris Lattner3822f632009-01-02 08:05:26 +0000402 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000404 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000405
Craig Topper2617dcc2014-04-15 06:32:26 +0000406 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000407 if (ParseStructDefinition(NameLoc, Name,
408 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000410 if (!isa<StructType>(Result)) {
411 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
412 if (Entry.first)
413 return Error(NameLoc, "non-struct types may not be recursive");
414 Entry.first = Result;
415 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000416 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000417
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000418 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000419}
420
Chris Lattnerac161bf2009-01-02 07:01:27 +0000421/// toplevelentity
422/// ::= 'declare' FunctionHeader
423bool LLParser::ParseDeclare() {
424 assert(Lex.getKind() == lltok::kw_declare);
425 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000426
Peter Collingbourne21521892016-06-21 23:42:48 +0000427 std::vector<std::pair<unsigned, MDNode *>> MDs;
428 while (Lex.getKind() == lltok::MetadataVar) {
429 unsigned MDK;
430 MDNode *N;
431 if (ParseMetadataAttachment(MDK, N))
432 return true;
433 MDs.push_back({MDK, N});
434 }
435
Chris Lattnerac161bf2009-01-02 07:01:27 +0000436 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000437 if (ParseFunctionHeader(F, false))
438 return true;
439 for (auto &MD : MDs)
440 F->addMetadata(MD.first, *MD.second);
441 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000442}
443
444/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000445/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000446bool LLParser::ParseDefine() {
447 assert(Lex.getKind() == lltok::kw_define);
448 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000449
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000451 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000452 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000453 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454}
455
Chris Lattner3822f632009-01-02 08:05:26 +0000456/// ParseGlobalType
457/// ::= 'constant'
458/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000459bool LLParser::ParseGlobalType(bool &IsConstant) {
460 if (Lex.getKind() == lltok::kw_constant)
461 IsConstant = true;
462 else if (Lex.getKind() == lltok::kw_global)
463 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000464 else {
465 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000466 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000467 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000468 Lex.Lex();
469 return false;
470}
471
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000472bool LLParser::ParseOptionalUnnamedAddr(
473 GlobalVariable::UnnamedAddr &UnnamedAddr) {
474 if (EatIfPresent(lltok::kw_unnamed_addr))
475 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
476 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
477 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
478 else
479 UnnamedAddr = GlobalValue::UnnamedAddr::None;
480 return false;
481}
482
Dan Gohman466876b2009-08-12 23:32:33 +0000483/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000484/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000485/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
486/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000487/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000488/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
489/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000490bool LLParser::ParseUnnamedGlobal() {
491 unsigned VarID = NumberedVals.size();
492 std::string Name;
493 LocTy NameLoc = Lex.getLoc();
494
495 // Handle the GlobalID form.
496 if (Lex.getKind() == lltok::GlobalID) {
497 if (Lex.getUIntVal() != VarID)
498 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000499 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000500 Lex.Lex(); // eat GlobalID;
501
502 if (ParseToken(lltok::equal, "expected '=' after name"))
503 return true;
504 }
505
506 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000507 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000508 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000509 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000510 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000511 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000512 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000513
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000514 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000515 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000516 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000517
518 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
519 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000520}
521
Chris Lattnerac161bf2009-01-02 07:01:27 +0000522/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000523/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000524/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
525/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000526bool LLParser::ParseNamedGlobal() {
527 assert(Lex.getKind() == lltok::GlobalVar);
528 LocTy NameLoc = Lex.getLoc();
529 std::string Name = Lex.getStrVal();
530 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000531
Chris Lattnerac161bf2009-01-02 07:01:27 +0000532 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000533 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000534 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000535 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000536 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000537 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000538 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000539 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000540
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000541 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000542 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000543 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000544
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000545 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
546 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000547}
548
David Majnemerdad0a642014-06-27 18:19:56 +0000549bool LLParser::parseComdat() {
550 assert(Lex.getKind() == lltok::ComdatVar);
551 std::string Name = Lex.getStrVal();
552 LocTy NameLoc = Lex.getLoc();
553 Lex.Lex();
554
555 if (ParseToken(lltok::equal, "expected '=' here"))
556 return true;
557
558 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
559 return TokError("expected comdat type");
560
561 Comdat::SelectionKind SK;
562 switch (Lex.getKind()) {
563 default:
564 return TokError("unknown selection kind");
565 case lltok::kw_any:
566 SK = Comdat::Any;
567 break;
568 case lltok::kw_exactmatch:
569 SK = Comdat::ExactMatch;
570 break;
571 case lltok::kw_largest:
572 SK = Comdat::Largest;
573 break;
574 case lltok::kw_noduplicates:
575 SK = Comdat::NoDuplicates;
576 break;
577 case lltok::kw_samesize:
578 SK = Comdat::SameSize;
579 break;
580 }
581 Lex.Lex();
582
583 // See if the comdat was forward referenced, if so, use the comdat.
584 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
585 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
586 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
587 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
588
589 Comdat *C;
590 if (I != ComdatSymTab.end())
591 C = &I->second;
592 else
593 C = M->getOrInsertComdat(Name);
594 C->setSelectionKind(SK);
595
596 return false;
597}
598
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000599// MDString:
600// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000601bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000602 std::string Str;
603 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000604 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000605 return false;
606}
607
608// MDNode:
609// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000610bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000611 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000612 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000613 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000614 if (ParseUInt32(MID))
615 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000616
Chris Lattner8eff0152010-04-01 05:14:45 +0000617 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000618 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000619 Result = NumberedMetadata[MID];
620 return false;
621 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000622
Chris Lattner8eff0152010-04-01 05:14:45 +0000623 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000624 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000625 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000626
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000627 Result = FwdRef.first.get();
628 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000629 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000630}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000631
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000632/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000633/// !foo = !{ !1, !2 }
634bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000635 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000636 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000637 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000638
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000639 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000640 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000641 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000642 return true;
643
Dan Gohman2637cc12010-07-21 23:38:33 +0000644 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000645 if (Lex.getKind() != lltok::rbrace)
646 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000647 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000648 // Parse DIExpressions inline as a special case. They are still MDNodes,
649 // so they can still appear in named metadata. Remove this logic if they
650 // become plain Metadata.
651 if (Lex.getKind() == lltok::MetadataVar &&
652 Lex.getStrVal() == "DIExpression") {
653 if (ParseDIExpression(N, /*IsDistinct=*/false))
654 return true;
655 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
656 ParseMDNodeID(N)) {
657 return true;
658 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000659 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000660 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000661
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000662 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000663}
664
Devang Patel39e64d42009-07-01 19:21:12 +0000665/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000666/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000667bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000668 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000669 Lex.Lex();
670 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000671
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000672 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000673 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000674 ParseToken(lltok::equal, "expected '=' here"))
675 return true;
676
677 // Detect common error, from old metadata syntax.
678 if (Lex.getKind() == lltok::Type)
679 return TokError("unexpected type in metadata definition");
680
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000681 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000682 if (Lex.getKind() == lltok::MetadataVar) {
683 if (ParseSpecializedMDNode(Init, IsDistinct))
684 return true;
685 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
686 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000687 return true;
688
Chris Lattnerfc58af22009-12-30 04:51:58 +0000689 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000690 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000691 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000692 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000693 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000694
Chris Lattnerfc58af22009-12-30 04:51:58 +0000695 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
696 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000697 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000698 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000699 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000700 }
701
Devang Patel39e64d42009-07-01 19:21:12 +0000702 return false;
703}
704
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000705static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
706 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
707 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
708}
709
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000710/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000711/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
712/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000713/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000714///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000715/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000716/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000717///
Eric Christopher536f0a92015-05-28 23:07:39 +0000718/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000720bool LLParser::parseIndirectSymbol(
721 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
722 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
723 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000724 bool IsAlias;
725 if (Lex.getKind() == lltok::kw_alias)
726 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000727 else if (Lex.getKind() == lltok::kw_ifunc)
728 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000729 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000730 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000731 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000732
Rafael Espindola78527052013-10-06 15:10:43 +0000733 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
734
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000735 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000736 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000738 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000739 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000740 "symbol with local linkage must have default visibility");
741
David Blaikie2f408302015-09-11 03:22:04 +0000742 Type *Ty;
743 LocTy ExplicitTypeLoc = Lex.getLoc();
744 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000745 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000746 return true;
747
Rafael Espindola64c1e182014-06-03 02:41:57 +0000748 Constant *Aliasee;
749 LocTy AliaseeLoc = Lex.getLoc();
750 if (Lex.getKind() != lltok::kw_bitcast &&
751 Lex.getKind() != lltok::kw_getelementptr &&
752 Lex.getKind() != lltok::kw_addrspacecast &&
753 Lex.getKind() != lltok::kw_inttoptr) {
754 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000755 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000757 // The bitcast dest type is not present, it is implied by the dest type.
758 ValID ID;
759 if (ParseValID(ID))
760 return true;
761 if (ID.Kind != ValID::t_Constant)
762 return Error(AliaseeLoc, "invalid aliasee");
763 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000764 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000765
Rafael Espindola64c1e182014-06-03 02:41:57 +0000766 Type *AliaseeType = Aliasee->getType();
767 auto *PTy = dyn_cast<PointerType>(AliaseeType);
768 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000769 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000770 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000771
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000772 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000773 return Error(
774 ExplicitTypeLoc,
775 "explicit pointee type doesn't match operand's pointee type");
776
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000777 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
778 return Error(
779 ExplicitTypeLoc,
780 "explicit pointee type should be a function type");
781
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000782 GlobalValue *GVal = nullptr;
783
784 // See if the alias was forward referenced, if so, prepare to replace the
785 // forward reference.
786 if (!Name.empty()) {
787 GVal = M->getNamedValue(Name);
788 if (GVal) {
789 if (!ForwardRefVals.erase(Name))
790 return Error(NameLoc, "redefinition of global '@" + Name + "'");
791 }
792 } else {
793 auto I = ForwardRefValIDs.find(NumberedVals.size());
794 if (I != ForwardRefValIDs.end()) {
795 GVal = I->second.first;
796 ForwardRefValIDs.erase(I);
797 }
798 }
799
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000801 std::unique_ptr<GlobalIndirectSymbol> GA;
802 if (IsAlias)
803 GA.reset(GlobalAlias::create(Ty, AddrSpace,
804 (GlobalValue::LinkageTypes)Linkage, Name,
805 Aliasee, /*Parent*/ nullptr));
806 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000807 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
808 (GlobalValue::LinkageTypes)Linkage, Name,
809 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000810 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000811 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000812 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000813 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000814
Rafael Espindola54fc2982015-06-17 17:53:31 +0000815 if (Name.empty())
816 NumberedVals.push_back(GA.get());
817
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000818 if (GVal) {
819 // Verify that types agree.
820 if (GVal->getType() != GA->getType())
821 return Error(
822 ExplicitTypeLoc,
823 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 // If they agree, just RAUW the old value with the alias and remove the
826 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000827 GVal->replaceAllUsesWith(GA.get());
828 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000829 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000830
Chris Lattnerac161bf2009-01-02 07:01:27 +0000831 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000832 if (IsAlias)
833 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
834 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000835 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000836 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000837
Rafael Espindolaaa273822014-05-09 21:49:17 +0000838 // The module owns this now
839 GA.release();
840
Chris Lattnerac161bf2009-01-02 07:01:27 +0000841 return false;
842}
843
844/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000845/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000846/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000847/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Nico Rieck7157bb72014-01-14 15:22:47 +0000848/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000849/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000850/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000851///
Eric Christopher536f0a92015-05-28 23:07:39 +0000852/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000853/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854///
855bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
856 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000857 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000858 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000859 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000860 if (!isValidVisibilityForLinkage(Visibility, Linkage))
861 return Error(NameLoc,
862 "symbol with local linkage must have default visibility");
863
Chris Lattnerac161bf2009-01-02 07:01:27 +0000864 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000865 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000866 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000868
Craig Topper2617dcc2014-04-15 06:32:26 +0000869 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000870 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000871 ParseOptionalToken(lltok::kw_externally_initialized,
872 IsExternallyInitialized,
873 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000874 ParseGlobalType(IsConstant) ||
875 ParseType(Ty, TyLoc))
876 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000877
Chris Lattnerac161bf2009-01-02 07:01:27 +0000878 // If the linkage is specified and is external, then no initializer is
879 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000880 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000881 if (!HasLinkage ||
882 !GlobalValue::isValidDeclarationLinkage(
883 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884 if (ParseGlobalValue(Ty, Init))
885 return true;
886 }
887
David Majnemer49b3d9b2015-02-16 08:41:08 +0000888 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000889 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000890
David Majnemer598bd052014-12-09 05:56:09 +0000891 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892
893 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000894 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000895 GVal = M->getNamedValue(Name);
896 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000897 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000898 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000899 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000901 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000902 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000903 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000904 ForwardRefValIDs.erase(I);
905 }
906 }
907
David Majnemer598bd052014-12-09 05:56:09 +0000908 GlobalVariable *GV;
909 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000910 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
911 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000912 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000913 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000914 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000915 return Error(TyLoc,
916 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000917
David Majnemer598bd052014-12-09 05:56:09 +0000918 GV = cast<GlobalVariable>(GVal);
919
Chris Lattnerac161bf2009-01-02 07:01:27 +0000920 // Move the forward-reference to the correct spot in the module.
921 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
922 }
923
924 if (Name.empty())
925 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000926
Chris Lattnerac161bf2009-01-02 07:01:27 +0000927 // Set the parsed properties on the global.
928 if (Init)
929 GV->setInitializer(Init);
930 GV->setConstant(IsConstant);
931 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
932 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000933 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000934 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000935 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000936 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000937
Chris Lattnerac161bf2009-01-02 07:01:27 +0000938 // Parse attributes on the global.
939 while (Lex.getKind() == lltok::comma) {
940 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000941
Chris Lattnerac161bf2009-01-02 07:01:27 +0000942 if (Lex.getKind() == lltok::kw_section) {
943 Lex.Lex();
944 GV->setSection(Lex.getStrVal());
945 if (ParseToken(lltok::StringConstant, "expected global section string"))
946 return true;
947 } else if (Lex.getKind() == lltok::kw_align) {
948 unsigned Alignment;
949 if (ParseOptionalAlignment(Alignment)) return true;
950 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000951 } else if (Lex.getKind() == lltok::MetadataVar) {
952 if (ParseGlobalObjectMetadataAttachment(*GV))
953 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000954 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000955 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000956 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000957 return true;
958 if (C)
959 GV->setComdat(C);
960 else
961 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000962 }
963 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000964
Javed Absarf3d79042017-05-11 12:28:08 +0000965 AttrBuilder Attrs;
966 LocTy BuiltinLoc;
967 std::vector<unsigned> FwdRefAttrGrps;
968 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
969 return true;
970 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
971 GV->setAttributes(AttributeSet::get(Context, Attrs));
972 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
973 }
974
Chris Lattnerac161bf2009-01-02 07:01:27 +0000975 return false;
976}
977
Bill Wendling63b88192013-02-06 06:52:58 +0000978/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000979/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000980bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000981 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000982 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000983 Lex.Lex();
984
David Majnemerb39e22b2014-12-09 18:33:57 +0000985 if (Lex.getKind() != lltok::AttrGrpID)
986 return TokError("expected attribute group id");
987
Bill Wendling63b88192013-02-06 06:52:58 +0000988 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000989 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000990 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000991 Lex.Lex();
992
993 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000994 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000995 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000996 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000997 ParseToken(lltok::rbrace, "expected end of attribute group"))
998 return true;
999
Bill Wendlingb32b0412013-02-08 06:32:06 +00001000 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001001 return Error(AttrGrpLoc, "attribute group has no attributes");
1002
1003 return false;
1004}
1005
Bill Wendling8b0321d2013-02-08 00:52:31 +00001006/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001007/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001008bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1009 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001010 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001011 bool HaveError = false;
1012
1013 B.clear();
1014
Bill Wendling63b88192013-02-06 06:52:58 +00001015 while (true) {
1016 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001017 if (Token == lltok::kw_builtin)
1018 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001019 switch (Token) {
1020 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001021 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001022 return Error(Lex.getLoc(), "unterminated attribute group");
1023 case lltok::rbrace:
1024 // Finished.
1025 return false;
1026
Bill Wendlingb32b0412013-02-08 06:32:06 +00001027 case lltok::AttrGrpID: {
1028 // Allow a function to reference an attribute group:
1029 //
1030 // define void @foo() #1 { ... }
1031 if (inAttrGrp)
1032 HaveError |=
1033 Error(Lex.getLoc(),
1034 "cannot have an attribute group reference in an attribute group");
1035
1036 unsigned AttrGrpNum = Lex.getUIntVal();
1037 if (inAttrGrp) break;
1038
1039 // Save the reference to the attribute group. We'll fill it in later.
1040 FwdRefAttrGrps.push_back(AttrGrpNum);
1041 break;
1042 }
Bill Wendling63b88192013-02-06 06:52:58 +00001043 // Target-dependent attributes:
1044 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001045 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001046 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001047 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001048 }
1049
1050 // Target-independent attributes:
1051 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001052 // As a hack, we allow function alignment to be initially parsed as an
1053 // attribute on a function declaration/definition or added to an attribute
1054 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001055 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001056 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001057 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001058 if (ParseToken(lltok::equal, "expected '=' here") ||
1059 ParseUInt32(Alignment))
1060 return true;
1061 } else {
1062 if (ParseOptionalAlignment(Alignment))
1063 return true;
1064 }
Bill Wendling63b88192013-02-06 06:52:58 +00001065 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001066 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001067 }
1068 case lltok::kw_alignstack: {
1069 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001070 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001071 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001072 if (ParseToken(lltok::equal, "expected '=' here") ||
1073 ParseUInt32(Alignment))
1074 return true;
1075 } else {
1076 if (ParseOptionalStackAlignment(Alignment))
1077 return true;
1078 }
Bill Wendling63b88192013-02-06 06:52:58 +00001079 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001080 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001081 }
George Burgess IV278199f2016-04-12 01:05:35 +00001082 case lltok::kw_allocsize: {
1083 unsigned ElemSizeArg;
1084 Optional<unsigned> NumElemsArg;
1085 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1086 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1087 return true;
1088 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1089 continue;
1090 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001091 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1092 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1093 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1094 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1095 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001096 case lltok::kw_inaccessiblememonly:
1097 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1098 case lltok::kw_inaccessiblemem_or_argmemonly:
1099 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001100 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1101 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1102 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1103 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1104 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1105 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1106 case lltok::kw_noimplicitfloat:
1107 B.addAttribute(Attribute::NoImplicitFloat); break;
1108 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1109 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1110 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1111 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001112 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001113 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1114 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1115 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1116 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1117 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1118 case lltok::kw_returns_twice:
1119 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001120 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001121 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1122 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1123 case lltok::kw_sspstrong:
1124 B.addAttribute(Attribute::StackProtectStrong); break;
1125 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1126 case lltok::kw_sanitize_address:
1127 B.addAttribute(Attribute::SanitizeAddress); break;
1128 case lltok::kw_sanitize_thread:
1129 B.addAttribute(Attribute::SanitizeThread); break;
1130 case lltok::kw_sanitize_memory:
1131 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001132 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001133 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001134 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001135
1136 // Error handling.
1137 case lltok::kw_inreg:
1138 case lltok::kw_signext:
1139 case lltok::kw_zeroext:
1140 HaveError |=
1141 Error(Lex.getLoc(),
1142 "invalid use of attribute on a function");
1143 break;
1144 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001145 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001146 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001147 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001148 case lltok::kw_nest:
1149 case lltok::kw_noalias:
1150 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001151 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001152 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001153 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001154 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001155 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001156 HaveError |=
1157 Error(Lex.getLoc(),
1158 "invalid use of parameter-only attribute on a function");
1159 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001160 }
1161
1162 Lex.Lex();
1163 }
1164}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001165
1166//===----------------------------------------------------------------------===//
1167// GlobalValue Reference/Resolution Routines.
1168//===----------------------------------------------------------------------===//
1169
Karl Schimpf77729782015-09-03 18:06:44 +00001170static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1171 const std::string &Name) {
1172 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1173 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1174 else
1175 return new GlobalVariable(*M, PTy->getElementType(), false,
1176 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1177 nullptr, GlobalVariable::NotThreadLocal,
1178 PTy->getAddressSpace());
1179}
1180
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181/// GetGlobalVal - Get a value with the specified name or ID, creating a
1182/// forward reference record if needed. This can return null if the value
1183/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001184GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001185 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001186 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001187 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001188 Error(Loc, "global variable reference must have pointer type");
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 // Look this name up in the normal function symbol table.
1193 GlobalValue *Val =
1194 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001195
Chris Lattnerac161bf2009-01-02 07:01:27 +00001196 // If this is a forward reference for the value, see if we already created a
1197 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001198 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001199 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 if (I != ForwardRefVals.end())
1201 Val = I->second.first;
1202 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001203
Chris Lattnerac161bf2009-01-02 07:01:27 +00001204 // If we have the value in the symbol table or fwd-ref table, return it.
1205 if (Val) {
1206 if (Val->getType() == Ty) return Val;
1207 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001208 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001209 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001211
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001213 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1215 return FwdVal;
1216}
1217
Chris Lattner229907c2011-07-18 04:54:35 +00001218GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1219 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001220 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001221 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001222 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001223 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001224
Craig Topper2617dcc2014-04-15 06:32:26 +00001225 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001226
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 // If this is a forward reference for the value, see if we already created a
1228 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001229 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001230 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231 if (I != ForwardRefValIDs.end())
1232 Val = I->second.first;
1233 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001234
Chris Lattnerac161bf2009-01-02 07:01:27 +00001235 // If we have the value in the symbol table or fwd-ref table, return it.
1236 if (Val) {
1237 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001238 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001239 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001240 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001241 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001242
Chris Lattnerac161bf2009-01-02 07:01:27 +00001243 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001244 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001245 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1246 return FwdVal;
1247}
1248
Chris Lattnerac161bf2009-01-02 07:01:27 +00001249//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001250// Comdat Reference/Resolution Routines.
1251//===----------------------------------------------------------------------===//
1252
1253Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1254 // Look this name up in the comdat symbol table.
1255 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1256 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1257 if (I != ComdatSymTab.end())
1258 return &I->second;
1259
1260 // Otherwise, create a new forward reference for this value and remember it.
1261 Comdat *C = M->getOrInsertComdat(Name);
1262 ForwardRefComdats[Name] = Loc;
1263 return C;
1264}
1265
David Majnemerdad0a642014-06-27 18:19:56 +00001266//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001267// Helper Routines.
1268//===----------------------------------------------------------------------===//
1269
1270/// ParseToken - If the current token has the specified kind, eat it and return
1271/// success. Otherwise, emit the specified error and return failure.
1272bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1273 if (Lex.getKind() != T)
1274 return TokError(ErrMsg);
1275 Lex.Lex();
1276 return false;
1277}
1278
Chris Lattner3822f632009-01-02 08:05:26 +00001279/// ParseStringConstant
1280/// ::= StringConstant
1281bool LLParser::ParseStringConstant(std::string &Result) {
1282 if (Lex.getKind() != lltok::StringConstant)
1283 return TokError("expected string constant");
1284 Result = Lex.getStrVal();
1285 Lex.Lex();
1286 return false;
1287}
1288
1289/// ParseUInt32
1290/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001291bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001292 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1293 return TokError("expected integer");
1294 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1295 if (Val64 != unsigned(Val64))
1296 return TokError("expected 32-bit integer (too large)");
1297 Val = Val64;
1298 Lex.Lex();
1299 return false;
1300}
1301
Hal Finkelb0407ba2014-07-18 15:51:28 +00001302/// ParseUInt64
1303/// ::= uint64
1304bool LLParser::ParseUInt64(uint64_t &Val) {
1305 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1306 return TokError("expected integer");
1307 Val = Lex.getAPSIntVal().getLimitedValue();
1308 Lex.Lex();
1309 return false;
1310}
1311
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001312/// ParseTLSModel
1313/// := 'localdynamic'
1314/// := 'initialexec'
1315/// := 'localexec'
1316bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1317 switch (Lex.getKind()) {
1318 default:
1319 return TokError("expected localdynamic, initialexec or localexec");
1320 case lltok::kw_localdynamic:
1321 TLM = GlobalVariable::LocalDynamicTLSModel;
1322 break;
1323 case lltok::kw_initialexec:
1324 TLM = GlobalVariable::InitialExecTLSModel;
1325 break;
1326 case lltok::kw_localexec:
1327 TLM = GlobalVariable::LocalExecTLSModel;
1328 break;
1329 }
1330
1331 Lex.Lex();
1332 return false;
1333}
1334
1335/// ParseOptionalThreadLocal
1336/// := /*empty*/
1337/// := 'thread_local'
1338/// := 'thread_local' '(' tlsmodel ')'
1339bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1340 TLM = GlobalVariable::NotThreadLocal;
1341 if (!EatIfPresent(lltok::kw_thread_local))
1342 return false;
1343
1344 TLM = GlobalVariable::GeneralDynamicTLSModel;
1345 if (Lex.getKind() == lltok::lparen) {
1346 Lex.Lex();
1347 return ParseTLSModel(TLM) ||
1348 ParseToken(lltok::rparen, "expected ')' after thread local model");
1349 }
1350 return false;
1351}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001352
1353/// ParseOptionalAddrSpace
1354/// := /*empty*/
1355/// := 'addrspace' '(' uint32 ')'
1356bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1357 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001358 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001359 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001360 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001361 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001362 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001363}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001364
Artur Pilipenko17376c42015-08-03 14:31:49 +00001365/// ParseStringAttribute
1366/// := StringConstant
1367/// := StringConstant '=' StringConstant
1368bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1369 std::string Attr = Lex.getStrVal();
1370 Lex.Lex();
1371 std::string Val;
1372 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1373 return true;
1374 B.addAttribute(Attr, Val);
1375 return false;
1376}
1377
Bill Wendling34c2eb22012-12-04 23:40:58 +00001378/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1379bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1380 bool HaveError = false;
1381
1382 B.clear();
1383
Eugene Zelenko1804a772016-08-25 00:45:04 +00001384 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001385 lltok::Kind Token = Lex.getKind();
1386 switch (Token) {
1387 default: // End of attributes.
1388 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001389 case lltok::StringConstant: {
1390 if (ParseStringAttribute(B))
1391 return true;
1392 continue;
1393 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001394 case lltok::kw_align: {
1395 unsigned Alignment;
1396 if (ParseOptionalAlignment(Alignment))
1397 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001398 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001399 continue;
1400 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001401 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001402 case lltok::kw_dereferenceable: {
1403 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001404 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001405 return true;
1406 B.addDereferenceableAttr(Bytes);
1407 continue;
1408 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001409 case lltok::kw_dereferenceable_or_null: {
1410 uint64_t Bytes;
1411 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1412 return true;
1413 B.addDereferenceableOrNullAttr(Bytes);
1414 continue;
1415 }
Reid Klecknera534a382013-12-19 02:14:12 +00001416 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001417 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1418 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1419 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1420 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001421 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001422 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1423 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001424 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001425 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1426 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001427 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001428 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001429 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001430 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001431
Stephen Lin7577ed52013-04-20 13:16:13 +00001432 case lltok::kw_alignstack:
1433 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001434 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001435 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001436 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001437 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001438 case lltok::kw_minsize:
1439 case lltok::kw_naked:
1440 case lltok::kw_nobuiltin:
1441 case lltok::kw_noduplicate:
1442 case lltok::kw_noimplicitfloat:
1443 case lltok::kw_noinline:
1444 case lltok::kw_nonlazybind:
1445 case lltok::kw_noredzone:
1446 case lltok::kw_noreturn:
1447 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001448 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001449 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001450 case lltok::kw_returns_twice:
1451 case lltok::kw_sanitize_address:
1452 case lltok::kw_sanitize_memory:
1453 case lltok::kw_sanitize_thread:
1454 case lltok::kw_ssp:
1455 case lltok::kw_sspreq:
1456 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001457 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001458 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001459 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001460 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1461 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001462 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001463
Bill Wendling34c2eb22012-12-04 23:40:58 +00001464 Lex.Lex();
1465 }
1466}
1467
1468/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1469bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1470 bool HaveError = false;
1471
1472 B.clear();
1473
Eugene Zelenko1804a772016-08-25 00:45:04 +00001474 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001475 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001476 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001477 default: // End of attributes.
1478 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001479 case lltok::StringConstant: {
1480 if (ParseStringAttribute(B))
1481 return true;
1482 continue;
1483 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001484 case lltok::kw_dereferenceable: {
1485 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001486 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001487 return true;
1488 B.addDereferenceableAttr(Bytes);
1489 continue;
1490 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001491 case lltok::kw_dereferenceable_or_null: {
1492 uint64_t Bytes;
1493 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1494 return true;
1495 B.addDereferenceableOrNullAttr(Bytes);
1496 continue;
1497 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001498 case lltok::kw_align: {
1499 unsigned Alignment;
1500 if (ParseOptionalAlignment(Alignment))
1501 return true;
1502 B.addAlignmentAttr(Alignment);
1503 continue;
1504 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001505 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1506 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001507 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001508 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1509 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001510
Bill Wendling34c2eb22012-12-04 23:40:58 +00001511 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001512 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001513 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001514 case lltok::kw_nest:
1515 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001516 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001517 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001518 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001519 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001520 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001521 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001522
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001523 case lltok::kw_alignstack:
1524 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001525 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001526 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001527 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001528 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001529 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001530 case lltok::kw_minsize:
1531 case lltok::kw_naked:
1532 case lltok::kw_nobuiltin:
1533 case lltok::kw_noduplicate:
1534 case lltok::kw_noimplicitfloat:
1535 case lltok::kw_noinline:
1536 case lltok::kw_nonlazybind:
1537 case lltok::kw_noredzone:
1538 case lltok::kw_noreturn:
1539 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001540 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001541 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001542 case lltok::kw_returns_twice:
1543 case lltok::kw_sanitize_address:
1544 case lltok::kw_sanitize_memory:
1545 case lltok::kw_sanitize_thread:
1546 case lltok::kw_ssp:
1547 case lltok::kw_sspreq:
1548 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001549 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001550 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001551 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001552 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001553 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001554
1555 case lltok::kw_readnone:
1556 case lltok::kw_readonly:
1557 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001558 }
1559
Chris Lattnerac161bf2009-01-02 07:01:27 +00001560 Lex.Lex();
1561 }
1562}
1563
Rafael Espindolac6269912016-05-10 17:16:45 +00001564static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1565 HasLinkage = true;
1566 switch (Kind) {
1567 default:
1568 HasLinkage = false;
1569 return GlobalValue::ExternalLinkage;
1570 case lltok::kw_private:
1571 return GlobalValue::PrivateLinkage;
1572 case lltok::kw_internal:
1573 return GlobalValue::InternalLinkage;
1574 case lltok::kw_weak:
1575 return GlobalValue::WeakAnyLinkage;
1576 case lltok::kw_weak_odr:
1577 return GlobalValue::WeakODRLinkage;
1578 case lltok::kw_linkonce:
1579 return GlobalValue::LinkOnceAnyLinkage;
1580 case lltok::kw_linkonce_odr:
1581 return GlobalValue::LinkOnceODRLinkage;
1582 case lltok::kw_available_externally:
1583 return GlobalValue::AvailableExternallyLinkage;
1584 case lltok::kw_appending:
1585 return GlobalValue::AppendingLinkage;
1586 case lltok::kw_common:
1587 return GlobalValue::CommonLinkage;
1588 case lltok::kw_extern_weak:
1589 return GlobalValue::ExternalWeakLinkage;
1590 case lltok::kw_external:
1591 return GlobalValue::ExternalLinkage;
1592 }
1593}
1594
Chris Lattnerac161bf2009-01-02 07:01:27 +00001595/// ParseOptionalLinkage
1596/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001597/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001598/// ::= 'internal'
1599/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001600/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001601/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001602/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001603/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001604/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001605/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606/// ::= 'extern_weak'
1607/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001608bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1609 unsigned &Visibility,
1610 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001611 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1612 if (HasLinkage)
1613 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001614 ParseOptionalVisibility(Visibility);
1615 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001616 return false;
1617}
1618
1619/// ParseOptionalVisibility
1620/// ::= /*empty*/
1621/// ::= 'default'
1622/// ::= 'hidden'
1623/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001624///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001625void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001626 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001627 default:
1628 Res = GlobalValue::DefaultVisibility;
1629 return;
1630 case lltok::kw_default:
1631 Res = GlobalValue::DefaultVisibility;
1632 break;
1633 case lltok::kw_hidden:
1634 Res = GlobalValue::HiddenVisibility;
1635 break;
1636 case lltok::kw_protected:
1637 Res = GlobalValue::ProtectedVisibility;
1638 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001639 }
1640 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001641}
1642
Nico Rieck7157bb72014-01-14 15:22:47 +00001643/// ParseOptionalDLLStorageClass
1644/// ::= /*empty*/
1645/// ::= 'dllimport'
1646/// ::= 'dllexport'
1647///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001648void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001649 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001650 default:
1651 Res = GlobalValue::DefaultStorageClass;
1652 return;
1653 case lltok::kw_dllimport:
1654 Res = GlobalValue::DLLImportStorageClass;
1655 break;
1656 case lltok::kw_dllexport:
1657 Res = GlobalValue::DLLExportStorageClass;
1658 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001659 }
1660 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001661}
1662
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663/// ParseOptionalCallingConv
1664/// ::= /*empty*/
1665/// ::= 'ccc'
1666/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001667/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001668/// ::= 'coldcc'
1669/// ::= 'x86_stdcallcc'
1670/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001671/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001672/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001673/// ::= 'arm_apcscc'
1674/// ::= 'arm_aapcscc'
1675/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001676/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001677/// ::= 'avr_intrcc'
1678/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001679/// ::= 'ptx_kernel'
1680/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001681/// ::= 'spir_func'
1682/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001683/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001684/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001685/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001686/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001687/// ::= 'preserve_mostcc'
1688/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001689/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001690/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001691/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001692/// ::= 'hhvmcc'
1693/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001694/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001695/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001696/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001697/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001698/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001699/// ::= 'amdgpu_gs'
1700/// ::= 'amdgpu_ps'
1701/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001702/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001703/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001704///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001705bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001706 switch (Lex.getKind()) {
1707 default: CC = CallingConv::C; return false;
1708 case lltok::kw_ccc: CC = CallingConv::C; break;
1709 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1710 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1711 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1712 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001713 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001714 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001715 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001716 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1717 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1718 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001719 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001720 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1721 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001722 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1723 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001724 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1725 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001726 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001727 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001728 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001729 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001730 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001731 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1732 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001733 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001734 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001735 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001736 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1737 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001738 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001739 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001740 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001741 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001742 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001743 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1744 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1745 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001746 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001747 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001748 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001749 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001750 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001752
Chris Lattnerac161bf2009-01-02 07:01:27 +00001753 Lex.Lex();
1754 return false;
1755}
1756
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001757/// ParseMetadataAttachment
1758/// ::= !dbg !42
1759bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1760 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1761
1762 std::string Name = Lex.getStrVal();
1763 Kind = M->getMDKindID(Name);
1764 Lex.Lex();
1765
1766 return ParseMDNode(MD);
1767}
1768
Chris Lattner5c427632009-12-30 05:31:19 +00001769/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001770/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001771bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001772 do {
1773 if (Lex.getKind() != lltok::MetadataVar)
1774 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001775
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001776 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001777 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001778 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001779 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001780
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001781 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001782 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001783 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001784
Chris Lattner596760d2009-12-29 21:25:40 +00001785 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001786 } while (EatIfPresent(lltok::comma));
1787 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001788}
1789
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001790/// ParseGlobalObjectMetadataAttachment
1791/// ::= !dbg !57
1792bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1793 unsigned MDK;
1794 MDNode *N;
1795 if (ParseMetadataAttachment(MDK, N))
1796 return true;
1797
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001798 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001799 return false;
1800}
1801
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001802/// ParseOptionalFunctionMetadata
1803/// ::= (!dbg !57)*
1804bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001805 while (Lex.getKind() == lltok::MetadataVar)
1806 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001807 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001808 return false;
1809}
1810
Chris Lattnerac161bf2009-01-02 07:01:27 +00001811/// ParseOptionalAlignment
1812/// ::= /* empty */
1813/// ::= 'align' 4
1814bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1815 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001816 if (!EatIfPresent(lltok::kw_align))
1817 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001818 LocTy AlignLoc = Lex.getLoc();
1819 if (ParseUInt32(Alignment)) return true;
1820 if (!isPowerOf2_32(Alignment))
1821 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001822 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001823 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001824 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001825}
1826
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001827/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001828/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001829/// ::= AttrKind '(' 4 ')'
1830///
1831/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1832bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1833 uint64_t &Bytes) {
1834 assert((AttrKind == lltok::kw_dereferenceable ||
1835 AttrKind == lltok::kw_dereferenceable_or_null) &&
1836 "contract!");
1837
Hal Finkelb0407ba2014-07-18 15:51:28 +00001838 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001839 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001840 return false;
1841 LocTy ParenLoc = Lex.getLoc();
1842 if (!EatIfPresent(lltok::lparen))
1843 return Error(ParenLoc, "expected '('");
1844 LocTy DerefLoc = Lex.getLoc();
1845 if (ParseUInt64(Bytes)) return true;
1846 ParenLoc = Lex.getLoc();
1847 if (!EatIfPresent(lltok::rparen))
1848 return Error(ParenLoc, "expected ')'");
1849 if (!Bytes)
1850 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1851 return false;
1852}
1853
Chris Lattnerb2f39502009-12-30 05:44:30 +00001854/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001855/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001856/// ::= ',' align 4
1857///
1858/// This returns with AteExtraComma set to true if it ate an excess comma at the
1859/// end.
1860bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1861 bool &AteExtraComma) {
1862 AteExtraComma = false;
1863 while (EatIfPresent(lltok::comma)) {
1864 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001865 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001866 AteExtraComma = true;
1867 return false;
1868 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001869
Chris Lattner95b0ff42010-04-23 00:50:50 +00001870 if (Lex.getKind() != lltok::kw_align)
1871 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001872
Chris Lattner95b0ff42010-04-23 00:50:50 +00001873 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001874 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001875
Devang Patelea8a4b92009-09-17 23:04:48 +00001876 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001877}
1878
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001879/// ParseOptionalCommaAddrSpace
1880/// ::=
1881/// ::= ',' addrspace(1)
1882///
1883/// This returns with AteExtraComma set to true if it ate an excess comma at the
1884/// end.
1885bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1886 LocTy &Loc,
1887 bool &AteExtraComma) {
1888 AteExtraComma = false;
1889 while (EatIfPresent(lltok::comma)) {
1890 // Metadata at the end is an early exit.
1891 if (Lex.getKind() == lltok::MetadataVar) {
1892 AteExtraComma = true;
1893 return false;
1894 }
1895
1896 Loc = Lex.getLoc();
1897 if (Lex.getKind() != lltok::kw_addrspace)
1898 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1899
1900 if (ParseOptionalAddrSpace(AddrSpace))
1901 return true;
1902 }
1903
1904 return false;
1905}
1906
George Burgess IV278199f2016-04-12 01:05:35 +00001907bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1908 Optional<unsigned> &HowManyArg) {
1909 Lex.Lex();
1910
1911 auto StartParen = Lex.getLoc();
1912 if (!EatIfPresent(lltok::lparen))
1913 return Error(StartParen, "expected '('");
1914
1915 if (ParseUInt32(BaseSizeArg))
1916 return true;
1917
1918 if (EatIfPresent(lltok::comma)) {
1919 auto HowManyAt = Lex.getLoc();
1920 unsigned HowMany;
1921 if (ParseUInt32(HowMany))
1922 return true;
1923 if (HowMany == BaseSizeArg)
1924 return Error(HowManyAt,
1925 "'allocsize' indices can't refer to the same parameter");
1926 HowManyArg = HowMany;
1927 } else
1928 HowManyArg = None;
1929
1930 auto EndParen = Lex.getLoc();
1931 if (!EatIfPresent(lltok::rparen))
1932 return Error(EndParen, "expected ')'");
1933 return false;
1934}
1935
Eli Friedmanfee02c62011-07-25 23:16:38 +00001936/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001937/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00001938/// else: ::=
1939///
1940/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001941bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00001942 AtomicOrdering &Ordering) {
1943 if (!isAtomic)
1944 return false;
1945
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001946 return ParseScope(SSID) || ParseOrdering(Ordering);
1947}
Tim Northovere94a5182014-03-11 10:48:52 +00001948
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001949/// ParseScope
1950/// ::= syncscope("singlethread" | "<target scope>")?
1951///
1952/// This sets synchronization scope ID to the ID of the parsed value.
1953bool LLParser::ParseScope(SyncScope::ID &SSID) {
1954 SSID = SyncScope::System;
1955 if (EatIfPresent(lltok::kw_syncscope)) {
1956 auto StartParenAt = Lex.getLoc();
1957 if (!EatIfPresent(lltok::lparen))
1958 return Error(StartParenAt, "Expected '(' in syncscope");
1959
1960 std::string SSN;
1961 auto SSNAt = Lex.getLoc();
1962 if (ParseStringConstant(SSN))
1963 return Error(SSNAt, "Expected synchronization scope name");
1964
1965 auto EndParenAt = Lex.getLoc();
1966 if (!EatIfPresent(lltok::rparen))
1967 return Error(EndParenAt, "Expected ')' in syncscope");
1968
1969 SSID = Context.getOrInsertSyncScopeID(SSN);
1970 }
1971
1972 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00001973}
1974
1975/// ParseOrdering
1976/// ::= AtomicOrdering
1977///
1978/// This sets Ordering to the parsed value.
1979bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001980 switch (Lex.getKind()) {
1981 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001982 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1983 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1984 // Not specified yet:
1985 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1986 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1987 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1988 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1989 case lltok::kw_seq_cst:
1990 Ordering = AtomicOrdering::SequentiallyConsistent;
1991 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001992 }
1993 Lex.Lex();
1994 return false;
1995}
1996
Charles Davisbe5557e2010-02-12 00:31:15 +00001997/// ParseOptionalStackAlignment
1998/// ::= /* empty */
1999/// ::= 'alignstack' '(' 4 ')'
2000bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2001 Alignment = 0;
2002 if (!EatIfPresent(lltok::kw_alignstack))
2003 return false;
2004 LocTy ParenLoc = Lex.getLoc();
2005 if (!EatIfPresent(lltok::lparen))
2006 return Error(ParenLoc, "expected '('");
2007 LocTy AlignLoc = Lex.getLoc();
2008 if (ParseUInt32(Alignment)) return true;
2009 ParenLoc = Lex.getLoc();
2010 if (!EatIfPresent(lltok::rparen))
2011 return Error(ParenLoc, "expected ')'");
2012 if (!isPowerOf2_32(Alignment))
2013 return Error(AlignLoc, "stack alignment is not a power of two");
2014 return false;
2015}
Devang Patelea8a4b92009-09-17 23:04:48 +00002016
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002017/// ParseIndexList - This parses the index list for an insert/extractvalue
2018/// instruction. This sets AteExtraComma in the case where we eat an extra
2019/// comma at the end of the line and find that it is followed by metadata.
2020/// Clients that don't allow metadata can call the version of this function that
2021/// only takes one argument.
2022///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023/// ParseIndexList
2024/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002025///
2026bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2027 bool &AteExtraComma) {
2028 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002029
Chris Lattnerac161bf2009-01-02 07:01:27 +00002030 if (Lex.getKind() != lltok::comma)
2031 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002032
Chris Lattner3822f632009-01-02 08:05:26 +00002033 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002034 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002035 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002036 AteExtraComma = true;
2037 return false;
2038 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002039 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002040 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002041 Indices.push_back(Idx);
2042 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002043
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044 return false;
2045}
2046
2047//===----------------------------------------------------------------------===//
2048// Type Parsing.
2049//===----------------------------------------------------------------------===//
2050
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002052bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054 switch (Lex.getKind()) {
2055 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002056 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002060 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 // Type ::= StructType
2064 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 return true;
2066 break;
2067 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002068 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069 Lex.Lex(); // eat the lsquare.
2070 if (ParseArrayVectorType(Result, false))
2071 return true;
2072 break;
2073 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002075 Lex.Lex();
2076 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002078 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 } else if (ParseArrayVectorType(Result, true))
2081 return true;
2082 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 case lltok::LocalVar: {
2084 // Type ::= %foo
2085 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002086
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002087 // If the type hasn't been defined yet, create a forward definition and
2088 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002089 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002090 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002093 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094 Lex.Lex();
2095 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002096 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002097
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002098 case lltok::LocalVarID: {
2099 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002100 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002102 // If the type hasn't been defined yet, create a forward definition and
2103 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002104 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002105 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002106 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002108 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002109 Lex.Lex();
2110 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 }
2112 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
2114 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002115 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 switch (Lex.getKind()) {
2117 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002118 default:
2119 if (!AllowVoid && Result->isVoidTy())
2120 return Error(TypeLoc, "void type only allowed for function results");
2121 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002123 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002125 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002126 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002127 if (Result->isVoidTy())
2128 return TokError("pointers to void are invalid - use i8* instead");
2129 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002130 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002131 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132 Lex.Lex();
2133 break;
2134
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002135 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002137 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002139 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002140 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002141 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002142 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002143 unsigned AddrSpace;
2144 if (ParseOptionalAddrSpace(AddrSpace) ||
2145 ParseToken(lltok::star, "expected '*' in address space"))
2146 return true;
2147
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002148 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 break;
2150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2153 case lltok::lparen:
2154 if (ParseFunctionType(Result))
2155 return true;
2156 break;
2157 }
2158 }
2159}
2160
2161/// ParseParameterList
2162/// ::= '(' ')'
2163/// ::= '(' Arg (',' Arg)* ')'
2164/// Arg
2165/// ::= Type OptionalAttributes Value OptionalAttributes
2166bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002167 PerFunctionState &PFS, bool IsMustTailCall,
2168 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 if (ParseToken(lltok::lparen, "expected '(' in call"))
2170 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002171
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 while (Lex.getKind() != lltok::rparen) {
2173 // If this isn't the first argument, we need a comma.
2174 if (!ArgList.empty() &&
2175 ParseToken(lltok::comma, "expected ',' in argument list"))
2176 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002177
Reid Kleckner83498642014-08-26 00:33:28 +00002178 // Parse an ellipsis if this is a musttail call in a variadic function.
2179 if (Lex.getKind() == lltok::dotdotdot) {
2180 const char *Msg = "unexpected ellipsis in argument list for ";
2181 if (!IsMustTailCall)
2182 return TokError(Twine(Msg) + "non-musttail call");
2183 if (!InVarArgsFunc)
2184 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2185 Lex.Lex(); // Lex the '...', it is purely for readability.
2186 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2187 }
2188
Chris Lattnerac161bf2009-01-02 07:01:27 +00002189 // Parse the argument.
2190 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002191 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002192 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002194 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002196
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002197 if (ArgTy->isMetadataTy()) {
2198 if (ParseMetadataAsValue(V, PFS))
2199 return true;
2200 } else {
2201 // Otherwise, handle normal operands.
2202 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2203 return true;
2204 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002205 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002206 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 }
2208
Reid Kleckner83498642014-08-26 00:33:28 +00002209 if (IsMustTailCall && InVarArgsFunc)
2210 return TokError("expected '...' at end of argument list for musttail call "
2211 "in varargs function");
2212
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 Lex.Lex(); // Lex the ')'.
2214 return false;
2215}
2216
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002217/// ParseOptionalOperandBundles
2218/// ::= /*empty*/
2219/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2220///
2221/// OperandBundle
2222/// ::= bundle-tag '(' ')'
2223/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2224///
2225/// bundle-tag ::= String Constant
2226bool LLParser::ParseOptionalOperandBundles(
2227 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2228 LocTy BeginLoc = Lex.getLoc();
2229 if (!EatIfPresent(lltok::lsquare))
2230 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002232 while (Lex.getKind() != lltok::rsquare) {
2233 // If this isn't the first operand bundle, we need a comma.
2234 if (!BundleList.empty() &&
2235 ParseToken(lltok::comma, "expected ',' in input list"))
2236 return true;
2237
2238 std::string Tag;
2239 if (ParseStringConstant(Tag))
2240 return true;
2241
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002242 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2243 return true;
2244
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002245 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002246 while (Lex.getKind() != lltok::rparen) {
2247 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002248 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002249 ParseToken(lltok::comma, "expected ',' in input list"))
2250 return true;
2251
2252 Type *Ty = nullptr;
2253 Value *Input = nullptr;
2254 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2255 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002256 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002257 }
2258
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002259 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2260
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002261 Lex.Lex(); // Lex the ')'.
2262 }
2263
2264 if (BundleList.empty())
2265 return Error(BeginLoc, "operand bundle set must not be empty");
2266
2267 Lex.Lex(); // Lex the ']'.
2268 return false;
2269}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270
Chris Lattner2ed06b42009-01-05 18:34:07 +00002271/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002272/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273/// ::= '(' ArgTypeListI ')'
2274/// ArgTypeListI
2275/// ::= /*empty*/
2276/// ::= '...'
2277/// ::= ArgTypeList ',' '...'
2278/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002279///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2281 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 isVarArg = false;
2283 assert(Lex.getKind() == lltok::lparen);
2284 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002285
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 if (Lex.getKind() == lltok::rparen) {
2287 // empty
2288 } else if (Lex.getKind() == lltok::dotdotdot) {
2289 isVarArg = true;
2290 Lex.Lex();
2291 } else {
2292 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002293 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002294 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002296
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002297 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002298 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattnerfdd87902009-10-05 05:54:46 +00002300 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002301 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Chris Lattnerdef19492011-06-17 06:36:20 +00002303 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 Name = Lex.getStrVal();
2305 Lex.Lex();
2306 }
Chris Lattner3822f632009-01-02 08:05:26 +00002307
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002308 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002309 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002311 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002312 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002313 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
Chris Lattner3822f632009-01-02 08:05:26 +00002315 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002317 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002318 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002319 break;
2320 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002321
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322 // Otherwise must be an argument type.
2323 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002324 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002325
Chris Lattnerfdd87902009-10-05 05:54:46 +00002326 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002327 return Error(TypeLoc, "argument can not have void type");
2328
Chris Lattnerdef19492011-06-17 06:36:20 +00002329 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002330 Name = Lex.getStrVal();
2331 Lex.Lex();
2332 } else {
2333 Name = "";
2334 }
Chris Lattner3822f632009-01-02 08:05:26 +00002335
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002336 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002337 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002338
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002339 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002340 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002341 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 }
2343 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002344
Chris Lattner3822f632009-01-02 08:05:26 +00002345 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002347
Chris Lattnerac161bf2009-01-02 07:01:27 +00002348/// ParseFunctionType
2349/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002350bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351 assert(Lex.getKind() == lltok::lparen);
2352
Chris Lattnerce473c72009-01-05 08:04:33 +00002353 if (!FunctionType::isValidReturnType(Result))
2354 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002356 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002357 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002358 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002360
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361 // Reject names on the arguments lists.
2362 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2363 if (!ArgList[i].Name.empty())
2364 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002365 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002366 return Error(ArgList[i].Loc,
2367 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369
Jay Foadb804a2b2011-07-12 14:06:48 +00002370 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002372 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002373
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002374 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 return false;
2376}
2377
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002378/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2379/// other structs.
2380bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2381 SmallVector<Type*, 8> Elts;
2382 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002383
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002384 Result = StructType::get(Context, Elts, Packed);
2385 return false;
2386}
2387
2388/// ParseStructDefinition - Parse a struct in a 'type' definition.
2389bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2390 std::pair<Type*, LocTy> &Entry,
2391 Type *&ResultTy) {
2392 // If the type was already defined, diagnose the redefinition.
2393 if (Entry.first && !Entry.second.isValid())
2394 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 // If we have opaque, just return without filling in the definition for the
2397 // struct. This counts as a definition as far as the .ll file goes.
2398 if (EatIfPresent(lltok::kw_opaque)) {
2399 // This type is being defined, so clear the location to indicate this.
2400 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002401
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002402 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002403 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002404 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002405 ResultTy = Entry.first;
2406 return false;
2407 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002409 // If the type starts with '<', then it is either a packed struct or a vector.
2410 bool isPacked = EatIfPresent(lltok::less);
2411
2412 // If we don't have a struct, then we have a random type alias, which we
2413 // accept for compatibility with old files. These types are not allowed to be
2414 // forward referenced and not allowed to be recursive.
2415 if (Lex.getKind() != lltok::lbrace) {
2416 if (Entry.first)
2417 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002418
Craig Topper2617dcc2014-04-15 06:32:26 +00002419 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002420 if (isPacked)
2421 return ParseArrayVectorType(ResultTy, true);
2422 return ParseType(ResultTy);
2423 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002424
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002425 // This type is being defined, so clear the location to indicate this.
2426 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002427
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002428 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002429 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002430 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002431
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002432 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002433
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002434 SmallVector<Type*, 8> Body;
2435 if (ParseStructBody(Body) ||
2436 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2437 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002438
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002439 STy->setBody(Body, isPacked);
2440 ResultTy = STy;
2441 return false;
2442}
2443
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002445/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002447/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002449/// ::= '<' '{' Type (',' Type)* '}' '>'
2450bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451 assert(Lex.getKind() == lltok::lbrace);
2452 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002454 // Handle the empty struct.
2455 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457
Chris Lattnerf880ca22009-03-09 04:49:14 +00002458 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002459 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002460 if (ParseType(Ty)) return true;
2461 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002462
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002463 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002464 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002465
Chris Lattner3822f632009-01-02 08:05:26 +00002466 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002467 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002468 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002469
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002470 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002471 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002472
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002473 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002474 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002475
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002476 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002477}
2478
2479/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2480/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002481/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002482/// ::= '[' APSINTVAL 'x' Types ']'
2483/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002484bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2486 Lex.getAPSIntVal().getBitWidth() > 64)
2487 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 LocTy SizeLoc = Lex.getLoc();
2490 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002491 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002492
Chris Lattner3822f632009-01-02 08:05:26 +00002493 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2494 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495
2496 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002497 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002498 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002499
Chris Lattner3822f632009-01-02 08:05:26 +00002500 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2501 "expected end of sequential type"))
2502 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002503
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002505 if (Size == 0)
2506 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 if ((unsigned)Size != Size)
2508 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002509 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002510 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002511 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002513 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002514 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002515 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 }
2517 return false;
2518}
2519
2520//===----------------------------------------------------------------------===//
2521// Function Semantic Analysis.
2522//===----------------------------------------------------------------------===//
2523
Chris Lattner3432c622009-10-28 03:39:23 +00002524LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2525 int functionNumber)
2526 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002527
2528 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002529 for (Argument &A : F.args())
2530 if (!A.hasName())
2531 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002532}
2533
2534LLParser::PerFunctionState::~PerFunctionState() {
2535 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002536
David Blaikie9ebdc692015-09-21 21:07:50 +00002537 for (const auto &P : ForwardRefVals) {
2538 if (isa<BasicBlock>(P.second.first))
2539 continue;
2540 P.second.first->replaceAllUsesWith(
2541 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002542 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002543 }
2544
2545 for (const auto &P : ForwardRefValIDs) {
2546 if (isa<BasicBlock>(P.second.first))
2547 continue;
2548 P.second.first->replaceAllUsesWith(
2549 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002550 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002551 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552}
2553
Chris Lattner3432c622009-10-28 03:39:23 +00002554bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 if (!ForwardRefVals.empty())
2556 return P.Error(ForwardRefVals.begin()->second.second,
2557 "use of undefined value '%" + ForwardRefVals.begin()->first +
2558 "'");
2559 if (!ForwardRefValIDs.empty())
2560 return P.Error(ForwardRefValIDs.begin()->second.second,
2561 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002562 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 return false;
2564}
2565
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566/// GetVal - Get a value with the specified name or ID, creating a
2567/// forward reference record if needed. This can return null if the value
2568/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002569Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002570 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002571 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002572 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002573
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 // If this is a forward reference for the value, see if we already created a
2575 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002576 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002577 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002578 if (I != ForwardRefVals.end())
2579 Val = I->second.first;
2580 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002581
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 // If we have the value in the symbol table or fwd-ref table, return it.
2583 if (Val) {
2584 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002585 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586 P.Error(Loc, "'%" + Name + "' is not a basic block");
2587 else
2588 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002589 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002590 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002592
Chris Lattnerac161bf2009-01-02 07:01:27 +00002593 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002594 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002596 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002598
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 // Otherwise, create a new forward reference for this value and remember it.
2600 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002601 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002602 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002603 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002604 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002605 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002606
Chris Lattnerac161bf2009-01-02 07:01:27 +00002607 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2608 return FwdVal;
2609}
2610
David Majnemer8a1c45d2015-12-12 05:38:55 +00002611Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002613 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002614
Chris Lattnerac161bf2009-01-02 07:01:27 +00002615 // If this is a forward reference for the value, see if we already created a
2616 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002617 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002618 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 if (I != ForwardRefValIDs.end())
2620 Val = I->second.first;
2621 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002622
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 // If we have the value in the symbol table or fwd-ref table, return it.
2624 if (Val) {
2625 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002626 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002627 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002628 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002629 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002630 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002631 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002633
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002634 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002635 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002636 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002638
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 // Otherwise, create a new forward reference for this value and remember it.
2640 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002641 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002642 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002643 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002644 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002645 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2648 return FwdVal;
2649}
2650
2651/// SetInstName - After an instruction is parsed and inserted into its
2652/// basic block, this installs its name.
2653bool LLParser::PerFunctionState::SetInstName(int NameID,
2654 const std::string &NameStr,
2655 LocTy NameLoc, Instruction *Inst) {
2656 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002657 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 if (NameID != -1 || !NameStr.empty())
2659 return P.Error(NameLoc, "instructions returning void cannot have a name");
2660 return false;
2661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002662
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 // If this was a numbered instruction, verify that the instruction is the
2664 // expected value and resolve any forward references.
2665 if (NameStr.empty()) {
2666 // If neither a name nor an ID was specified, just use the next ID.
2667 if (NameID == -1)
2668 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 if (unsigned(NameID) != NumberedVals.size())
2671 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002672 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
David Blaikie9ebdc692015-09-21 21:07:50 +00002674 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002676 Value *Sentinel = FI->second.first;
2677 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002678 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002679 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002680
2681 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002682 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 ForwardRefValIDs.erase(FI);
2684 }
2685
2686 NumberedVals.push_back(Inst);
2687 return false;
2688 }
2689
2690 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002691 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002693 Value *Sentinel = FI->second.first;
2694 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002695 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002696 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002697
2698 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002699 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 ForwardRefVals.erase(FI);
2701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002702
Chris Lattnerac161bf2009-01-02 07:01:27 +00002703 // Set the name on the instruction.
2704 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002706 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002707 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 NameStr + "'");
2709 return false;
2710}
2711
2712/// GetBB - Get a basic block with the specified name or ID, creating a
2713/// forward reference record if needed.
2714BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2715 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002716 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2717 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002718}
2719
2720BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002721 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2722 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002723}
2724
2725/// DefineBB - Define the specified basic block, which is either named or
2726/// unnamed. If there is an error, this returns null otherwise it returns
2727/// the block being defined.
2728BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2729 LocTy Loc) {
2730 BasicBlock *BB;
2731 if (Name.empty())
2732 BB = GetBB(NumberedVals.size(), Loc);
2733 else
2734 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002735 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002736
Chris Lattnerac161bf2009-01-02 07:01:27 +00002737 // Move the block to the end of the function. Forward ref'd blocks are
2738 // inserted wherever they happen to be referenced.
2739 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002740
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 // Remove the block from forward ref sets.
2742 if (Name.empty()) {
2743 ForwardRefValIDs.erase(NumberedVals.size());
2744 NumberedVals.push_back(BB);
2745 } else {
2746 // BB forward references are already in the function symbol table.
2747 ForwardRefVals.erase(Name);
2748 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002749
Chris Lattnerac161bf2009-01-02 07:01:27 +00002750 return BB;
2751}
2752
2753//===----------------------------------------------------------------------===//
2754// Constants.
2755//===----------------------------------------------------------------------===//
2756
2757/// ParseValID - Parse an abstract value that doesn't necessarily have a
2758/// type implied. For example, if we parse "4" we don't know what integer type
2759/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002760/// sanity. PFS is used to convert function-local operands of metadata (since
2761/// metadata operands are not just parsed here but also converted to values).
2762/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002763bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002764 ID.Loc = Lex.getLoc();
2765 switch (Lex.getKind()) {
2766 default: return TokError("expected value token");
2767 case lltok::GlobalID: // @42
2768 ID.UIntVal = Lex.getUIntVal();
2769 ID.Kind = ValID::t_GlobalID;
2770 break;
2771 case lltok::GlobalVar: // @foo
2772 ID.StrVal = Lex.getStrVal();
2773 ID.Kind = ValID::t_GlobalName;
2774 break;
2775 case lltok::LocalVarID: // %42
2776 ID.UIntVal = Lex.getUIntVal();
2777 ID.Kind = ValID::t_LocalID;
2778 break;
2779 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 ID.StrVal = Lex.getStrVal();
2781 ID.Kind = ValID::t_LocalName;
2782 break;
2783 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002784 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002785 ID.Kind = ValID::t_APSInt;
2786 break;
2787 case lltok::APFloat:
2788 ID.APFloatVal = Lex.getAPFloatVal();
2789 ID.Kind = ValID::t_APFloat;
2790 break;
2791 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002792 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 ID.Kind = ValID::t_Constant;
2794 break;
2795 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002796 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002797 ID.Kind = ValID::t_Constant;
2798 break;
2799 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2800 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2801 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002802 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002803
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 case lltok::lbrace: {
2805 // ValID ::= '{' ConstVector '}'
2806 Lex.Lex();
2807 SmallVector<Constant*, 16> Elts;
2808 if (ParseGlobalValueVector(Elts) ||
2809 ParseToken(lltok::rbrace, "expected end of struct constant"))
2810 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811
David Blaikieadbda4b2015-08-03 20:08:41 +00002812 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002813 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002814 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2815 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002816 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 return false;
2818 }
2819 case lltok::less: {
2820 // ValID ::= '<' ConstVector '>' --> Vector.
2821 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2822 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002823 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002824
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 SmallVector<Constant*, 16> Elts;
2826 LocTy FirstEltLoc = Lex.getLoc();
2827 if (ParseGlobalValueVector(Elts) ||
2828 (isPackedStruct &&
2829 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2830 ParseToken(lltok::greater, "expected end of constant"))
2831 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002834 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2835 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2836 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002837 ID.UIntVal = Elts.size();
2838 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002839 return false;
2840 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002841
Chris Lattnerac161bf2009-01-02 07:01:27 +00002842 if (Elts.empty())
2843 return Error(ID.Loc, "constant vector must not be empty");
2844
Duncan Sands9dff9be2010-02-15 16:12:20 +00002845 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002846 !Elts[0]->getType()->isFloatingPointTy() &&
2847 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002848 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002849 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002850
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 // Verify that all the vector elements have the same type.
2852 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2853 if (Elts[i]->getType() != Elts[0]->getType())
2854 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002855 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002856 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002857
Chris Lattner69229312011-02-15 00:14:00 +00002858 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002859 ID.Kind = ValID::t_Constant;
2860 return false;
2861 }
2862 case lltok::lsquare: { // Array Constant
2863 Lex.Lex();
2864 SmallVector<Constant*, 16> Elts;
2865 LocTy FirstEltLoc = Lex.getLoc();
2866 if (ParseGlobalValueVector(Elts) ||
2867 ParseToken(lltok::rsquare, "expected end of array constant"))
2868 return true;
2869
2870 // Handle empty element.
2871 if (Elts.empty()) {
2872 // Use undef instead of an array because it's inconvenient to determine
2873 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002874 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002875 return false;
2876 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002877
Chris Lattnerac161bf2009-01-02 07:01:27 +00002878 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002879 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002880 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002881
Owen Anderson4056ca92009-07-29 22:17:13 +00002882 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002883
Chris Lattnerac161bf2009-01-02 07:01:27 +00002884 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002885 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002886 if (Elts[i]->getType() != Elts[0]->getType())
2887 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002888 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002889 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002890 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002891
Jay Foad83be3612011-06-22 09:24:39 +00002892 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 ID.Kind = ValID::t_Constant;
2894 return false;
2895 }
2896 case lltok::kw_c: // c "foo"
2897 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002898 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2899 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002900 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2901 ID.Kind = ValID::t_Constant;
2902 return false;
2903
2904 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002905 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2906 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002907 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002908 Lex.Lex();
2909 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002910 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002911 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002912 ParseStringConstant(ID.StrVal) ||
2913 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 ParseToken(lltok::StringConstant, "expected constraint string"))
2915 return true;
2916 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002917 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002918 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002919 ID.Kind = ValID::t_InlineAsm;
2920 return false;
2921 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002922
Chris Lattner3432c622009-10-28 03:39:23 +00002923 case lltok::kw_blockaddress: {
2924 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2925 Lex.Lex();
2926
2927 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002928
Chris Lattner3432c622009-10-28 03:39:23 +00002929 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2930 ParseValID(Fn) ||
2931 ParseToken(lltok::comma, "expected comma in block address expression")||
2932 ParseValID(Label) ||
2933 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2934 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002935
Chris Lattner3432c622009-10-28 03:39:23 +00002936 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2937 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002938 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002939 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002940
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002941 // Try to find the function (but skip it if it's forward-referenced).
2942 GlobalValue *GV = nullptr;
2943 if (Fn.Kind == ValID::t_GlobalID) {
2944 if (Fn.UIntVal < NumberedVals.size())
2945 GV = NumberedVals[Fn.UIntVal];
2946 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2947 GV = M->getNamedValue(Fn.StrVal);
2948 }
2949 Function *F = nullptr;
2950 if (GV) {
2951 // Confirm that it's actually a function with a definition.
2952 if (!isa<Function>(GV))
2953 return Error(Fn.Loc, "expected function name in blockaddress");
2954 F = cast<Function>(GV);
2955 if (F->isDeclaration())
2956 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2957 }
2958
2959 if (!F) {
2960 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002961 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002962 ForwardRefBlockAddresses.insert(std::make_pair(
2963 std::move(Fn),
2964 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002965 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2966 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002967 if (!FwdRef)
2968 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2969 GlobalValue::InternalLinkage, nullptr, "");
2970 ID.ConstantVal = FwdRef;
2971 ID.Kind = ValID::t_Constant;
2972 return false;
2973 }
2974
2975 // We found the function; now find the basic block. Don't use PFS, since we
2976 // might be inside a constant expression.
2977 BasicBlock *BB;
2978 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2979 if (Label.Kind == ValID::t_LocalID)
2980 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2981 else
2982 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2983 if (!BB)
2984 return Error(Label.Loc, "referenced value is not a basic block");
2985 } else {
2986 if (Label.Kind == ValID::t_LocalID)
2987 return Error(Label.Loc, "cannot take address of numeric label after "
2988 "the function is defined");
2989 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002990 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002991 if (!BB)
2992 return Error(Label.Loc, "referenced value is not a basic block");
2993 }
2994
2995 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002996 ID.Kind = ValID::t_Constant;
2997 return false;
2998 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002999
Chris Lattnerac161bf2009-01-02 07:01:27 +00003000 case lltok::kw_trunc:
3001 case lltok::kw_zext:
3002 case lltok::kw_sext:
3003 case lltok::kw_fptrunc:
3004 case lltok::kw_fpext:
3005 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003006 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 case lltok::kw_uitofp:
3008 case lltok::kw_sitofp:
3009 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003010 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003011 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003014 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003015 Constant *SrcVal;
3016 Lex.Lex();
3017 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3018 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003019 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 ParseType(DestTy) ||
3021 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3022 return true;
3023 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3024 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003025 getTypeString(SrcVal->getType()) + "' to '" +
3026 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003027 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003028 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 ID.Kind = ValID::t_Constant;
3030 return false;
3031 }
3032 case lltok::kw_extractvalue: {
3033 Lex.Lex();
3034 Constant *Val;
3035 SmallVector<unsigned, 4> Indices;
3036 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3037 ParseGlobalTypeAndValue(Val) ||
3038 ParseIndexList(Indices) ||
3039 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3040 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003041
Chris Lattner392be582010-02-12 20:49:41 +00003042 if (!Val->getType()->isAggregateType())
3043 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003044 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003046 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 ID.Kind = ValID::t_Constant;
3048 return false;
3049 }
3050 case lltok::kw_insertvalue: {
3051 Lex.Lex();
3052 Constant *Val0, *Val1;
3053 SmallVector<unsigned, 4> Indices;
3054 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3055 ParseGlobalTypeAndValue(Val0) ||
3056 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3057 ParseGlobalTypeAndValue(Val1) ||
3058 ParseIndexList(Indices) ||
3059 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3060 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003061 if (!Val0->getType()->isAggregateType())
3062 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003063 Type *IndexedType =
3064 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3065 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003067 if (IndexedType != Val1->getType())
3068 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3069 getTypeString(Val1->getType()) +
3070 "' instead of '" + getTypeString(IndexedType) +
3071 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003072 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 ID.Kind = ValID::t_Constant;
3074 return false;
3075 }
3076 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003077 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 unsigned PredVal, Opc = Lex.getUIntVal();
3079 Constant *Val0, *Val1;
3080 Lex.Lex();
3081 if (ParseCmpPredicate(PredVal, Opc) ||
3082 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3083 ParseGlobalTypeAndValue(Val0) ||
3084 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3085 ParseGlobalTypeAndValue(Val1) ||
3086 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3087 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003088
Chris Lattnerac161bf2009-01-02 07:01:27 +00003089 if (Val0->getType() != Val1->getType())
3090 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003091
Chris Lattnerac161bf2009-01-02 07:01:27 +00003092 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003093
Chris Lattnerac161bf2009-01-02 07:01:27 +00003094 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003095 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003096 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003097 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003098 } else {
3099 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003100 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003101 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003102 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003103 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003104 }
3105 ID.Kind = ValID::t_Constant;
3106 return false;
3107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003108
Chris Lattnerac161bf2009-01-02 07:01:27 +00003109 // Binary Operators.
3110 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003111 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003113 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003114 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003115 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003116 case lltok::kw_udiv:
3117 case lltok::kw_sdiv:
3118 case lltok::kw_fdiv:
3119 case lltok::kw_urem:
3120 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003121 case lltok::kw_frem:
3122 case lltok::kw_shl:
3123 case lltok::kw_lshr:
3124 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003125 bool NUW = false;
3126 bool NSW = false;
3127 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003128 unsigned Opc = Lex.getUIntVal();
3129 Constant *Val0, *Val1;
3130 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003131 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003132 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3133 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003134 if (EatIfPresent(lltok::kw_nuw))
3135 NUW = true;
3136 if (EatIfPresent(lltok::kw_nsw)) {
3137 NSW = true;
3138 if (EatIfPresent(lltok::kw_nuw))
3139 NUW = true;
3140 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003141 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3142 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003143 if (EatIfPresent(lltok::kw_exact))
3144 Exact = true;
3145 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003146 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3147 ParseGlobalTypeAndValue(Val0) ||
3148 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3149 ParseGlobalTypeAndValue(Val1) ||
3150 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3151 return true;
3152 if (Val0->getType() != Val1->getType())
3153 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003154 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003155 if (NUW)
3156 return Error(ModifierLoc, "nuw only applies to integer operations");
3157 if (NSW)
3158 return Error(ModifierLoc, "nsw only applies to integer operations");
3159 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003160 // Check that the type is valid for the operator.
3161 switch (Opc) {
3162 case Instruction::Add:
3163 case Instruction::Sub:
3164 case Instruction::Mul:
3165 case Instruction::UDiv:
3166 case Instruction::SDiv:
3167 case Instruction::URem:
3168 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003169 case Instruction::Shl:
3170 case Instruction::AShr:
3171 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003172 if (!Val0->getType()->isIntOrIntVectorTy())
3173 return Error(ID.Loc, "constexpr requires integer operands");
3174 break;
3175 case Instruction::FAdd:
3176 case Instruction::FSub:
3177 case Instruction::FMul:
3178 case Instruction::FDiv:
3179 case Instruction::FRem:
3180 if (!Val0->getType()->isFPOrFPVectorTy())
3181 return Error(ID.Loc, "constexpr requires fp operands");
3182 break;
3183 default: llvm_unreachable("Unknown binary operator!");
3184 }
Dan Gohman1b849082009-09-07 23:54:19 +00003185 unsigned Flags = 0;
3186 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3187 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003188 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003189 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003190 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003191 ID.Kind = ValID::t_Constant;
3192 return false;
3193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003194
Chris Lattnerac161bf2009-01-02 07:01:27 +00003195 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003196 case lltok::kw_and:
3197 case lltok::kw_or:
3198 case lltok::kw_xor: {
3199 unsigned Opc = Lex.getUIntVal();
3200 Constant *Val0, *Val1;
3201 Lex.Lex();
3202 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3203 ParseGlobalTypeAndValue(Val0) ||
3204 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3205 ParseGlobalTypeAndValue(Val1) ||
3206 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3207 return true;
3208 if (Val0->getType() != Val1->getType())
3209 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003210 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003211 return Error(ID.Loc,
3212 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003213 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003214 ID.Kind = ValID::t_Constant;
3215 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216 }
3217
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 case lltok::kw_getelementptr:
3219 case lltok::kw_shufflevector:
3220 case lltok::kw_insertelement:
3221 case lltok::kw_extractelement:
3222 case lltok::kw_select: {
3223 unsigned Opc = Lex.getUIntVal();
3224 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003225 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003226 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003227 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003228
Dan Gohman1639c392009-07-27 21:53:46 +00003229 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003230 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003231
3232 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3233 return true;
3234
3235 LocTy ExplicitTypeLoc = Lex.getLoc();
3236 if (Opc == Instruction::GetElementPtr) {
3237 if (ParseType(Ty) ||
3238 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3239 return true;
3240 }
3241
Peter Collingbourned93620b2016-11-10 22:34:55 +00003242 Optional<unsigned> InRangeOp;
3243 if (ParseGlobalValueVector(
3244 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003245 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3246 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003247
Chris Lattnerac161bf2009-01-02 07:01:27 +00003248 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003249 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003250 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003251 return Error(ID.Loc, "base of getelementptr must be a pointer");
3252
3253 Type *BaseType = Elts[0]->getType();
3254 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003255 if (Ty != BasePointerType->getElementType())
3256 return Error(
3257 ExplicitTypeLoc,
3258 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003259
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003260 unsigned GEPWidth =
3261 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3262
Jay Foaded8db7d2011-07-21 14:31:17 +00003263 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003264 for (Constant *Val : Indices) {
3265 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003266 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003267 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003268 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003269 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003270 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003271 return Error(
3272 ID.Loc,
3273 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003274 // GEPWidth may have been unknown because the base is a scalar,
3275 // but it is known now.
3276 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003277 }
3278 }
3279
Craig Toppere3dcce92015-08-01 22:20:21 +00003280 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003281 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003282 return Error(ID.Loc, "base element of getelementptr must be sized");
3283
David Blaikie4a2e73b2015-04-02 18:55:32 +00003284 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003285 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003286
3287 if (InRangeOp) {
3288 if (*InRangeOp == 0)
3289 return Error(ID.Loc,
3290 "inrange keyword may not appear on pointer operand");
3291 --*InRangeOp;
3292 }
3293
3294 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3295 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296 } else if (Opc == Instruction::Select) {
3297 if (Elts.size() != 3)
3298 return Error(ID.Loc, "expected three operands to select");
3299 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3300 Elts[2]))
3301 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003302 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003303 } else if (Opc == Instruction::ShuffleVector) {
3304 if (Elts.size() != 3)
3305 return Error(ID.Loc, "expected three operands to shufflevector");
3306 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3307 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003308 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003309 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003310 } else if (Opc == Instruction::ExtractElement) {
3311 if (Elts.size() != 2)
3312 return Error(ID.Loc, "expected two operands to extractelement");
3313 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3314 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003315 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003316 } else {
3317 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3318 if (Elts.size() != 3)
3319 return Error(ID.Loc, "expected three operands to insertelement");
3320 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3321 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003322 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003323 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003324 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003325
Chris Lattnerac161bf2009-01-02 07:01:27 +00003326 ID.Kind = ValID::t_Constant;
3327 return false;
3328 }
3329 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003330
Chris Lattnerac161bf2009-01-02 07:01:27 +00003331 Lex.Lex();
3332 return false;
3333}
3334
3335/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003336bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003337 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003338 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003339 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003340 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003341 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003342 if (V && !(C = dyn_cast<Constant>(V)))
3343 return Error(ID.Loc, "global values must be constants");
3344 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345}
3346
Victor Hernandez9d75c962010-01-11 22:31:58 +00003347bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003348 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003349 return ParseType(Ty) ||
3350 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003351}
3352
Rafael Espindola83a362c2015-01-06 22:55:16 +00003353bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003354 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003355
3356 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003357 if (!EatIfPresent(lltok::kw_comdat))
3358 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003359
3360 if (EatIfPresent(lltok::lparen)) {
3361 if (Lex.getKind() != lltok::ComdatVar)
3362 return TokError("expected comdat variable");
3363 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3364 Lex.Lex();
3365 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3366 return true;
3367 } else {
3368 if (GlobalName.empty())
3369 return TokError("comdat cannot be unnamed");
3370 C = getComdat(GlobalName, KwLoc);
3371 }
3372
David Majnemerdad0a642014-06-27 18:19:56 +00003373 return false;
3374}
3375
Victor Hernandez9d75c962010-01-11 22:31:58 +00003376/// ParseGlobalValueVector
3377/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003378/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3379bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3380 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003381 // Empty list.
3382 if (Lex.getKind() == lltok::rbrace ||
3383 Lex.getKind() == lltok::rsquare ||
3384 Lex.getKind() == lltok::greater ||
3385 Lex.getKind() == lltok::rparen)
3386 return false;
3387
Peter Collingbourned93620b2016-11-10 22:34:55 +00003388 do {
3389 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3390 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003391
Peter Collingbourned93620b2016-11-10 22:34:55 +00003392 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003393 if (ParseGlobalTypeAndValue(C)) return true;
3394 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003395 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003396
3397 return false;
3398}
3399
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003400bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003401 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003402 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003403 return true;
3404
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003405 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003406 return false;
3407}
3408
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003409/// MDNode:
3410/// ::= !{ ... }
3411/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003412/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003413bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003414 if (Lex.getKind() == lltok::MetadataVar)
3415 return ParseSpecializedMDNode(N);
3416
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003417 return ParseToken(lltok::exclaim, "expected '!' here") ||
3418 ParseMDNodeTail(N);
3419}
3420
3421bool LLParser::ParseMDNodeTail(MDNode *&N) {
3422 // !{ ... }
3423 if (Lex.getKind() == lltok::lbrace)
3424 return ParseMDTuple(N);
3425
3426 // !42
3427 return ParseMDNodeID(N);
3428}
3429
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003430namespace {
3431
3432/// Structure to represent an optional metadata field.
3433template <class FieldTy> struct MDFieldImpl {
3434 typedef MDFieldImpl ImplTy;
3435 FieldTy Val;
3436 bool Seen;
3437
3438 void assign(FieldTy Val) {
3439 Seen = true;
3440 this->Val = std::move(Val);
3441 }
3442
3443 explicit MDFieldImpl(FieldTy Default)
3444 : Val(std::move(Default)), Seen(false) {}
3445};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003446
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003447struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3448 uint64_t Max;
3449
3450 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3451 : ImplTy(Default), Max(Max) {}
3452};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003453
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003454struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003455 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003456};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003457
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003458struct ColumnField : public MDUnsignedField {
3459 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3460};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003461
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003462struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003463 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003464 DwarfTagField(dwarf::Tag DefaultTag)
3465 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003466};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003467
Amjad Abouda9bcf162015-12-10 12:56:35 +00003468struct DwarfMacinfoTypeField : public MDUnsignedField {
3469 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3470 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3471 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3472};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003473
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003474struct DwarfAttEncodingField : public MDUnsignedField {
3475 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3476};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003477
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003478struct DwarfVirtualityField : public MDUnsignedField {
3479 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3480};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003481
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003482struct DwarfLangField : public MDUnsignedField {
3483 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3484};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003485
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003486struct DwarfCCField : public MDUnsignedField {
3487 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3488};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003489
Adrian Prantlb939a252016-03-31 23:56:58 +00003490struct EmissionKindField : public MDUnsignedField {
3491 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3492};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003493
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003494struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3495 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003496};
3497
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003498struct MDSignedField : public MDFieldImpl<int64_t> {
3499 int64_t Min;
3500 int64_t Max;
3501
3502 MDSignedField(int64_t Default = 0)
3503 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3504 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3505 : ImplTy(Default), Min(Min), Max(Max) {}
3506};
3507
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003508struct MDBoolField : public MDFieldImpl<bool> {
3509 MDBoolField(bool Default = false) : ImplTy(Default) {}
3510};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003511
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003512struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003513 bool AllowNull;
3514
3515 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003516};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003517
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003518struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3519 MDConstant() : ImplTy(nullptr) {}
3520};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003521
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003522struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003523 bool AllowEmpty;
3524 MDStringField(bool AllowEmpty = true)
3525 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003526};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003527
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003528struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3529 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3530};
3531
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003532struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3533 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3534 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3535};
3536
Eugene Zelenko1804a772016-08-25 00:45:04 +00003537} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003538
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003539namespace llvm {
3540
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003541template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003542bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003543 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003544 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3545 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003546
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003547 auto &U = Lex.getAPSIntVal();
3548 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003549 return TokError("value for '" + Name + "' too large, limit is " +
3550 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003551 Result.assign(U.getZExtValue());
3552 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003553 Lex.Lex();
3554 return false;
3555}
3556
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003557template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003558bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3559 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3560}
3561template <>
3562bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3563 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3564}
3565
3566template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003567bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3568 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003569 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003570
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003571 if (Lex.getKind() != lltok::DwarfTag)
3572 return TokError("expected DWARF tag");
3573
3574 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3575 if (Tag == dwarf::DW_TAG_invalid)
3576 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003577 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003578
3579 Result.assign(Tag);
3580 Lex.Lex();
3581 return false;
3582}
3583
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003584template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003585bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003586 DwarfMacinfoTypeField &Result) {
3587 if (Lex.getKind() == lltok::APSInt)
3588 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3589
3590 if (Lex.getKind() != lltok::DwarfMacinfo)
3591 return TokError("expected DWARF macinfo type");
3592
3593 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3594 if (Macinfo == dwarf::DW_MACINFO_invalid)
3595 return TokError(
3596 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3597 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3598
3599 Result.assign(Macinfo);
3600 Lex.Lex();
3601 return false;
3602}
3603
3604template <>
3605bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003606 DwarfVirtualityField &Result) {
3607 if (Lex.getKind() == lltok::APSInt)
3608 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3609
3610 if (Lex.getKind() != lltok::DwarfVirtuality)
3611 return TokError("expected DWARF virtuality code");
3612
3613 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003614 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003615 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3616 Lex.getStrVal() + "'");
3617 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3618 Result.assign(Virtuality);
3619 Lex.Lex();
3620 return false;
3621}
3622
3623template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003624bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3625 if (Lex.getKind() == lltok::APSInt)
3626 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3627
3628 if (Lex.getKind() != lltok::DwarfLang)
3629 return TokError("expected DWARF language");
3630
3631 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3632 if (!Lang)
3633 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3634 "'");
3635 assert(Lang <= Result.Max && "Expected valid DWARF language");
3636 Result.assign(Lang);
3637 Lex.Lex();
3638 return false;
3639}
3640
3641template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003642bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3643 if (Lex.getKind() == lltok::APSInt)
3644 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3645
3646 if (Lex.getKind() != lltok::DwarfCC)
3647 return TokError("expected DWARF calling convention");
3648
3649 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3650 if (!CC)
3651 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3652 "'");
3653 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3654 Result.assign(CC);
3655 Lex.Lex();
3656 return false;
3657}
3658
3659template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003660bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3661 if (Lex.getKind() == lltok::APSInt)
3662 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3663
3664 if (Lex.getKind() != lltok::EmissionKind)
3665 return TokError("expected emission kind");
3666
3667 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3668 if (!Kind)
3669 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3670 "'");
3671 assert(*Kind <= Result.Max && "Expected valid emission kind");
3672 Result.assign(*Kind);
3673 Lex.Lex();
3674 return false;
3675}
3676
3677template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003678bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003679 DwarfAttEncodingField &Result) {
3680 if (Lex.getKind() == lltok::APSInt)
3681 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3682
3683 if (Lex.getKind() != lltok::DwarfAttEncoding)
3684 return TokError("expected DWARF type attribute encoding");
3685
3686 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3687 if (!Encoding)
3688 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3689 Lex.getStrVal() + "'");
3690 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3691 Result.assign(Encoding);
3692 Lex.Lex();
3693 return false;
3694}
3695
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003696/// DIFlagField
3697/// ::= uint32
3698/// ::= DIFlagVector
3699/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3700template <>
3701bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003702
3703 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003704 auto parseFlag = [&](DINode::DIFlags &Val) {
3705 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3706 uint32_t TempVal = static_cast<uint32_t>(Val);
3707 bool Res = ParseUInt32(TempVal);
3708 Val = static_cast<DINode::DIFlags>(TempVal);
3709 return Res;
3710 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003711
3712 if (Lex.getKind() != lltok::DIFlag)
3713 return TokError("expected debug info flag");
3714
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003715 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003716 if (!Val)
3717 return TokError(Twine("invalid debug info flag flag '") +
3718 Lex.getStrVal() + "'");
3719 Lex.Lex();
3720 return false;
3721 };
3722
3723 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003724 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003725 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003726 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003727 if (parseFlag(Val))
3728 return true;
3729 Combined |= Val;
3730 } while (EatIfPresent(lltok::bar));
3731
3732 Result.assign(Combined);
3733 return false;
3734}
3735
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003736template <>
3737bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003738 MDSignedField &Result) {
3739 if (Lex.getKind() != lltok::APSInt)
3740 return TokError("expected signed integer");
3741
3742 auto &S = Lex.getAPSIntVal();
3743 if (S < Result.Min)
3744 return TokError("value for '" + Name + "' too small, limit is " +
3745 Twine(Result.Min));
3746 if (S > Result.Max)
3747 return TokError("value for '" + Name + "' too large, limit is " +
3748 Twine(Result.Max));
3749 Result.assign(S.getExtValue());
3750 assert(Result.Val >= Result.Min && "Expected value in range");
3751 assert(Result.Val <= Result.Max && "Expected value in range");
3752 Lex.Lex();
3753 return false;
3754}
3755
3756template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003757bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3758 switch (Lex.getKind()) {
3759 default:
3760 return TokError("expected 'true' or 'false'");
3761 case lltok::kw_true:
3762 Result.assign(true);
3763 break;
3764 case lltok::kw_false:
3765 Result.assign(false);
3766 break;
3767 }
3768 Lex.Lex();
3769 return false;
3770}
3771
3772template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003773bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003774 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003775 if (!Result.AllowNull)
3776 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003777 Lex.Lex();
3778 Result.assign(nullptr);
3779 return false;
3780 }
3781
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003782 Metadata *MD;
3783 if (ParseMetadata(MD, nullptr))
3784 return true;
3785
3786 Result.assign(MD);
3787 return false;
3788}
3789
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003790template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003791bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003792 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003793 std::string S;
3794 if (ParseStringConstant(S))
3795 return true;
3796
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003797 if (!Result.AllowEmpty && S.empty())
3798 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3799
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003800 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003801 return false;
3802}
3803
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003804template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003805bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3806 SmallVector<Metadata *, 4> MDs;
3807 if (ParseMDNodeVector(MDs))
3808 return true;
3809
3810 Result.assign(std::move(MDs));
3811 return false;
3812}
3813
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003814template <>
3815bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3816 ChecksumKindField &Result) {
3817 if (Lex.getKind() != lltok::ChecksumKind)
3818 return TokError(
3819 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3820
3821 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3822
3823 Result.assign(CSKind);
3824 Lex.Lex();
3825 return false;
3826}
3827
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003828} // end namespace llvm
3829
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003830template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003831bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003832 do {
3833 if (Lex.getKind() != lltok::LabelStr)
3834 return TokError("expected field label here");
3835
3836 if (parseField())
3837 return true;
3838 } while (EatIfPresent(lltok::comma));
3839
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003840 return false;
3841}
3842
3843template <class ParserTy>
3844bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3845 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3846 Lex.Lex();
3847
3848 if (ParseToken(lltok::lparen, "expected '(' here"))
3849 return true;
3850 if (Lex.getKind() != lltok::rparen)
3851 if (ParseMDFieldsImplBody(parseField))
3852 return true;
3853
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003854 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003855 return ParseToken(lltok::rparen, "expected ')' here");
3856}
3857
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003858template <class FieldTy>
3859bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3860 if (Result.Seen)
3861 return TokError("field '" + Name + "' cannot be specified more than once");
3862
3863 LocTy Loc = Lex.getLoc();
3864 Lex.Lex();
3865 return ParseMDField(Loc, Name, Result);
3866}
3867
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003868bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3869 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003870
3871#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003872 if (Lex.getStrVal() == #CLASS) \
3873 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003874#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003875
3876 return TokError("expected metadata type");
3877}
3878
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003879#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3880#define NOP_FIELD(NAME, TYPE, INIT)
3881#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3882 if (!NAME.Seen) \
3883 return Error(ClosingLoc, "missing required field '" #NAME "'");
3884#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003885 if (Lex.getStrVal() == #NAME) \
3886 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003887#define PARSE_MD_FIELDS() \
3888 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3889 do { \
3890 LocTy ClosingLoc; \
3891 if (ParseMDFieldsImpl([&]() -> bool { \
3892 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3893 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3894 }, ClosingLoc)) \
3895 return true; \
3896 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3897 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003898#define GET_OR_DISTINCT(CLASS, ARGS) \
3899 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003900
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003901/// ParseDILocationFields:
3902/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3903bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003904#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003905 OPTIONAL(line, LineField, ); \
3906 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003907 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003908 OPTIONAL(inlinedAt, MDField, );
3909 PARSE_MD_FIELDS();
3910#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003911
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003912 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003913 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003914 return false;
3915}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003916
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003917/// ParseGenericDINode:
3918/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3919bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003921 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003922 OPTIONAL(header, MDStringField, ); \
3923 OPTIONAL(operands, MDFieldList, );
3924 PARSE_MD_FIELDS();
3925#undef VISIT_MD_FIELDS
3926
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003927 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003928 (Context, tag.Val, header.Val, operands.Val));
3929 return false;
3930}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003931
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003932/// ParseDISubrange:
3933/// ::= !DISubrange(count: 30, lowerBound: 2)
3934bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003935#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003936 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003937 OPTIONAL(lowerBound, MDSignedField, );
3938 PARSE_MD_FIELDS();
3939#undef VISIT_MD_FIELDS
3940
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003941 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003942 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003943}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003944
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003945/// ParseDIEnumerator:
3946/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3947bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003948#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003949 REQUIRED(name, MDStringField, ); \
3950 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003951 PARSE_MD_FIELDS();
3952#undef VISIT_MD_FIELDS
3953
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003954 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003955 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003956}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003957
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003958/// ParseDIBasicType:
3959/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3960bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003961#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003962 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003963 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003964 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003965 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003966 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003967 PARSE_MD_FIELDS();
3968#undef VISIT_MD_FIELDS
3969
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003970 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003971 align.Val, encoding.Val));
3972 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003973}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003974
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003975/// ParseDIDerivedType:
3976/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003977/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003978/// align: 32, offset: 0, flags: 0, extraData: !3,
3979/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003980bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003981#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3982 REQUIRED(tag, DwarfTagField, ); \
3983 OPTIONAL(name, MDStringField, ); \
3984 OPTIONAL(file, MDField, ); \
3985 OPTIONAL(line, LineField, ); \
3986 OPTIONAL(scope, MDField, ); \
3987 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003988 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003989 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003990 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003991 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003992 OPTIONAL(extraData, MDField, ); \
3993 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003994 PARSE_MD_FIELDS();
3995#undef VISIT_MD_FIELDS
3996
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003997 Optional<unsigned> DWARFAddressSpace;
3998 if (dwarfAddressSpace.Val != UINT32_MAX)
3999 DWARFAddressSpace = dwarfAddressSpace.Val;
4000
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004001 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004002 (Context, tag.Val, name.Val, file.Val, line.Val,
4003 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004004 offset.Val, DWARFAddressSpace, flags.Val,
4005 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004006 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004007}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004008
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004009bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004010#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4011 REQUIRED(tag, DwarfTagField, ); \
4012 OPTIONAL(name, MDStringField, ); \
4013 OPTIONAL(file, MDField, ); \
4014 OPTIONAL(line, LineField, ); \
4015 OPTIONAL(scope, MDField, ); \
4016 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004017 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004018 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004019 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004020 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004021 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004022 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004023 OPTIONAL(vtableHolder, MDField, ); \
4024 OPTIONAL(templateParams, MDField, ); \
4025 OPTIONAL(identifier, MDStringField, );
4026 PARSE_MD_FIELDS();
4027#undef VISIT_MD_FIELDS
4028
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004029 // If this has an identifier try to build an ODR type.
4030 if (identifier.Val)
4031 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004032 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4033 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4034 elements.Val, runtimeLang.Val, vtableHolder.Val,
4035 templateParams.Val)) {
4036 Result = CT;
4037 return false;
4038 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004039
4040 // Create a new node, and save it in the context if it belongs in the type
4041 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004042 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004043 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004044 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4045 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4046 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4047 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004048}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004049
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004050bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004051#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004052 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004053 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004054 REQUIRED(types, MDField, );
4055 PARSE_MD_FIELDS();
4056#undef VISIT_MD_FIELDS
4057
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004058 Result = GET_OR_DISTINCT(DISubroutineType,
4059 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004060 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004061}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004062
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004063/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004064/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4065/// checksumkind: CSK_MD5,
4066/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004067bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004068#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4069 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004070 REQUIRED(directory, MDStringField, ); \
4071 OPTIONAL(checksumkind, ChecksumKindField, ); \
4072 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004073 PARSE_MD_FIELDS();
4074#undef VISIT_MD_FIELDS
4075
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004076 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4077 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004078 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004079}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004080
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004081/// ParseDICompileUnit:
4082/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004083/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004084/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004085/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004086/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004087bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004088 if (!IsDistinct)
4089 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4090
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004091#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4092 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004093 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004094 OPTIONAL(producer, MDStringField, ); \
4095 OPTIONAL(isOptimized, MDBoolField, ); \
4096 OPTIONAL(flags, MDStringField, ); \
4097 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4098 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004099 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004100 OPTIONAL(enums, MDField, ); \
4101 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004102 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004103 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004104 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004105 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004106 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004107 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4108 OPTIONAL(gnuPubnames, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004109 PARSE_MD_FIELDS();
4110#undef VISIT_MD_FIELDS
4111
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004112 Result = DICompileUnit::getDistinct(
4113 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4114 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004115 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004116 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004117 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004118}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004119
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004120/// ParseDISubprogram:
4121/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004122/// file: !1, line: 7, type: !2, isLocal: false,
4123/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004124/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004125/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004126/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004127/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004128bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004129 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004130#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4131 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004132 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004133 OPTIONAL(linkageName, MDStringField, ); \
4134 OPTIONAL(file, MDField, ); \
4135 OPTIONAL(line, LineField, ); \
4136 OPTIONAL(type, MDField, ); \
4137 OPTIONAL(isLocal, MDBoolField, ); \
4138 OPTIONAL(isDefinition, MDBoolField, (true)); \
4139 OPTIONAL(scopeLine, LineField, ); \
4140 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004141 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004142 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004143 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004144 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004145 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004146 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004147 OPTIONAL(templateParams, MDField, ); \
4148 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004149 OPTIONAL(variables, MDField, ); \
4150 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004151 PARSE_MD_FIELDS();
4152#undef VISIT_MD_FIELDS
4153
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004154 if (isDefinition.Val && !IsDistinct)
4155 return Lex.Error(
4156 Loc,
4157 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4158
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004159 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004160 DISubprogram,
4161 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4162 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4163 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4164 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4165 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004166 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004167}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004168
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004169/// ParseDILexicalBlock:
4170/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4171bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004172#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004173 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004174 OPTIONAL(file, MDField, ); \
4175 OPTIONAL(line, LineField, ); \
4176 OPTIONAL(column, ColumnField, );
4177 PARSE_MD_FIELDS();
4178#undef VISIT_MD_FIELDS
4179
4180 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004181 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004182 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004183}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004184
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004185/// ParseDILexicalBlockFile:
4186/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4187bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004188#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004189 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004190 OPTIONAL(file, MDField, ); \
4191 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4192 PARSE_MD_FIELDS();
4193#undef VISIT_MD_FIELDS
4194
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004195 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004196 (Context, scope.Val, file.Val, discriminator.Val));
4197 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004198}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004199
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004200/// ParseDINamespace:
4201/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4202bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004203#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4204 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004205 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004206 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004207 PARSE_MD_FIELDS();
4208#undef VISIT_MD_FIELDS
4209
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004210 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004211 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004212 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004213}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004214
Amjad Abouda9bcf162015-12-10 12:56:35 +00004215/// ParseDIMacro:
4216/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4217bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4218#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4219 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004220 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004221 REQUIRED(name, MDStringField, ); \
4222 OPTIONAL(value, MDStringField, );
4223 PARSE_MD_FIELDS();
4224#undef VISIT_MD_FIELDS
4225
4226 Result = GET_OR_DISTINCT(DIMacro,
4227 (Context, type.Val, line.Val, name.Val, value.Val));
4228 return false;
4229}
4230
4231/// ParseDIMacroFile:
4232/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4233bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4234#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4235 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004236 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004237 REQUIRED(file, MDField, ); \
4238 OPTIONAL(nodes, MDField, );
4239 PARSE_MD_FIELDS();
4240#undef VISIT_MD_FIELDS
4241
4242 Result = GET_OR_DISTINCT(DIMacroFile,
4243 (Context, type.Val, line.Val, file.Val, nodes.Val));
4244 return false;
4245}
4246
Adrian Prantlab1243f2015-06-29 23:03:47 +00004247/// ParseDIModule:
4248/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4249/// includePath: "/usr/include", isysroot: "/")
4250bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4251#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4252 REQUIRED(scope, MDField, ); \
4253 REQUIRED(name, MDStringField, ); \
4254 OPTIONAL(configMacros, MDStringField, ); \
4255 OPTIONAL(includePath, MDStringField, ); \
4256 OPTIONAL(isysroot, MDStringField, );
4257 PARSE_MD_FIELDS();
4258#undef VISIT_MD_FIELDS
4259
4260 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4261 configMacros.Val, includePath.Val, isysroot.Val));
4262 return false;
4263}
4264
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004265/// ParseDITemplateTypeParameter:
4266/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4267bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004268#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004269 OPTIONAL(name, MDStringField, ); \
4270 REQUIRED(type, MDField, );
4271 PARSE_MD_FIELDS();
4272#undef VISIT_MD_FIELDS
4273
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004274 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004275 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004276 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004277}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004278
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004279/// ParseDITemplateValueParameter:
4280/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004281/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004282bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004283#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004284 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004285 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004286 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004287 REQUIRED(value, MDField, );
4288 PARSE_MD_FIELDS();
4289#undef VISIT_MD_FIELDS
4290
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004291 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004292 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004293 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004294}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004295
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004296/// ParseDIGlobalVariable:
4297/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004298/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004299/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004300bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004301#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004302 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004303 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004304 OPTIONAL(linkageName, MDStringField, ); \
4305 OPTIONAL(file, MDField, ); \
4306 OPTIONAL(line, LineField, ); \
4307 OPTIONAL(type, MDField, ); \
4308 OPTIONAL(isLocal, MDBoolField, ); \
4309 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004310 OPTIONAL(declaration, MDField, ); \
4311 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004312 PARSE_MD_FIELDS();
4313#undef VISIT_MD_FIELDS
4314
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004315 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004316 (Context, scope.Val, name.Val, linkageName.Val,
4317 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004318 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004319 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004320}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004321
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004322/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004323/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004324/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4325/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004326/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004327/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4328/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004329bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004330#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004331 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004332 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004333 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004334 OPTIONAL(file, MDField, ); \
4335 OPTIONAL(line, LineField, ); \
4336 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004337 OPTIONAL(flags, DIFlagField, ); \
4338 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004339 PARSE_MD_FIELDS();
4340#undef VISIT_MD_FIELDS
4341
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004342 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004343 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004344 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004345 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004346}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004347
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004348/// ParseDIExpression:
4349/// ::= !DIExpression(0, 7, -1)
4350bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004351 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4352 Lex.Lex();
4353
4354 if (ParseToken(lltok::lparen, "expected '(' here"))
4355 return true;
4356
4357 SmallVector<uint64_t, 8> Elements;
4358 if (Lex.getKind() != lltok::rparen)
4359 do {
4360 if (Lex.getKind() == lltok::DwarfOp) {
4361 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4362 Lex.Lex();
4363 Elements.push_back(Op);
4364 continue;
4365 }
4366 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4367 }
4368
4369 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4370 return TokError("expected unsigned integer");
4371
4372 auto &U = Lex.getAPSIntVal();
4373 if (U.ugt(UINT64_MAX))
4374 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4375 Elements.push_back(U.getZExtValue());
4376 Lex.Lex();
4377 } while (EatIfPresent(lltok::comma));
4378
4379 if (ParseToken(lltok::rparen, "expected ')' here"))
4380 return true;
4381
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004382 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004383 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004384}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004385
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004386/// ParseDIGlobalVariableExpression:
4387/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4388bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4389 bool IsDistinct) {
4390#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4391 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004392 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004393 PARSE_MD_FIELDS();
4394#undef VISIT_MD_FIELDS
4395
4396 Result =
4397 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4398 return false;
4399}
4400
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004401/// ParseDIObjCProperty:
4402/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004403/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004404bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004406 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004407 OPTIONAL(file, MDField, ); \
4408 OPTIONAL(line, LineField, ); \
4409 OPTIONAL(setter, MDStringField, ); \
4410 OPTIONAL(getter, MDStringField, ); \
4411 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4412 OPTIONAL(type, MDField, );
4413 PARSE_MD_FIELDS();
4414#undef VISIT_MD_FIELDS
4415
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004416 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004417 (Context, name.Val, file.Val, line.Val, setter.Val,
4418 getter.Val, attributes.Val, type.Val));
4419 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004420}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004421
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004422/// ParseDIImportedEntity:
4423/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004424/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004425bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004426#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4427 REQUIRED(tag, DwarfTagField, ); \
4428 REQUIRED(scope, MDField, ); \
4429 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004430 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004431 OPTIONAL(line, LineField, ); \
4432 OPTIONAL(name, MDStringField, );
4433 PARSE_MD_FIELDS();
4434#undef VISIT_MD_FIELDS
4435
Adrian Prantld63bfd22017-07-19 00:09:54 +00004436 Result = GET_OR_DISTINCT(
4437 DIImportedEntity,
4438 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004439 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004440}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004441
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004442#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004443#undef NOP_FIELD
4444#undef REQUIRE_FIELD
4445#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004446
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004447/// ParseMetadataAsValue
4448/// ::= metadata i32 %local
4449/// ::= metadata i32 @global
4450/// ::= metadata i32 7
4451/// ::= metadata !0
4452/// ::= metadata !{...}
4453/// ::= metadata !"string"
4454bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4455 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004456 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004457 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004458 return true;
4459
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004460 V = MetadataAsValue::get(Context, MD);
4461 return false;
4462}
4463
4464/// ParseValueAsMetadata
4465/// ::= i32 %local
4466/// ::= i32 @global
4467/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004468bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4469 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004470 Type *Ty;
4471 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004472 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004473 return true;
4474 if (Ty->isMetadataTy())
4475 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4476
4477 Value *V;
4478 if (ParseValue(Ty, V, PFS))
4479 return true;
4480
4481 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004482 return false;
4483}
4484
4485/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004486/// ::= i32 %local
4487/// ::= i32 @global
4488/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004489/// ::= !42
4490/// ::= !{...}
4491/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004492/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004493bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004494 if (Lex.getKind() == lltok::MetadataVar) {
4495 MDNode *N;
4496 if (ParseSpecializedMDNode(N))
4497 return true;
4498 MD = N;
4499 return false;
4500 }
4501
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004502 // ValueAsMetadata:
4503 // <type> <value>
4504 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004505 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004506
4507 // '!'.
4508 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4509 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004510
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004511 // MDString:
4512 // ::= '!' STRINGCONSTANT
4513 if (Lex.getKind() == lltok::StringConstant) {
4514 MDString *S;
4515 if (ParseMDString(S))
4516 return true;
4517 MD = S;
4518 return false;
4519 }
4520
Dan Gohman8939ba332010-07-14 18:26:50 +00004521 // MDNode:
4522 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004523 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004524 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004525 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004526 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004527 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004528 return false;
4529}
4530
Victor Hernandez9d75c962010-01-11 22:31:58 +00004531//===----------------------------------------------------------------------===//
4532// Function Parsing.
4533//===----------------------------------------------------------------------===//
4534
Chris Lattner229907c2011-07-18 04:54:35 +00004535bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004536 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004537 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004539
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004542 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004543 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004544 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004546 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004547 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004548 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004549 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004550 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004551 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004552 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4553 (ID.UIntVal >> 1) & 1,
4554 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004555 return false;
4556 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 case ValID::t_GlobalName:
4558 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004559 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004560 case ValID::t_GlobalID:
4561 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004562 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004564 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004566 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004567 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004568 return false;
4569 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004570 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004571 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4572 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004573
Dan Gohman518cda42011-12-17 00:04:22 +00004574 // The lexer has no type info, so builds all half, float, and double FP
4575 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004576 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004577 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004578 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004579 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004580 &Ignored);
4581 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004582 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004583 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004585 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004586
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004587 if (V->getType() != Ty)
4588 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004589 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004590
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 return false;
4592 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004593 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004594 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004595 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004596 return false;
4597 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004598 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004599 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004600 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004601 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004602 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004603 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004604 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004605 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004606 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004607 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004608 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004609 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004610 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004611 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004612 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004613 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004614 case ValID::t_None:
4615 if (!Ty->isTokenTy())
4616 return Error(ID.Loc, "invalid type for none constant");
4617 V = Constant::getNullValue(Ty);
4618 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004619 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004620 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004621 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004622
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 V = ID.ConstantVal;
4624 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004625 case ValID::t_ConstantStruct:
4626 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004627 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004628 if (ST->getNumElements() != ID.UIntVal)
4629 return Error(ID.Loc,
4630 "initializer with struct type has wrong # elements");
4631 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4632 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004634 // Verify that the elements are compatible with the structtype.
4635 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4636 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4637 return Error(ID.Loc, "element " + Twine(i) +
4638 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004639
David Blaikieadbda4b2015-08-03 20:08:41 +00004640 V = ConstantStruct::get(
4641 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004642 } else
4643 return Error(ID.Loc, "constant expression type mismatch");
4644 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004646 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004648
Alex Lorenzd2255952015-07-17 22:07:03 +00004649bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4650 C = nullptr;
4651 ValID ID;
4652 auto Loc = Lex.getLoc();
4653 if (ParseValID(ID, /*PFS=*/nullptr))
4654 return true;
4655 switch (ID.Kind) {
4656 case ValID::t_APSInt:
4657 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004658 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004659 case ValID::t_Constant:
4660 case ValID::t_ConstantStruct:
4661 case ValID::t_PackedConstantStruct: {
4662 Value *V;
4663 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4664 return true;
4665 assert(isa<Constant>(V) && "Expected a constant value");
4666 C = cast<Constant>(V);
4667 return false;
4668 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004669 case ValID::t_Null:
4670 C = Constant::getNullValue(Ty);
4671 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004672 default:
4673 return Error(Loc, "expected a constant value");
4674 }
4675}
4676
David Majnemer8a1c45d2015-12-12 05:38:55 +00004677bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004678 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004679 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004680 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004681}
4682
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004683bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004684 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004685 return ParseType(Ty) ||
4686 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004687}
4688
Chris Lattner3ed871f2009-10-27 19:13:16 +00004689bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4690 PerFunctionState &PFS) {
4691 Value *V;
4692 Loc = Lex.getLoc();
4693 if (ParseTypeAndValue(V, PFS)) return true;
4694 if (!isa<BasicBlock>(V))
4695 return Error(Loc, "expected a basic block");
4696 BB = cast<BasicBlock>(V);
4697 return false;
4698}
4699
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700/// FunctionHeader
4701/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004702/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004703/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004704bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4705 // Parse the linkage.
4706 LocTy LinkageLoc = Lex.getLoc();
4707 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004708
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004709 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004710 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004711 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004712 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004713 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004714 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004715 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004716 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4717 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004718 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004719 return true;
4720
4721 // Verify that the linkage is ok.
4722 switch ((GlobalValue::LinkageTypes)Linkage) {
4723 case GlobalValue::ExternalLinkage:
4724 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004725 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004726 if (isDefine)
4727 return Error(LinkageLoc, "invalid linkage for function definition");
4728 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004729 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004730 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004731 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004732 case GlobalValue::LinkOnceAnyLinkage:
4733 case GlobalValue::LinkOnceODRLinkage:
4734 case GlobalValue::WeakAnyLinkage:
4735 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004736 if (!isDefine)
4737 return Error(LinkageLoc, "invalid linkage for function declaration");
4738 break;
4739 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004740 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 return Error(LinkageLoc, "invalid function linkage type");
4742 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004743
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004744 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4745 return Error(LinkageLoc,
4746 "symbol with local linkage must have default visibility");
4747
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004748 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004749 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004750
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004752
4753 std::string FunctionName;
4754 if (Lex.getKind() == lltok::GlobalVar) {
4755 FunctionName = Lex.getStrVal();
4756 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4757 unsigned NameID = Lex.getUIntVal();
4758
4759 if (NameID != NumberedVals.size())
4760 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004761 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004762 } else {
4763 return TokError("expected function name");
4764 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004765
Chris Lattner3822f632009-01-02 08:05:26 +00004766 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004767
Chris Lattner3822f632009-01-02 08:05:26 +00004768 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004769 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004770
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004771 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004773 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004774 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004775 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004777 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004778 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004779 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004780 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004781 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004782 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004783 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004784 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004785
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004786 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004787 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004788 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004789 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004790 (EatIfPresent(lltok::kw_section) &&
4791 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004792 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004793 ParseOptionalAlignment(Alignment) ||
4794 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004795 ParseStringConstant(GC)) ||
4796 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004797 ParseGlobalTypeAndValue(Prefix)) ||
4798 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004799 ParseGlobalTypeAndValue(Prologue)) ||
4800 (EatIfPresent(lltok::kw_personality) &&
4801 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004802 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803
Michael Gottesman41748d72013-06-27 00:25:01 +00004804 if (FuncAttrs.contains(Attribute::Builtin))
4805 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004806
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004808 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004809 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004810 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004811 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004812
Chris Lattnerac161bf2009-01-02 07:01:27 +00004813 // Okay, if we got here, the function is syntactically valid. Convert types
4814 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004815 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004816 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004817
Chris Lattnerac161bf2009-01-02 07:01:27 +00004818 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004819 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004820 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821 }
4822
Reid Kleckner7f720332017-04-13 00:58:09 +00004823 AttributeList PAL =
4824 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4825 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826
Bill Wendling749a43d2012-12-30 13:50:49 +00004827 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004828 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4829
Chris Lattner229907c2011-07-18 04:54:35 +00004830 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004831 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004832 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833
Craig Topper2617dcc2014-04-15 06:32:26 +00004834 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004835 if (!FunctionName.empty()) {
4836 // If this was a definition of a forward reference, remove the definition
4837 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004838 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004839 if (FRVI != ForwardRefVals.end()) {
4840 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004841 if (!Fn)
4842 return Error(FRVI->second.second, "invalid forward reference to "
4843 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004844 if (Fn->getType() != PFT)
4845 return Error(FRVI->second.second, "invalid forward reference to "
4846 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004847
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 ForwardRefVals.erase(FRVI);
4849 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004850 // Reject redefinitions.
4851 return Error(NameLoc, "invalid redefinition of function '" +
4852 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004853 } else if (M->getNamedValue(FunctionName)) {
4854 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004855 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004856
Dan Gohman399d6ae2009-08-29 23:37:49 +00004857 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004858 // If this is a definition of a forward referenced function, make sure the
4859 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004860 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004861 if (I != ForwardRefValIDs.end()) {
4862 Fn = cast<Function>(I->second.first);
4863 if (Fn->getType() != PFT)
4864 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004865 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004866 ForwardRefValIDs.erase(I);
4867 }
4868 }
4869
Craig Topper2617dcc2014-04-15 06:32:26 +00004870 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004871 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4872 else // Move the forward-reference to the correct spot in the module.
4873 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4874
4875 if (FunctionName.empty())
4876 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004877
Chris Lattnerac161bf2009-01-02 07:01:27 +00004878 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4879 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004880 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004881 Fn->setCallingConv(CC);
4882 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004883 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004884 Fn->setAlignment(Alignment);
4885 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004886 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004887 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004888 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004889 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004890 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004891 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004892
Chris Lattnerac161bf2009-01-02 07:01:27 +00004893 // Add all of the arguments we parsed to the function.
4894 Function::arg_iterator ArgIt = Fn->arg_begin();
4895 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4896 // If the argument has a name, insert it into the argument symbol table.
4897 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004898
Chris Lattnerac161bf2009-01-02 07:01:27 +00004899 // Set the name, if it conflicted, it will be auto-renamed.
4900 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004901
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004902 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004903 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4904 ArgList[i].Name + "'");
4905 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004906
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004907 if (isDefine)
4908 return false;
4909
Robin Morisset039781e2014-08-29 21:53:01 +00004910 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004911 ValID ID;
4912 if (FunctionName.empty()) {
4913 ID.Kind = ValID::t_GlobalID;
4914 ID.UIntVal = NumberedVals.size() - 1;
4915 } else {
4916 ID.Kind = ValID::t_GlobalName;
4917 ID.StrVal = FunctionName;
4918 }
4919 auto Blocks = ForwardRefBlockAddresses.find(ID);
4920 if (Blocks != ForwardRefBlockAddresses.end())
4921 return Error(Blocks->first.Loc,
4922 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004923 return false;
4924}
4925
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004926bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4927 ValID ID;
4928 if (FunctionNumber == -1) {
4929 ID.Kind = ValID::t_GlobalName;
4930 ID.StrVal = F.getName();
4931 } else {
4932 ID.Kind = ValID::t_GlobalID;
4933 ID.UIntVal = FunctionNumber;
4934 }
4935
4936 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4937 if (Blocks == P.ForwardRefBlockAddresses.end())
4938 return false;
4939
4940 for (const auto &I : Blocks->second) {
4941 const ValID &BBID = I.first;
4942 GlobalValue *GV = I.second;
4943
4944 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4945 "Expected local id or name");
4946 BasicBlock *BB;
4947 if (BBID.Kind == ValID::t_LocalName)
4948 BB = GetBB(BBID.StrVal, BBID.Loc);
4949 else
4950 BB = GetBB(BBID.UIntVal, BBID.Loc);
4951 if (!BB)
4952 return P.Error(BBID.Loc, "referenced value is not a basic block");
4953
4954 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4955 GV->eraseFromParent();
4956 }
4957
4958 P.ForwardRefBlockAddresses.erase(Blocks);
4959 return false;
4960}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961
4962/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004963/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004964bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004965 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004966 return TokError("expected '{' in function body");
4967 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004968
Chris Lattner3432c622009-10-28 03:39:23 +00004969 int FunctionNumber = -1;
4970 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004971
Chris Lattner3432c622009-10-28 03:39:23 +00004972 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004973
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004974 // Resolve block addresses and allow basic blocks to be forward-declared
4975 // within this function.
4976 if (PFS.resolveForwardRefBlockAddresses())
4977 return true;
4978 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4979
Chris Lattnerbbddd962010-01-09 19:20:07 +00004980 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004981 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004982 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004983
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004984 while (Lex.getKind() != lltok::rbrace &&
4985 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004986 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004987
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004988 while (Lex.getKind() != lltok::rbrace)
4989 if (ParseUseListOrder(&PFS))
4990 return true;
4991
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 // Eat the }.
4993 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004994
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004996 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004997}
4998
4999/// ParseBasicBlock
5000/// ::= LabelStr? Instruction*
5001bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5002 // If this basic block starts out with a name, remember it.
5003 std::string Name;
5004 LocTy NameLoc = Lex.getLoc();
5005 if (Lex.getKind() == lltok::LabelStr) {
5006 Name = Lex.getStrVal();
5007 Lex.Lex();
5008 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005009
Chris Lattnerac161bf2009-01-02 07:01:27 +00005010 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005011 if (!BB)
5012 return Error(NameLoc,
5013 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005014
Chris Lattnerac161bf2009-01-02 07:01:27 +00005015 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005016
Chris Lattnerac161bf2009-01-02 07:01:27 +00005017 // Parse the instructions in this block until we get a terminator.
5018 Instruction *Inst;
5019 do {
5020 // This instruction may have three possibilities for a name: a) none
5021 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5022 LocTy NameLoc = Lex.getLoc();
5023 int NameID = -1;
5024 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005025
Chris Lattnerac161bf2009-01-02 07:01:27 +00005026 if (Lex.getKind() == lltok::LocalVarID) {
5027 NameID = Lex.getUIntVal();
5028 Lex.Lex();
5029 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5030 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005031 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 NameStr = Lex.getStrVal();
5033 Lex.Lex();
5034 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5035 return true;
5036 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005037
Chris Lattner77b89dc2009-12-30 05:23:43 +00005038 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005039 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005040 case InstError: return true;
5041 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005042 BB->getInstList().push_back(Inst);
5043
Chris Lattner77b89dc2009-12-30 05:23:43 +00005044 // With a normal result, we check to see if the instruction is followed by
5045 // a comma and metadata.
5046 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005047 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005048 return true;
5049 break;
5050 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005051 BB->getInstList().push_back(Inst);
5052
Chris Lattner77b89dc2009-12-30 05:23:43 +00005053 // If the instruction parser ate an extra comma at the end of it, it
5054 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005055 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005056 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005057 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005058 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005059
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 // Set the name on the instruction.
5061 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5062 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005063
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 return false;
5065}
5066
5067//===----------------------------------------------------------------------===//
5068// Instruction Parsing.
5069//===----------------------------------------------------------------------===//
5070
5071/// ParseInstruction - Parse one of the many different instructions.
5072///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005073int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5074 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 lltok::Kind Token = Lex.getKind();
5076 if (Token == lltok::Eof)
5077 return TokError("found end of file when expecting more instructions");
5078 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005079 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 switch (Token) {
5083 default: return Error(Loc, "expected instruction opcode");
5084 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005085 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5087 case lltok::kw_br: return ParseBr(Inst, PFS);
5088 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005089 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005090 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005091 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005092 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5093 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005094 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5095 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005096 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005097 // Binary Operators.
5098 case lltok::kw_add:
5099 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005100 case lltok::kw_mul:
5101 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005102 bool NUW = EatIfPresent(lltok::kw_nuw);
5103 bool NSW = EatIfPresent(lltok::kw_nsw);
5104 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005105
Chris Lattnera676c0f2011-02-07 16:40:21 +00005106 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005107
Chris Lattnera676c0f2011-02-07 16:40:21 +00005108 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5109 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5110 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005111 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005112 case lltok::kw_fadd:
5113 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005114 case lltok::kw_fmul:
5115 case lltok::kw_fdiv:
5116 case lltok::kw_frem: {
5117 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5118 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5119 if (Res != 0)
5120 return Res;
5121 if (FMF.any())
5122 Inst->setFastMathFlags(FMF);
5123 return 0;
5124 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005125
Chris Lattner35315d02011-02-06 21:44:57 +00005126 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005127 case lltok::kw_udiv:
5128 case lltok::kw_lshr:
5129 case lltok::kw_ashr: {
5130 bool Exact = EatIfPresent(lltok::kw_exact);
5131
5132 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5133 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5134 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005135 }
5136
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005138 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005139 case lltok::kw_and:
5140 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005141 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005142 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5143 case lltok::kw_fcmp: {
5144 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5145 int Res = ParseCompare(Inst, PFS, KeywordVal);
5146 if (Res != 0)
5147 return Res;
5148 if (FMF.any())
5149 Inst->setFastMathFlags(FMF);
5150 return 0;
5151 }
5152
Chris Lattnerac161bf2009-01-02 07:01:27 +00005153 // Casts.
5154 case lltok::kw_trunc:
5155 case lltok::kw_zext:
5156 case lltok::kw_sext:
5157 case lltok::kw_fptrunc:
5158 case lltok::kw_fpext:
5159 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005160 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005161 case lltok::kw_uitofp:
5162 case lltok::kw_sitofp:
5163 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005164 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005165 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005166 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005167 // Other.
5168 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005169 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005170 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5171 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5172 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5173 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005174 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005175 // Call.
5176 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5177 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5178 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005179 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005180 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005181 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005182 case lltok::kw_load: return ParseLoad(Inst, PFS);
5183 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005184 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5185 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005186 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5188 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5189 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5190 }
5191}
5192
5193/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5194bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005195 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005196 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005197 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005198 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5199 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5200 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5201 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5202 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5203 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5204 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5205 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5206 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5207 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5208 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5209 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5210 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5211 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5212 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5213 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5214 }
5215 } else {
5216 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005217 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5219 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5220 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5221 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5222 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5223 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5224 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5225 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5226 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5227 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5228 }
5229 }
5230 Lex.Lex();
5231 return false;
5232}
5233
5234//===----------------------------------------------------------------------===//
5235// Terminator Instructions.
5236//===----------------------------------------------------------------------===//
5237
5238/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005239/// ::= 'ret' void (',' !dbg, !1)*
5240/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005241bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005242 PerFunctionState &PFS) {
5243 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005244 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005245 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005246
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005247 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005248
Chris Lattnerfdd87902009-10-05 05:54:46 +00005249 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005250 if (!ResType->isVoidTy())
5251 return Error(TypeLoc, "value doesn't match function result type '" +
5252 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005253
Owen Anderson55f1c092009-08-13 21:58:54 +00005254 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005255 return false;
5256 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005257
Chris Lattnerac161bf2009-01-02 07:01:27 +00005258 Value *RV;
5259 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005261 if (ResType != RV->getType())
5262 return Error(TypeLoc, "value doesn't match function result type '" +
5263 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005264
Owen Anderson55f1c092009-08-13 21:58:54 +00005265 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005266 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005267}
5268
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269/// ParseBr
5270/// ::= 'br' TypeAndValue
5271/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5272bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5273 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005274 Value *Op0;
5275 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005277
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5279 Inst = BranchInst::Create(BB);
5280 return false;
5281 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005282
Owen Anderson55f1c092009-08-13 21:58:54 +00005283 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005284 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005285
Chris Lattnerac161bf2009-01-02 07:01:27 +00005286 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005287 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005288 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005289 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005291
Chris Lattner3ed871f2009-10-27 19:13:16 +00005292 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005293 return false;
5294}
5295
5296/// ParseSwitch
5297/// Instruction
5298/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5299/// JumpTable
5300/// ::= (TypeAndValue ',' TypeAndValue)*
5301bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5302 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005303 Value *Cond;
5304 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005305 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5306 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005307 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5309 return true;
5310
Duncan Sands19d0b472010-02-16 11:11:14 +00005311 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005312 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005313
Chris Lattnerac161bf2009-01-02 07:01:27 +00005314 // Parse the jump table pairs.
5315 SmallPtrSet<Value*, 32> SeenCases;
5316 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5317 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005318 Value *Constant;
5319 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005320
Chris Lattnerac161bf2009-01-02 07:01:27 +00005321 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5322 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005323 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005324 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005325
David Blaikie70573dc2014-11-19 07:49:26 +00005326 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327 return Error(CondLoc, "duplicate case value in switch");
5328 if (!isa<ConstantInt>(Constant))
5329 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005330
Chris Lattner3ed871f2009-10-27 19:13:16 +00005331 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005332 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005333
Chris Lattnerac161bf2009-01-02 07:01:27 +00005334 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005335
Chris Lattner3ed871f2009-10-27 19:13:16 +00005336 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005337 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5338 SI->addCase(Table[i].first, Table[i].second);
5339 Inst = SI;
5340 return false;
5341}
5342
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005343/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005344/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005345/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5346bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005347 LocTy AddrLoc;
5348 Value *Address;
5349 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005350 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5351 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005352 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005353
Duncan Sands19d0b472010-02-16 11:11:14 +00005354 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005355 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005356
Chris Lattner3ed871f2009-10-27 19:13:16 +00005357 // Parse the destination list.
5358 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005359
Chris Lattner3ed871f2009-10-27 19:13:16 +00005360 if (Lex.getKind() != lltok::rsquare) {
5361 BasicBlock *DestBB;
5362 if (ParseTypeAndBasicBlock(DestBB, PFS))
5363 return true;
5364 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005365
Chris Lattner3ed871f2009-10-27 19:13:16 +00005366 while (EatIfPresent(lltok::comma)) {
5367 if (ParseTypeAndBasicBlock(DestBB, PFS))
5368 return true;
5369 DestList.push_back(DestBB);
5370 }
5371 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005372
Chris Lattner3ed871f2009-10-27 19:13:16 +00005373 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5374 return true;
5375
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005376 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005377 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5378 IBI->addDestination(DestList[i]);
5379 Inst = IBI;
5380 return false;
5381}
5382
Chris Lattnerac161bf2009-01-02 07:01:27 +00005383/// ParseInvoke
5384/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5385/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5386bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5387 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005388 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005389 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005390 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005391 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005392 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393 LocTy RetTypeLoc;
5394 ValID CalleeID;
5395 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005396 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005397
Chris Lattner3ed871f2009-10-27 19:13:16 +00005398 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005399 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005400 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005401 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005402 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5403 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005404 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005405 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005406 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005407 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005408 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005409 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005410
Chris Lattnerac161bf2009-01-02 07:01:27 +00005411 // If RetType is a non-function pointer type, then this is the short syntax
5412 // for the call, which means that RetType is just the return type. Infer the
5413 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005414 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5415 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005416 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005417 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005418 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5419 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005420
Chris Lattnerac161bf2009-01-02 07:01:27 +00005421 if (!FunctionType::isValidReturnType(RetType))
5422 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005423
Owen Anderson4056ca92009-07-29 22:17:13 +00005424 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005425 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005426
David Blaikie41ba2b42015-07-27 23:32:19 +00005427 CalleeID.FTy = Ty;
5428
Chris Lattnerac161bf2009-01-02 07:01:27 +00005429 // Look up the callee.
5430 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005431 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5432 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005433
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005434 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005435 SmallVector<Value *, 8> Args;
5436 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005437
Chris Lattnerac161bf2009-01-02 07:01:27 +00005438 // Loop through FunctionType's arguments and ensure they are specified
5439 // correctly. Also, gather any parameter attributes.
5440 FunctionType::param_iterator I = Ty->param_begin();
5441 FunctionType::param_iterator E = Ty->param_end();
5442 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005443 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005444 if (I != E) {
5445 ExpectedTy = *I++;
5446 } else if (!Ty->isVarArg()) {
5447 return Error(ArgList[i].Loc, "too many arguments specified");
5448 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005449
Chris Lattnerac161bf2009-01-02 07:01:27 +00005450 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5451 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005452 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005453 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005454 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005455 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005456
Chris Lattnerac161bf2009-01-02 07:01:27 +00005457 if (I != E)
5458 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005459
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005460 if (FnAttrs.hasAlignmentAttr())
5461 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005462
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005463 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005464 AttributeList PAL =
5465 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5466 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005467
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005468 InvokeInst *II =
5469 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005470 II->setCallingConv(CC);
5471 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005472 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005473 Inst = II;
5474 return false;
5475}
5476
Bill Wendlingf891bf82011-07-31 06:30:59 +00005477/// ParseResume
5478/// ::= 'resume' TypeAndValue
5479bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5480 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005481 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5482 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005483
Bill Wendlingf891bf82011-07-31 06:30:59 +00005484 ResumeInst *RI = ResumeInst::Create(Exn);
5485 Inst = RI;
5486 return false;
5487}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005488
David Majnemer654e1302015-07-31 17:58:14 +00005489bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5490 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005491 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005492 return true;
5493
5494 while (Lex.getKind() != lltok::rsquare) {
5495 // If this isn't the first argument, we need a comma.
5496 if (!Args.empty() &&
5497 ParseToken(lltok::comma, "expected ',' in argument list"))
5498 return true;
5499
5500 // Parse the argument.
5501 LocTy ArgLoc;
5502 Type *ArgTy = nullptr;
5503 if (ParseType(ArgTy, ArgLoc))
5504 return true;
5505
5506 Value *V;
5507 if (ArgTy->isMetadataTy()) {
5508 if (ParseMetadataAsValue(V, PFS))
5509 return true;
5510 } else {
5511 if (ParseValue(ArgTy, V, PFS))
5512 return true;
5513 }
5514 Args.push_back(V);
5515 }
5516
5517 Lex.Lex(); // Lex the ']'.
5518 return false;
5519}
5520
5521/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005522/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005523bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005524 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005525
David Majnemer8a1c45d2015-12-12 05:38:55 +00005526 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5527 return true;
5528
5529 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005530 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005531
5532 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5533 return true;
5534
5535 BasicBlock *UnwindBB = nullptr;
5536 if (Lex.getKind() == lltok::kw_to) {
5537 Lex.Lex();
5538 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5539 return true;
5540 } else {
5541 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5542 return true;
5543 }
5544 }
5545
David Majnemer8a1c45d2015-12-12 05:38:55 +00005546 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005547 return false;
5548}
5549
5550/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005551/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005552bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005553 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005554
David Majnemer8a1c45d2015-12-12 05:38:55 +00005555 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5556 return true;
5557
5558 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005559 return true;
5560
David Majnemer0bc0eef2015-08-15 02:46:08 +00005561 BasicBlock *BB;
5562 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5563 ParseTypeAndBasicBlock(BB, PFS))
5564 return true;
5565
David Majnemer8a1c45d2015-12-12 05:38:55 +00005566 Inst = CatchReturnInst::Create(CatchPad, BB);
5567 return false;
5568}
5569
5570/// ParseCatchSwitch
5571/// ::= 'catchswitch' within Parent
5572bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5573 Value *ParentPad;
5574 LocTy BBLoc;
5575
5576 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5577 return true;
5578
5579 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5580 Lex.getKind() != lltok::LocalVarID)
5581 return TokError("expected scope value for catchswitch");
5582
5583 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5584 return true;
5585
5586 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5587 return true;
5588
5589 SmallVector<BasicBlock *, 32> Table;
5590 do {
5591 BasicBlock *DestBB;
5592 if (ParseTypeAndBasicBlock(DestBB, PFS))
5593 return true;
5594 Table.push_back(DestBB);
5595 } while (EatIfPresent(lltok::comma));
5596
5597 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5598 return true;
5599
5600 if (ParseToken(lltok::kw_unwind,
5601 "expected 'unwind' after catchswitch scope"))
5602 return true;
5603
5604 BasicBlock *UnwindBB = nullptr;
5605 if (EatIfPresent(lltok::kw_to)) {
5606 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5607 return true;
5608 } else {
5609 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5610 return true;
5611 }
5612
5613 auto *CatchSwitch =
5614 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5615 for (BasicBlock *DestBB : Table)
5616 CatchSwitch->addHandler(DestBB);
5617 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005618 return false;
5619}
5620
5621/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005622/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005623bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005624 Value *CatchSwitch = nullptr;
5625
5626 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5627 return true;
5628
5629 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5630 return TokError("expected scope value for catchpad");
5631
5632 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5633 return true;
5634
David Majnemer654e1302015-07-31 17:58:14 +00005635 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005636 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005637 return true;
5638
David Majnemer8a1c45d2015-12-12 05:38:55 +00005639 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005640 return false;
5641}
5642
David Majnemer654e1302015-07-31 17:58:14 +00005643/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005644/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005645bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005646 Value *ParentPad = nullptr;
5647
5648 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5649 return true;
5650
5651 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5652 Lex.getKind() != lltok::LocalVarID)
5653 return TokError("expected scope value for cleanuppad");
5654
5655 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5656 return true;
5657
David Majnemer654e1302015-07-31 17:58:14 +00005658 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005659 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005660 return true;
5661
David Majnemer8a1c45d2015-12-12 05:38:55 +00005662 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005663 return false;
5664}
5665
Chris Lattnerac161bf2009-01-02 07:01:27 +00005666//===----------------------------------------------------------------------===//
5667// Binary Operators.
5668//===----------------------------------------------------------------------===//
5669
5670/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005671/// ::= ArithmeticOps TypeAndValue ',' Value
5672///
5673/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5674/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005675bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005676 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005677 LocTy Loc; Value *LHS, *RHS;
5678 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5679 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5680 ParseValue(LHS->getType(), RHS, PFS))
5681 return true;
5682
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005683 bool Valid;
5684 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005685 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005686 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005687 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5688 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005689 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005690 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5691 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005692 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005693
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005694 if (!Valid)
5695 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005696
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5698 return false;
5699}
5700
5701/// ParseLogical
5702/// ::= ArithmeticOps TypeAndValue ',' Value {
5703bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5704 unsigned Opc) {
5705 LocTy Loc; Value *LHS, *RHS;
5706 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5707 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5708 ParseValue(LHS->getType(), RHS, PFS))
5709 return true;
5710
Duncan Sands9dff9be2010-02-15 16:12:20 +00005711 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 return Error(Loc,"instruction requires integer or integer vector operands");
5713
5714 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5715 return false;
5716}
5717
Chris Lattnerac161bf2009-01-02 07:01:27 +00005718/// ParseCompare
5719/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5720/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005721bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5722 unsigned Opc) {
5723 // Parse the integer/fp comparison predicate.
5724 LocTy Loc;
5725 unsigned Pred;
5726 Value *LHS, *RHS;
5727 if (ParseCmpPredicate(Pred, Opc) ||
5728 ParseTypeAndValue(LHS, Loc, PFS) ||
5729 ParseToken(lltok::comma, "expected ',' after compare value") ||
5730 ParseValue(LHS->getType(), RHS, PFS))
5731 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005732
Chris Lattnerac161bf2009-01-02 07:01:27 +00005733 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005734 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005735 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005736 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005737 } else {
5738 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005739 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00005740 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005742 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005743 }
5744 return false;
5745}
5746
5747//===----------------------------------------------------------------------===//
5748// Other Instructions.
5749//===----------------------------------------------------------------------===//
5750
5751
5752/// ParseCast
5753/// ::= CastOpc TypeAndValue 'to' Type
5754bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5755 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005756 LocTy Loc;
5757 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005758 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005759 if (ParseTypeAndValue(Op, Loc, PFS) ||
5760 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5761 ParseType(DestTy))
5762 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005763
Chris Lattner89d856e2009-03-01 00:53:13 +00005764 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5765 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005766 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005767 getTypeString(Op->getType()) + "' to '" +
5768 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005769 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005770 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5771 return false;
5772}
5773
5774/// ParseSelect
5775/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5776bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5777 LocTy Loc;
5778 Value *Op0, *Op1, *Op2;
5779 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5780 ParseToken(lltok::comma, "expected ',' after select condition") ||
5781 ParseTypeAndValue(Op1, PFS) ||
5782 ParseToken(lltok::comma, "expected ',' after select value") ||
5783 ParseTypeAndValue(Op2, PFS))
5784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005785
Chris Lattnerac161bf2009-01-02 07:01:27 +00005786 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5787 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005788
Chris Lattnerac161bf2009-01-02 07:01:27 +00005789 Inst = SelectInst::Create(Op0, Op1, Op2);
5790 return false;
5791}
5792
Chris Lattnerb55ab542009-01-05 08:18:44 +00005793/// ParseVA_Arg
5794/// ::= 'va_arg' TypeAndValue ',' Type
5795bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005796 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005797 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005798 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005799 if (ParseTypeAndValue(Op, PFS) ||
5800 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005801 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005802 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005803
Chris Lattnerb55ab542009-01-05 08:18:44 +00005804 if (!EltTy->isFirstClassType())
5805 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806
5807 Inst = new VAArgInst(Op, EltTy);
5808 return false;
5809}
5810
5811/// ParseExtractElement
5812/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5813bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5814 LocTy Loc;
5815 Value *Op0, *Op1;
5816 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5817 ParseToken(lltok::comma, "expected ',' after extract value") ||
5818 ParseTypeAndValue(Op1, PFS))
5819 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005820
Chris Lattnerac161bf2009-01-02 07:01:27 +00005821 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5822 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005823
Eric Christopherc9742252009-07-25 02:28:41 +00005824 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005825 return false;
5826}
5827
5828/// ParseInsertElement
5829/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5830bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5831 LocTy Loc;
5832 Value *Op0, *Op1, *Op2;
5833 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5834 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5835 ParseTypeAndValue(Op1, PFS) ||
5836 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5837 ParseTypeAndValue(Op2, PFS))
5838 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005839
Chris Lattnerac161bf2009-01-02 07:01:27 +00005840 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005841 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005842
Chris Lattnerac161bf2009-01-02 07:01:27 +00005843 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5844 return false;
5845}
5846
5847/// ParseShuffleVector
5848/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5849bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5850 LocTy Loc;
5851 Value *Op0, *Op1, *Op2;
5852 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5853 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5854 ParseTypeAndValue(Op1, PFS) ||
5855 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5856 ParseTypeAndValue(Op2, PFS))
5857 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005858
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005860 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005861
Chris Lattnerac161bf2009-01-02 07:01:27 +00005862 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5863 return false;
5864}
5865
5866/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005867/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005868int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005869 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005870 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005871
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005872 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005873 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5874 ParseValue(Ty, Op0, PFS) ||
5875 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005876 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005877 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5878 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005879
Chris Lattnerf4f03422009-12-30 05:27:33 +00005880 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005881 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005882
5883 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005885
Chris Lattner3822f632009-01-02 08:05:26 +00005886 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005887 break;
5888
Chris Lattnerf4f03422009-12-30 05:27:33 +00005889 if (Lex.getKind() == lltok::MetadataVar) {
5890 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005891 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005892 }
Devang Patel8f842d32009-10-16 18:45:49 +00005893
Chris Lattner3822f632009-01-02 08:05:26 +00005894 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005895 ParseValue(Ty, Op0, PFS) ||
5896 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005897 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005898 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5899 return true;
5900 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005901
Chris Lattnerac161bf2009-01-02 07:01:27 +00005902 if (!Ty->isFirstClassType())
5903 return Error(TypeLoc, "phi node must have first class type");
5904
Jay Foad52131342011-03-30 11:28:46 +00005905 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005906 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5907 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5908 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005909 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005910}
5911
Bill Wendlingfae14752011-08-12 20:24:12 +00005912/// ParseLandingPad
5913/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5914/// Clause
5915/// ::= 'catch' TypeAndValue
5916/// ::= 'filter'
5917/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5918bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005919 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005920
David Majnemer7fddecc2015-06-17 20:52:32 +00005921 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005922 return true;
5923
David Majnemer7fddecc2015-06-17 20:52:32 +00005924 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005925 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5926
5927 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5928 LandingPadInst::ClauseType CT;
5929 if (EatIfPresent(lltok::kw_catch))
5930 CT = LandingPadInst::Catch;
5931 else if (EatIfPresent(lltok::kw_filter))
5932 CT = LandingPadInst::Filter;
5933 else
5934 return TokError("expected 'catch' or 'filter' clause type");
5935
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005936 Value *V;
5937 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005938 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005939 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005940
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005941 // A 'catch' type expects a non-array constant. A filter clause expects an
5942 // array constant.
5943 if (CT == LandingPadInst::Catch) {
5944 if (isa<ArrayType>(V->getType()))
5945 Error(VLoc, "'catch' clause has an invalid type");
5946 } else {
5947 if (!isa<ArrayType>(V->getType()))
5948 Error(VLoc, "'filter' clause has an invalid type");
5949 }
5950
Owen Andersonf8f259d2015-03-09 07:13:42 +00005951 Constant *CV = dyn_cast<Constant>(V);
5952 if (!CV)
5953 return Error(VLoc, "clause argument must be a constant");
5954 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005955 }
5956
Owen Andersonf8f259d2015-03-09 07:13:42 +00005957 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005958 return false;
5959}
5960
Chris Lattnerac161bf2009-01-02 07:01:27 +00005961/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005962/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5963/// OptionalAttrs Type Value ParameterList OptionalAttrs
5964/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5965/// OptionalAttrs Type Value ParameterList OptionalAttrs
5966/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5967/// OptionalAttrs Type Value ParameterList OptionalAttrs
5968/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5969/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005970bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005971 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005972 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005973 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005974 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005975 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005976 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977 LocTy RetTypeLoc;
5978 ValID CalleeID;
5979 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005980 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005981 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005982
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005983 if (TCK != CallInst::TCK_None &&
5984 ParseToken(lltok::kw_call,
5985 "expected 'tail call', 'musttail call', or 'notail call'"))
5986 return true;
5987
5988 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5989
5990 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005991 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005993 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5994 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005995 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5996 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005997 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005998
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005999 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6000 return Error(CallLoc, "fast-math-flags specified for call without "
6001 "floating-point scalar or vector return type");
6002
Chris Lattnerac161bf2009-01-02 07:01:27 +00006003 // If RetType is a non-function pointer type, then this is the short syntax
6004 // for the call, which means that RetType is just the return type. Infer the
6005 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006006 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6007 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006009 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006010 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6011 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006012
Chris Lattnerac161bf2009-01-02 07:01:27 +00006013 if (!FunctionType::isValidReturnType(RetType))
6014 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006015
Owen Anderson4056ca92009-07-29 22:17:13 +00006016 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006017 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006018
David Blaikie41ba2b42015-07-27 23:32:19 +00006019 CalleeID.FTy = Ty;
6020
Chris Lattnerac161bf2009-01-02 07:01:27 +00006021 // Look up the callee.
6022 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00006023 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6024 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006025
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006026 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006027 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006028
Chris Lattnerac161bf2009-01-02 07:01:27 +00006029 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006030
Chris Lattnerac161bf2009-01-02 07:01:27 +00006031 // Loop through FunctionType's arguments and ensure they are specified
6032 // correctly. Also, gather any parameter attributes.
6033 FunctionType::param_iterator I = Ty->param_begin();
6034 FunctionType::param_iterator E = Ty->param_end();
6035 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006036 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006037 if (I != E) {
6038 ExpectedTy = *I++;
6039 } else if (!Ty->isVarArg()) {
6040 return Error(ArgList[i].Loc, "too many arguments specified");
6041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006042
Chris Lattnerac161bf2009-01-02 07:01:27 +00006043 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6044 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006045 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006046 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006047 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006048 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006049
Chris Lattnerac161bf2009-01-02 07:01:27 +00006050 if (I != E)
6051 return Error(CallLoc, "not enough parameters specified for call");
6052
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006053 if (FnAttrs.hasAlignmentAttr())
6054 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006055
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006056 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006057 AttributeList PAL =
6058 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6059 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006060
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006061 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006062 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006063 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006064 if (FMF.any())
6065 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006066 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006067 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006068 Inst = CI;
6069 return false;
6070}
6071
6072//===----------------------------------------------------------------------===//
6073// Memory Instructions.
6074//===----------------------------------------------------------------------===//
6075
6076/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006077/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6078/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006079int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006080 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006081 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006082 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006083 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006084 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006085
6086 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006087 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006088
David Majnemera3b0eb22015-02-16 08:38:03 +00006089 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006090
David Majnemera3b0eb22015-02-16 08:38:03 +00006091 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6092 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006093
Chris Lattnerb2f39502009-12-30 05:44:30 +00006094 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006095 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006096 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006097 if (ParseOptionalAlignment(Alignment))
6098 return true;
6099 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6100 return true;
6101 } else if (Lex.getKind() == lltok::kw_addrspace) {
6102 ASLoc = Lex.getLoc();
6103 if (ParseOptionalAddrSpace(AddrSpace))
6104 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006105 } else if (Lex.getKind() == lltok::MetadataVar) {
6106 AteExtraComma = true;
6107 } else {
6108 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006109 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6110 (!AteExtraComma &&
6111 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006112 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006113 }
6114 }
6115
Dan Gohman2140a742010-05-28 01:14:11 +00006116 if (Size && !Size->getType()->isIntegerTy())
6117 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006118
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006119 const DataLayout &DL = M->getDataLayout();
6120 unsigned AS = DL.getAllocaAddrSpace();
6121 if (AS != AddrSpace) {
6122 // TODO: In the future it should be possible to specify addrspace per-alloca.
6123 return Error(ASLoc, "address space must match datalayout");
6124 }
6125
6126 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006127 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006128 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006129 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006130 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006131}
6132
6133/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006134/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006135/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006136/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006137int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006138 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006139 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006140 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006141 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006142 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006143 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006144
6145 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006146 isAtomic = true;
6147 Lex.Lex();
6148 }
6149
Chris Lattnerbc639292011-11-27 06:56:53 +00006150 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006151 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006152 isVolatile = true;
6153 Lex.Lex();
6154 }
6155
David Blaikie15d9a4c2015-04-06 20:59:48 +00006156 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006157 LocTy ExplicitTypeLoc = Lex.getLoc();
6158 if (ParseType(Ty) ||
6159 ParseToken(lltok::comma, "expected comma after load's type") ||
6160 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006161 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006162 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6163 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006164
David Blaikie15d9a4c2015-04-06 20:59:48 +00006165 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006166 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006167 if (isAtomic && !Alignment)
6168 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006169 if (Ordering == AtomicOrdering::Release ||
6170 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006171 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006172
David Blaikiea79ac142015-02-27 21:17:42 +00006173 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6174 return Error(ExplicitTypeLoc,
6175 "explicit pointee type doesn't match operand's pointee type");
6176
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006177 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006178 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006179}
6180
6181/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006182
6183/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6184/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006185/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006186int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006187 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006188 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006189 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006190 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006191 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006192 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006193
6194 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006195 isAtomic = true;
6196 Lex.Lex();
6197 }
6198
Chris Lattnerbc639292011-11-27 06:56:53 +00006199 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006200 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006201 isVolatile = true;
6202 Lex.Lex();
6203 }
6204
Chris Lattnerac161bf2009-01-02 07:01:27 +00006205 if (ParseTypeAndValue(Val, Loc, PFS) ||
6206 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006207 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006208 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006209 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006210 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006211
Duncan Sands19d0b472010-02-16 11:11:14 +00006212 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006213 return Error(PtrLoc, "store operand must be a pointer");
6214 if (!Val->getType()->isFirstClassType())
6215 return Error(Loc, "store operand must be a first class value");
6216 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6217 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006218 if (isAtomic && !Alignment)
6219 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006220 if (Ordering == AtomicOrdering::Acquire ||
6221 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006222 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006223
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006224 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006225 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006226}
6227
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006228/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006229/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6230/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006231int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006232 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6233 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006234 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6235 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006236 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006237 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006238 bool isWeak = false;
6239
6240 if (EatIfPresent(lltok::kw_weak))
6241 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006242
6243 if (EatIfPresent(lltok::kw_volatile))
6244 isVolatile = true;
6245
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006246 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6247 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6248 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6249 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6250 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006251 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006252 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006253 return true;
6254
JF Bastien800f87a2016-04-06 21:19:33 +00006255 if (SuccessOrdering == AtomicOrdering::Unordered ||
6256 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006257 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006258 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6259 return TokError("cmpxchg failure argument shall be no stronger than the "
6260 "success argument");
6261 if (FailureOrdering == AtomicOrdering::Release ||
6262 FailureOrdering == AtomicOrdering::AcquireRelease)
6263 return TokError(
6264 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006265 if (!Ptr->getType()->isPointerTy())
6266 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6267 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6268 return Error(CmpLoc, "compare value and pointer type do not match");
6269 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6270 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006271 if (!New->getType()->isFirstClassType())
6272 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006273 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006274 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006275 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006276 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006277 Inst = CXI;
6278 return AteExtraComma ? InstExtraComma : InstNormal;
6279}
6280
6281/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006282/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6283/// 'singlethread'? AtomicOrdering
6284int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006285 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6286 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006287 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006288 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006289 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006290 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006291
6292 if (EatIfPresent(lltok::kw_volatile))
6293 isVolatile = true;
6294
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006295 switch (Lex.getKind()) {
6296 default: return TokError("expected binary operation in atomicrmw");
6297 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6298 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6299 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6300 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6301 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6302 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6303 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6304 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6305 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6306 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6307 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6308 }
6309 Lex.Lex(); // Eat the operation.
6310
6311 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6312 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6313 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006314 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006315 return true;
6316
JF Bastien800f87a2016-04-06 21:19:33 +00006317 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006318 return TokError("atomicrmw cannot be unordered");
6319 if (!Ptr->getType()->isPointerTy())
6320 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6321 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6322 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6323 if (!Val->getType()->isIntegerTy())
6324 return Error(ValLoc, "atomicrmw operand must be an integer");
6325 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6326 if (Size < 8 || (Size & (Size - 1)))
6327 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6328 " integer");
6329
6330 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006331 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006332 RMWI->setVolatile(isVolatile);
6333 Inst = RMWI;
6334 return AteExtraComma ? InstExtraComma : InstNormal;
6335}
6336
Eli Friedmanfee02c62011-07-25 23:16:38 +00006337/// ParseFence
6338/// ::= 'fence' 'singlethread'? AtomicOrdering
6339int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006340 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006341 SyncScope::ID SSID = SyncScope::System;
6342 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006343 return true;
6344
JF Bastien800f87a2016-04-06 21:19:33 +00006345 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006346 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006347 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006348 return TokError("fence cannot be monotonic");
6349
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006350 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006351 return InstNormal;
6352}
6353
Chris Lattnerac161bf2009-01-02 07:01:27 +00006354/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006355/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006356int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006357 Value *Ptr = nullptr;
6358 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006359 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006360
Dan Gohman16cbbe42009-07-29 15:58:36 +00006361 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006362
David Blaikie79e6c742015-02-27 19:29:02 +00006363 Type *Ty = nullptr;
6364 LocTy ExplicitTypeLoc = Lex.getLoc();
6365 if (ParseType(Ty) ||
6366 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6367 ParseTypeAndValue(Ptr, Loc, PFS))
6368 return true;
6369
Eli Benderskyd9806682013-04-22 17:03:42 +00006370 Type *BaseType = Ptr->getType();
6371 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6372 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006373 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006374
David Blaikie8d757942015-03-09 23:08:44 +00006375 if (Ty != BasePointerType->getElementType())
6376 return Error(ExplicitTypeLoc,
6377 "explicit pointee type doesn't match operand's pointee type");
6378
Chris Lattnerac161bf2009-01-02 07:01:27 +00006379 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006380 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006381 // GEP returns a vector of pointers if at least one of parameters is a vector.
6382 // All vector parameters should have the same vector width.
6383 unsigned GEPWidth = BaseType->isVectorTy() ?
6384 BaseType->getVectorNumElements() : 0;
6385
Chris Lattner3822f632009-01-02 08:05:26 +00006386 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006387 if (Lex.getKind() == lltok::MetadataVar) {
6388 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006389 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006390 }
Chris Lattner3822f632009-01-02 08:05:26 +00006391 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006392 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006393 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006394
Nadav Rotem3924cb02011-12-05 06:29:09 +00006395 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006396 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6397 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006398 return Error(EltLoc,
6399 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006400 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006401 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 Indices.push_back(Val);
6403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006404
Craig Toppere3dcce92015-08-01 22:20:21 +00006405 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006406 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006407 return Error(Loc, "base element of getelementptr must be sized");
6408
David Blaikied33bad32015-04-17 22:32:13 +00006409 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006410 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006411 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006412 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006413 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006414 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006415}
6416
6417/// ParseExtractValue
6418/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006419int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006420 Value *Val; LocTy Loc;
6421 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006422 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006423 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006424 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006425 return true;
6426
Chris Lattner392be582010-02-12 20:49:41 +00006427 if (!Val->getType()->isAggregateType())
6428 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006429
Jay Foad57aa6362011-07-13 10:26:04 +00006430 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006431 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006432 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006433 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006434}
6435
6436/// ParseInsertValue
6437/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006438int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006439 Value *Val0, *Val1; LocTy Loc0, Loc1;
6440 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006441 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006442 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6443 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6444 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006445 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006446 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006447
Chris Lattner392be582010-02-12 20:49:41 +00006448 if (!Val0->getType()->isAggregateType())
6449 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006450
David Majnemer30074532015-02-11 07:43:58 +00006451 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6452 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006453 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006454 if (IndexedType != Val1->getType())
6455 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6456 getTypeString(Val1->getType()) + "' instead of '" +
6457 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006458 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006459 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006460}
Nick Lewycky49f89192009-04-04 07:22:01 +00006461
6462//===----------------------------------------------------------------------===//
6463// Embedded metadata.
6464//===----------------------------------------------------------------------===//
6465
6466/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006467/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006468/// Element
6469/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006470bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006471 if (ParseToken(lltok::lbrace, "expected '{' here"))
6472 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006473
Dan Gohman1e0213a2010-07-13 19:33:27 +00006474 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006475 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006476 return false;
6477
Nick Lewycky49f89192009-04-04 07:22:01 +00006478 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006479 // Null is a special case since it is typeless.
6480 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006481 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006482 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006483 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006484
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006485 Metadata *MD;
6486 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006487 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006488 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006489 } while (EatIfPresent(lltok::comma));
6490
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006491 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006492}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006493
6494//===----------------------------------------------------------------------===//
6495// Use-list order directives.
6496//===----------------------------------------------------------------------===//
6497bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6498 SMLoc Loc) {
6499 if (V->use_empty())
6500 return Error(Loc, "value has no uses");
6501
6502 unsigned NumUses = 0;
6503 SmallDenseMap<const Use *, unsigned, 16> Order;
6504 for (const Use &U : V->uses()) {
6505 if (++NumUses > Indexes.size())
6506 break;
6507 Order[&U] = Indexes[NumUses - 1];
6508 }
6509 if (NumUses < 2)
6510 return Error(Loc, "value only has one use");
6511 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6512 return Error(Loc, "wrong number of indexes, expected " +
6513 Twine(std::distance(V->use_begin(), V->use_end())));
6514
6515 V->sortUseList([&](const Use &L, const Use &R) {
6516 return Order.lookup(&L) < Order.lookup(&R);
6517 });
6518 return false;
6519}
6520
6521/// ParseUseListOrderIndexes
6522/// ::= '{' uint32 (',' uint32)+ '}'
6523bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6524 SMLoc Loc = Lex.getLoc();
6525 if (ParseToken(lltok::lbrace, "expected '{' here"))
6526 return true;
6527 if (Lex.getKind() == lltok::rbrace)
6528 return Lex.Error("expected non-empty list of uselistorder indexes");
6529
6530 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6531 // indexes should be distinct numbers in the range [0, size-1], and should
6532 // not be in order.
6533 unsigned Offset = 0;
6534 unsigned Max = 0;
6535 bool IsOrdered = true;
6536 assert(Indexes.empty() && "Expected empty order vector");
6537 do {
6538 unsigned Index;
6539 if (ParseUInt32(Index))
6540 return true;
6541
6542 // Update consistency checks.
6543 Offset += Index - Indexes.size();
6544 Max = std::max(Max, Index);
6545 IsOrdered &= Index == Indexes.size();
6546
6547 Indexes.push_back(Index);
6548 } while (EatIfPresent(lltok::comma));
6549
6550 if (ParseToken(lltok::rbrace, "expected '}' here"))
6551 return true;
6552
6553 if (Indexes.size() < 2)
6554 return Error(Loc, "expected >= 2 uselistorder indexes");
6555 if (Offset != 0 || Max >= Indexes.size())
6556 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6557 if (IsOrdered)
6558 return Error(Loc, "expected uselistorder indexes to change the order");
6559
6560 return false;
6561}
6562
6563/// ParseUseListOrder
6564/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6565bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6566 SMLoc Loc = Lex.getLoc();
6567 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6568 return true;
6569
6570 Value *V;
6571 SmallVector<unsigned, 16> Indexes;
6572 if (ParseTypeAndValue(V, PFS) ||
6573 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6574 ParseUseListOrderIndexes(Indexes))
6575 return true;
6576
6577 return sortUseListOrder(V, Indexes, Loc);
6578}
6579
6580/// ParseUseListOrderBB
6581/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6582bool LLParser::ParseUseListOrderBB() {
6583 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6584 SMLoc Loc = Lex.getLoc();
6585 Lex.Lex();
6586
6587 ValID Fn, Label;
6588 SmallVector<unsigned, 16> Indexes;
6589 if (ParseValID(Fn) ||
6590 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6591 ParseValID(Label) ||
6592 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6593 ParseUseListOrderIndexes(Indexes))
6594 return true;
6595
6596 // Check the function.
6597 GlobalValue *GV;
6598 if (Fn.Kind == ValID::t_GlobalName)
6599 GV = M->getNamedValue(Fn.StrVal);
6600 else if (Fn.Kind == ValID::t_GlobalID)
6601 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6602 else
6603 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6604 if (!GV)
6605 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6606 auto *F = dyn_cast<Function>(GV);
6607 if (!F)
6608 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6609 if (F->isDeclaration())
6610 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6611
6612 // Check the basic block.
6613 if (Label.Kind == ValID::t_LocalID)
6614 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6615 if (Label.Kind != ValID::t_LocalName)
6616 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006617 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006618 if (!V)
6619 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6620 if (!isa<BasicBlock>(V))
6621 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6622
6623 return sortUseListOrder(V, Indexes, Loc);
6624}