blob: a8f44e982a279d9b6c625d4447754a62481fed3c [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000016#include "llvm/ADT/STLExtras.h"
George Burgess IV278199f2016-04-12 01:05:35 +000017#include "llvm/ADT/StringExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000018#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000019#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/CallingConv.h"
21#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000022#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000023#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/InlineAsm.h"
26#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000027#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
29#include "llvm/IR/Operator.h"
30#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000031#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000032#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000033#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000034#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000035#include "llvm/Support/raw_ostream.h"
36using namespace llvm;
37
Chris Lattner229907c2011-07-18 04:54:35 +000038static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000039 std::string Result;
40 raw_string_ostream Tmp(Result);
41 Tmp << *T;
42 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000043}
44
Chris Lattner3822f632009-01-02 08:05:26 +000045/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000046bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000047 // Prime the lexer.
48 Lex.Lex();
49
Mehdi Amini50af49f2016-04-02 03:46:17 +000050 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000051 return Error(
52 Lex.getLoc(),
53 "Can't read textual IR with a Context that discards named Values");
54
Chris Lattnerad6f3352009-01-04 20:44:11 +000055 return ParseTopLevelEntities() ||
56 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000057}
58
Alex Lorenz1de2acd2015-08-21 21:32:39 +000059bool LLParser::parseStandaloneConstantValue(Constant *&C,
60 const SlotMapping *Slots) {
61 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000062 Lex.Lex();
63
64 Type *Ty = nullptr;
65 if (ParseType(Ty) || parseConstantValue(Ty, C))
66 return true;
67 if (Lex.getKind() != lltok::Eof)
68 return Error(Lex.getLoc(), "expected end of string");
69 return false;
70}
71
Quentin Colombetdafed5d2016-03-08 00:37:07 +000072bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
73 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000074 restoreParsingState(Slots);
75 Lex.Lex();
76
Quentin Colombetdafed5d2016-03-08 00:37:07 +000077 Read = 0;
78 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000079 Ty = nullptr;
80 if (ParseType(Ty))
81 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000082 SMLoc End = Lex.getLoc();
83 Read = End.getPointer() - Start.getPointer();
84
Quentin Colombet81e72b42016-03-07 22:09:05 +000085 return false;
86}
87
Alex Lorenz1de2acd2015-08-21 21:32:39 +000088void LLParser::restoreParsingState(const SlotMapping *Slots) {
89 if (!Slots)
90 return;
91 NumberedVals = Slots->GlobalValues;
92 NumberedMetadata = Slots->MetadataNodes;
93 for (const auto &I : Slots->NamedTypes)
94 NamedTypes.insert(
95 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
96 for (const auto &I : Slots->Types)
97 NumberedTypes.insert(
98 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
99}
100
Chris Lattnerac161bf2009-01-02 07:01:27 +0000101/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
102/// module.
103bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000104 // Handle any function attribute group forward references.
105 for (std::map<Value*, std::vector<unsigned> >::iterator
106 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
107 I != E; ++I) {
108 Value *V = I->first;
109 std::vector<unsigned> &Vec = I->second;
110 AttrBuilder B;
111
112 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
113 VI != VE; ++VI)
114 B.merge(NumberedAttrBuilders[*VI]);
115
116 if (Function *Fn = dyn_cast<Function>(V)) {
117 AttributeSet AS = Fn->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
121
122 FnAttrs.merge(B);
123
124 // If the alignment was parsed as an attribute, move to the alignment
125 // field.
126 if (FnAttrs.hasAlignmentAttr()) {
127 Fn->setAlignment(FnAttrs.getAlignment());
128 FnAttrs.removeAttribute(Attribute::Alignment);
129 }
130
131 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
132 AttributeSet::get(Context,
133 AttributeSet::FunctionIndex,
134 FnAttrs));
135 Fn->setAttributes(AS);
136 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
137 AttributeSet AS = CI->getAttributes();
138 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
139 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
140 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000141 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000142 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
143 AttributeSet::get(Context,
144 AttributeSet::FunctionIndex,
145 FnAttrs));
146 CI->setAttributes(AS);
147 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
148 AttributeSet AS = II->getAttributes();
149 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
150 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
151 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000152 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000153 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
154 AttributeSet::get(Context,
155 AttributeSet::FunctionIndex,
156 FnAttrs));
157 II->setAttributes(AS);
158 } else {
159 llvm_unreachable("invalid object with forward attribute group reference");
160 }
161 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000162
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000163 // If there are entries in ForwardRefBlockAddresses at this point, the
164 // function was never defined.
165 if (!ForwardRefBlockAddresses.empty())
166 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
167 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000168
David Majnemer19b51052015-02-11 07:43:56 +0000169 for (const auto &NT : NumberedTypes)
170 if (NT.second.second.isValid())
171 return Error(NT.second.second,
172 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000173
174 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
175 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
176 if (I->second.second.isValid())
177 return Error(I->second.second,
178 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000179
David Majnemerdad0a642014-06-27 18:19:56 +0000180 if (!ForwardRefComdats.empty())
181 return Error(ForwardRefComdats.begin()->second,
182 "use of undefined comdat '$" +
183 ForwardRefComdats.begin()->first + "'");
184
Chris Lattnerac161bf2009-01-02 07:01:27 +0000185 if (!ForwardRefVals.empty())
186 return Error(ForwardRefVals.begin()->second.second,
187 "use of undefined value '@" + ForwardRefVals.begin()->first +
188 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000189
Chris Lattnerac161bf2009-01-02 07:01:27 +0000190 if (!ForwardRefValIDs.empty())
191 return Error(ForwardRefValIDs.begin()->second.second,
192 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000193 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000194
Devang Pateld2541152009-07-08 19:23:54 +0000195 if (!ForwardRefMDNodes.empty())
196 return Error(ForwardRefMDNodes.begin()->second.second,
197 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000198 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000199
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000200 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000201 for (auto &N : NumberedMetadata) {
202 if (N.second && !N.second->isResolved())
203 N.second->resolveCycles();
204 }
Devang Pateld2541152009-07-08 19:23:54 +0000205
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000206 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
207 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
208
Chris Lattnerac161bf2009-01-02 07:01:27 +0000209 // Look for intrinsic functions and CallInst that need to be upgraded
210 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000211 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Manman Ren8b4306c2013-12-02 21:29:56 +0000213 UpgradeDebugInfo(*M);
214
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000215 if (!Slots)
216 return false;
217 // Initialize the slot mapping.
218 // Because by this point we've parsed and validated everything, we can "steal"
219 // the mapping from LLParser as it doesn't need it anymore.
220 Slots->GlobalValues = std::move(NumberedVals);
221 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000222 for (const auto &I : NamedTypes)
223 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
224 for (const auto &I : NumberedTypes)
225 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000226
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 return false;
228}
229
230//===----------------------------------------------------------------------===//
231// Top-Level Entities
232//===----------------------------------------------------------------------===//
233
234bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000235 while (1) {
236 switch (Lex.getKind()) {
237 default: return TokError("expected top-level entity");
238 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 case lltok::kw_declare: if (ParseDeclare()) return true; break;
240 case lltok::kw_define: if (ParseDefine()) return true; break;
241 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
242 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000243 case lltok::kw_source_filename:
244 if (ParseSourceFileName())
245 return true;
246 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000247 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000248 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000249 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000250 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000251 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000252 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000253 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000254 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000255
256 // The Global variable production with no name can have many different
257 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000258 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000259 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000260 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000261 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000262 case lltok::kw_internal: // OptionalLinkage
263 case lltok::kw_weak: // OptionalLinkage
264 case lltok::kw_weak_odr: // OptionalLinkage
265 case lltok::kw_linkonce: // OptionalLinkage
266 case lltok::kw_linkonce_odr: // OptionalLinkage
267 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000268 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000269 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000270 case lltok::kw_external: // OptionalLinkage
271 case lltok::kw_default: // OptionalVisibility
272 case lltok::kw_hidden: // OptionalVisibility
273 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000274 case lltok::kw_dllimport: // OptionalDLLStorageClass
275 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000276 case lltok::kw_thread_local: // OptionalThreadLocal
277 case lltok::kw_addrspace: // OptionalAddrSpace
278 case lltok::kw_constant: // GlobalType
279 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000280 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000281 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000282 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000283 bool HasLinkage;
284 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000285 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000286 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000287 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000288 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000289 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000290 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000291 return true;
292 break;
293 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000294
295 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000296 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
297 case lltok::kw_uselistorder_bb:
298 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299 }
300 }
301}
302
303
304/// toplevelentity
305/// ::= 'module' 'asm' STRINGCONSTANT
306bool LLParser::ParseModuleAsm() {
307 assert(Lex.getKind() == lltok::kw_module);
308 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000309
310 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000311 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
312 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000313
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000314 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000315 return false;
316}
317
318/// toplevelentity
319/// ::= 'target' 'triple' '=' STRINGCONSTANT
320/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
321bool LLParser::ParseTargetDefinition() {
322 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000323 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324 switch (Lex.Lex()) {
325 default: return TokError("unknown target property");
326 case lltok::kw_triple:
327 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000328 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
329 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000330 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000331 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 return false;
333 case lltok::kw_datalayout:
334 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000335 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
336 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000337 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000338 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000339 return false;
340 }
341}
342
Bill Wendling706d3d62012-11-28 08:41:48 +0000343/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000344/// ::= 'source_filename' '=' STRINGCONSTANT
345bool LLParser::ParseSourceFileName() {
346 assert(Lex.getKind() == lltok::kw_source_filename);
347 std::string Str;
348 Lex.Lex();
349 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
350 ParseStringConstant(Str))
351 return true;
352 M->setSourceFileName(Str);
353 return false;
354}
355
356/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000357/// ::= 'deplibs' '=' '[' ']'
358/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
359/// FIXME: Remove in 4.0. Currently parse, but ignore.
360bool LLParser::ParseDepLibs() {
361 assert(Lex.getKind() == lltok::kw_deplibs);
362 Lex.Lex();
363 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
364 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
365 return true;
366
367 if (EatIfPresent(lltok::rsquare))
368 return false;
369
370 do {
371 std::string Str;
372 if (ParseStringConstant(Str)) return true;
373 } while (EatIfPresent(lltok::comma));
374
375 return ParseToken(lltok::rsquare, "expected ']' at end of list");
376}
377
Dan Gohman466876b2009-08-12 23:32:33 +0000378/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000379/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000381 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000383 Lex.Lex(); // eat LocalVarID;
384
385 if (ParseToken(lltok::equal, "expected '=' after name") ||
386 ParseToken(lltok::kw_type, "expected 'type' after '='"))
387 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388
Craig Topper2617dcc2014-04-15 06:32:26 +0000389 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000390 if (ParseStructDefinition(TypeLoc, "",
391 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000393 if (!isa<StructType>(Result)) {
394 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
395 if (Entry.first)
396 return Error(TypeLoc, "non-struct types may not be recursive");
397 Entry.first = Result;
398 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000399 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000400
Chris Lattnerac161bf2009-01-02 07:01:27 +0000401 return false;
402}
403
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000404
Chris Lattnerac161bf2009-01-02 07:01:27 +0000405/// toplevelentity
406/// ::= LocalVar '=' 'type' type
407bool LLParser::ParseNamedType() {
408 std::string Name = Lex.getStrVal();
409 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000410 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000411
Chris Lattner3822f632009-01-02 08:05:26 +0000412 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000413 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000414 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000415
Craig Topper2617dcc2014-04-15 06:32:26 +0000416 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000417 if (ParseStructDefinition(NameLoc, Name,
418 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000420 if (!isa<StructType>(Result)) {
421 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
422 if (Entry.first)
423 return Error(NameLoc, "non-struct types may not be recursive");
424 Entry.first = Result;
425 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000426 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000427
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000428 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429}
430
431
432/// toplevelentity
433/// ::= 'declare' FunctionHeader
434bool LLParser::ParseDeclare() {
435 assert(Lex.getKind() == lltok::kw_declare);
436 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000437
Chris Lattnerac161bf2009-01-02 07:01:27 +0000438 Function *F;
439 return ParseFunctionHeader(F, false);
440}
441
442/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000443/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444bool LLParser::ParseDefine() {
445 assert(Lex.getKind() == lltok::kw_define);
446 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000447
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000449 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000450 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000451 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452}
453
Chris Lattner3822f632009-01-02 08:05:26 +0000454/// ParseGlobalType
455/// ::= 'constant'
456/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000457bool LLParser::ParseGlobalType(bool &IsConstant) {
458 if (Lex.getKind() == lltok::kw_constant)
459 IsConstant = true;
460 else if (Lex.getKind() == lltok::kw_global)
461 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000462 else {
463 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000464 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000465 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000466 Lex.Lex();
467 return false;
468}
469
Dan Gohman466876b2009-08-12 23:32:33 +0000470/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000471/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000472/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
473/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000474/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000475/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
476/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000477bool LLParser::ParseUnnamedGlobal() {
478 unsigned VarID = NumberedVals.size();
479 std::string Name;
480 LocTy NameLoc = Lex.getLoc();
481
482 // Handle the GlobalID form.
483 if (Lex.getKind() == lltok::GlobalID) {
484 if (Lex.getUIntVal() != VarID)
485 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000486 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000487 Lex.Lex(); // eat GlobalID;
488
489 if (ParseToken(lltok::equal, "expected '=' after name"))
490 return true;
491 }
492
493 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000494 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000495 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000496 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000497 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000498 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000499 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000500 ParseOptionalThreadLocal(TLM) ||
501 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000502 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000503
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000504 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000505 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000506 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000507
508 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
509 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000510}
511
Chris Lattnerac161bf2009-01-02 07:01:27 +0000512/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000513/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000514/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
515/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000516bool LLParser::ParseNamedGlobal() {
517 assert(Lex.getKind() == lltok::GlobalVar);
518 LocTy NameLoc = Lex.getLoc();
519 std::string Name = Lex.getStrVal();
520 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000521
Chris Lattnerac161bf2009-01-02 07:01:27 +0000522 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000523 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000524 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000525 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000526 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
527 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000528 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000529 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000530 ParseOptionalThreadLocal(TLM) ||
531 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000532 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000533
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000534 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000535 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000536 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000537
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000538 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
539 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000540}
541
David Majnemerdad0a642014-06-27 18:19:56 +0000542bool LLParser::parseComdat() {
543 assert(Lex.getKind() == lltok::ComdatVar);
544 std::string Name = Lex.getStrVal();
545 LocTy NameLoc = Lex.getLoc();
546 Lex.Lex();
547
548 if (ParseToken(lltok::equal, "expected '=' here"))
549 return true;
550
551 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
552 return TokError("expected comdat type");
553
554 Comdat::SelectionKind SK;
555 switch (Lex.getKind()) {
556 default:
557 return TokError("unknown selection kind");
558 case lltok::kw_any:
559 SK = Comdat::Any;
560 break;
561 case lltok::kw_exactmatch:
562 SK = Comdat::ExactMatch;
563 break;
564 case lltok::kw_largest:
565 SK = Comdat::Largest;
566 break;
567 case lltok::kw_noduplicates:
568 SK = Comdat::NoDuplicates;
569 break;
570 case lltok::kw_samesize:
571 SK = Comdat::SameSize;
572 break;
573 }
574 Lex.Lex();
575
576 // See if the comdat was forward referenced, if so, use the comdat.
577 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
578 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
579 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
580 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
581
582 Comdat *C;
583 if (I != ComdatSymTab.end())
584 C = &I->second;
585 else
586 C = M->getOrInsertComdat(Name);
587 C->setSelectionKind(SK);
588
589 return false;
590}
591
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000592// MDString:
593// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000594bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000595 std::string Str;
596 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000597 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000598 return false;
599}
600
601// MDNode:
602// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000603bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000604 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000605 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000606 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000607 if (ParseUInt32(MID))
608 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000609
Chris Lattner8eff0152010-04-01 05:14:45 +0000610 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000611 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000612 Result = NumberedMetadata[MID];
613 return false;
614 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615
Chris Lattner8eff0152010-04-01 05:14:45 +0000616 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000617 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000618 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000619
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000620 Result = FwdRef.first.get();
621 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000622 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000623}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000624
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000625/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000626/// !foo = !{ !1, !2 }
627bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000628 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000629 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000630 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000631
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000632 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000633 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000634 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000635 return true;
636
Dan Gohman2637cc12010-07-21 23:38:33 +0000637 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000638 if (Lex.getKind() != lltok::rbrace)
639 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000640 if (ParseToken(lltok::exclaim, "Expected '!' here"))
641 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000642
Craig Topper2617dcc2014-04-15 06:32:26 +0000643 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000644 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000645 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000647
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000648 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000649}
650
Devang Patel39e64d42009-07-01 19:21:12 +0000651/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000652/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000653bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000654 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000655 Lex.Lex();
656 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000657
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000658 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000659 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000660 ParseToken(lltok::equal, "expected '=' here"))
661 return true;
662
663 // Detect common error, from old metadata syntax.
664 if (Lex.getKind() == lltok::Type)
665 return TokError("unexpected type in metadata definition");
666
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000667 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000668 if (Lex.getKind() == lltok::MetadataVar) {
669 if (ParseSpecializedMDNode(Init, IsDistinct))
670 return true;
671 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
672 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000673 return true;
674
Chris Lattnerfc58af22009-12-30 04:51:58 +0000675 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000676 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000677 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000678 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000679 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000680
Chris Lattnerfc58af22009-12-30 04:51:58 +0000681 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
682 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000683 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000684 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000685 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000686 }
687
Devang Patel39e64d42009-07-01 19:21:12 +0000688 return false;
689}
690
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000691static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
692 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
693 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
694}
695
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000696/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000697/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
698/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000699/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000700///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000701/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000702/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000703///
Eric Christopher536f0a92015-05-28 23:07:39 +0000704/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000705///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000706bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
707 unsigned L, unsigned Visibility,
708 unsigned DLLStorageClass,
709 GlobalVariable::ThreadLocalMode TLM,
710 bool UnnamedAddr) {
711 bool IsAlias;
712 if (Lex.getKind() == lltok::kw_alias)
713 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000714 else if (Lex.getKind() == lltok::kw_ifunc)
715 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000716 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000717 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000718 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719
Rafael Espindola78527052013-10-06 15:10:43 +0000720 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
721
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000722 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000723 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000724
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000725 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000726 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000727 "symbol with local linkage must have default visibility");
728
David Blaikie2f408302015-09-11 03:22:04 +0000729 Type *Ty;
730 LocTy ExplicitTypeLoc = Lex.getLoc();
731 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000732 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000733 return true;
734
Rafael Espindola64c1e182014-06-03 02:41:57 +0000735 Constant *Aliasee;
736 LocTy AliaseeLoc = Lex.getLoc();
737 if (Lex.getKind() != lltok::kw_bitcast &&
738 Lex.getKind() != lltok::kw_getelementptr &&
739 Lex.getKind() != lltok::kw_addrspacecast &&
740 Lex.getKind() != lltok::kw_inttoptr) {
741 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000742 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000743 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000744 // The bitcast dest type is not present, it is implied by the dest type.
745 ValID ID;
746 if (ParseValID(ID))
747 return true;
748 if (ID.Kind != ValID::t_Constant)
749 return Error(AliaseeLoc, "invalid aliasee");
750 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000752
Rafael Espindola64c1e182014-06-03 02:41:57 +0000753 Type *AliaseeType = Aliasee->getType();
754 auto *PTy = dyn_cast<PointerType>(AliaseeType);
755 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000756 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000757 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000758
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000759 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000760 return Error(
761 ExplicitTypeLoc,
762 "explicit pointee type doesn't match operand's pointee type");
763
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000764 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
765 return Error(
766 ExplicitTypeLoc,
767 "explicit pointee type should be a function type");
768
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000769 GlobalValue *GVal = nullptr;
770
771 // See if the alias was forward referenced, if so, prepare to replace the
772 // forward reference.
773 if (!Name.empty()) {
774 GVal = M->getNamedValue(Name);
775 if (GVal) {
776 if (!ForwardRefVals.erase(Name))
777 return Error(NameLoc, "redefinition of global '@" + Name + "'");
778 }
779 } else {
780 auto I = ForwardRefValIDs.find(NumberedVals.size());
781 if (I != ForwardRefValIDs.end()) {
782 GVal = I->second.first;
783 ForwardRefValIDs.erase(I);
784 }
785 }
786
Chris Lattnerac161bf2009-01-02 07:01:27 +0000787 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000788 std::unique_ptr<GlobalIndirectSymbol> GA;
789 if (IsAlias)
790 GA.reset(GlobalAlias::create(Ty, AddrSpace,
791 (GlobalValue::LinkageTypes)Linkage, Name,
792 Aliasee, /*Parent*/ nullptr));
793 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000794 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
795 (GlobalValue::LinkageTypes)Linkage, Name,
796 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000797 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000798 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000799 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000800 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000801
Rafael Espindola54fc2982015-06-17 17:53:31 +0000802 if (Name.empty())
803 NumberedVals.push_back(GA.get());
804
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000805 if (GVal) {
806 // Verify that types agree.
807 if (GVal->getType() != GA->getType())
808 return Error(
809 ExplicitTypeLoc,
810 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 // If they agree, just RAUW the old value with the alias and remove the
813 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000814 GVal->replaceAllUsesWith(GA.get());
815 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000816 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000817
Chris Lattnerac161bf2009-01-02 07:01:27 +0000818 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000819 if (IsAlias)
820 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
821 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000822 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000823 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Rafael Espindolaaa273822014-05-09 21:49:17 +0000825 // The module owns this now
826 GA.release();
827
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 return false;
829}
830
831/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000832/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000833/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000834/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000835/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000836/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000837/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000838///
Eric Christopher536f0a92015-05-28 23:07:39 +0000839/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000840/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000841///
842bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
843 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000844 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000845 GlobalVariable::ThreadLocalMode TLM,
846 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000847 if (!isValidVisibilityForLinkage(Visibility, Linkage))
848 return Error(NameLoc,
849 "symbol with local linkage must have default visibility");
850
Chris Lattnerac161bf2009-01-02 07:01:27 +0000851 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000852 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000853 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000855
Craig Topper2617dcc2014-04-15 06:32:26 +0000856 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000857 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000858 ParseOptionalToken(lltok::kw_externally_initialized,
859 IsExternallyInitialized,
860 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 ParseGlobalType(IsConstant) ||
862 ParseType(Ty, TyLoc))
863 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000864
Chris Lattnerac161bf2009-01-02 07:01:27 +0000865 // If the linkage is specified and is external, then no initializer is
866 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000867 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000868 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000869 Linkage != GlobalValue::ExternalLinkage)) {
870 if (ParseGlobalValue(Ty, Init))
871 return true;
872 }
873
David Majnemer49b3d9b2015-02-16 08:41:08 +0000874 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000875 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000876
David Majnemer598bd052014-12-09 05:56:09 +0000877 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000878
879 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000880 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000881 GVal = M->getNamedValue(Name);
882 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000883 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000884 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000885 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000886 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000887 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000888 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000889 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000890 ForwardRefValIDs.erase(I);
891 }
892 }
893
David Majnemer598bd052014-12-09 05:56:09 +0000894 GlobalVariable *GV;
895 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000896 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
897 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000898 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000900 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000901 return Error(TyLoc,
902 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000903
David Majnemer598bd052014-12-09 05:56:09 +0000904 GV = cast<GlobalVariable>(GVal);
905
Chris Lattnerac161bf2009-01-02 07:01:27 +0000906 // Move the forward-reference to the correct spot in the module.
907 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
908 }
909
910 if (Name.empty())
911 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
Chris Lattnerac161bf2009-01-02 07:01:27 +0000913 // Set the parsed properties on the global.
914 if (Init)
915 GV->setInitializer(Init);
916 GV->setConstant(IsConstant);
917 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
918 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000919 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000920 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000921 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000922 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000923
Chris Lattnerac161bf2009-01-02 07:01:27 +0000924 // Parse attributes on the global.
925 while (Lex.getKind() == lltok::comma) {
926 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000927
Chris Lattnerac161bf2009-01-02 07:01:27 +0000928 if (Lex.getKind() == lltok::kw_section) {
929 Lex.Lex();
930 GV->setSection(Lex.getStrVal());
931 if (ParseToken(lltok::StringConstant, "expected global section string"))
932 return true;
933 } else if (Lex.getKind() == lltok::kw_align) {
934 unsigned Alignment;
935 if (ParseOptionalAlignment(Alignment)) return true;
936 GV->setAlignment(Alignment);
937 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000938 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000939 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000940 return true;
941 if (C)
942 GV->setComdat(C);
943 else
944 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000945 }
946 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000947
Chris Lattnerac161bf2009-01-02 07:01:27 +0000948 return false;
949}
950
Bill Wendling63b88192013-02-06 06:52:58 +0000951/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000952/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000953bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000954 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000955 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000956 Lex.Lex();
957
David Majnemerb39e22b2014-12-09 18:33:57 +0000958 if (Lex.getKind() != lltok::AttrGrpID)
959 return TokError("expected attribute group id");
960
Bill Wendling63b88192013-02-06 06:52:58 +0000961 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000962 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000963 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000964 Lex.Lex();
965
966 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000967 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000968 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000969 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000970 ParseToken(lltok::rbrace, "expected end of attribute group"))
971 return true;
972
Bill Wendlingb32b0412013-02-08 06:32:06 +0000973 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000974 return Error(AttrGrpLoc, "attribute group has no attributes");
975
976 return false;
977}
978
Bill Wendling8b0321d2013-02-08 00:52:31 +0000979/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000980/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000981bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
982 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000983 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984 bool HaveError = false;
985
986 B.clear();
987
Bill Wendling63b88192013-02-06 06:52:58 +0000988 while (true) {
989 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000990 if (Token == lltok::kw_builtin)
991 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000992 switch (Token) {
993 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000994 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000995 return Error(Lex.getLoc(), "unterminated attribute group");
996 case lltok::rbrace:
997 // Finished.
998 return false;
999
Bill Wendlingb32b0412013-02-08 06:32:06 +00001000 case lltok::AttrGrpID: {
1001 // Allow a function to reference an attribute group:
1002 //
1003 // define void @foo() #1 { ... }
1004 if (inAttrGrp)
1005 HaveError |=
1006 Error(Lex.getLoc(),
1007 "cannot have an attribute group reference in an attribute group");
1008
1009 unsigned AttrGrpNum = Lex.getUIntVal();
1010 if (inAttrGrp) break;
1011
1012 // Save the reference to the attribute group. We'll fill it in later.
1013 FwdRefAttrGrps.push_back(AttrGrpNum);
1014 break;
1015 }
Bill Wendling63b88192013-02-06 06:52:58 +00001016 // Target-dependent attributes:
1017 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001018 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001019 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001020 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001021 }
1022
1023 // Target-independent attributes:
1024 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001025 // As a hack, we allow function alignment to be initially parsed as an
1026 // attribute on a function declaration/definition or added to an attribute
1027 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001028 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001029 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001030 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001031 if (ParseToken(lltok::equal, "expected '=' here") ||
1032 ParseUInt32(Alignment))
1033 return true;
1034 } else {
1035 if (ParseOptionalAlignment(Alignment))
1036 return true;
1037 }
Bill Wendling63b88192013-02-06 06:52:58 +00001038 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001039 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001040 }
1041 case lltok::kw_alignstack: {
1042 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001043 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001044 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001045 if (ParseToken(lltok::equal, "expected '=' here") ||
1046 ParseUInt32(Alignment))
1047 return true;
1048 } else {
1049 if (ParseOptionalStackAlignment(Alignment))
1050 return true;
1051 }
Bill Wendling63b88192013-02-06 06:52:58 +00001052 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001053 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001054 }
George Burgess IV278199f2016-04-12 01:05:35 +00001055 case lltok::kw_allocsize: {
1056 unsigned ElemSizeArg;
1057 Optional<unsigned> NumElemsArg;
1058 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1059 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1060 return true;
1061 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1062 continue;
1063 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001064 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1065 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1066 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1067 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1068 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001069 case lltok::kw_inaccessiblememonly:
1070 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1071 case lltok::kw_inaccessiblemem_or_argmemonly:
1072 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001073 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1074 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1075 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1076 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1077 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1078 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1079 case lltok::kw_noimplicitfloat:
1080 B.addAttribute(Attribute::NoImplicitFloat); break;
1081 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1082 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1083 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1084 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001085 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001086 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1087 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1088 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1089 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1090 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1091 case lltok::kw_returns_twice:
1092 B.addAttribute(Attribute::ReturnsTwice); break;
1093 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1094 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1095 case lltok::kw_sspstrong:
1096 B.addAttribute(Attribute::StackProtectStrong); break;
1097 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1098 case lltok::kw_sanitize_address:
1099 B.addAttribute(Attribute::SanitizeAddress); break;
1100 case lltok::kw_sanitize_thread:
1101 B.addAttribute(Attribute::SanitizeThread); break;
1102 case lltok::kw_sanitize_memory:
1103 B.addAttribute(Attribute::SanitizeMemory); break;
1104 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001105
1106 // Error handling.
1107 case lltok::kw_inreg:
1108 case lltok::kw_signext:
1109 case lltok::kw_zeroext:
1110 HaveError |=
1111 Error(Lex.getLoc(),
1112 "invalid use of attribute on a function");
1113 break;
1114 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001115 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001116 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001117 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001118 case lltok::kw_nest:
1119 case lltok::kw_noalias:
1120 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001121 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001122 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001123 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001124 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001125 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001126 HaveError |=
1127 Error(Lex.getLoc(),
1128 "invalid use of parameter-only attribute on a function");
1129 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001130 }
1131
1132 Lex.Lex();
1133 }
1134}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135
1136//===----------------------------------------------------------------------===//
1137// GlobalValue Reference/Resolution Routines.
1138//===----------------------------------------------------------------------===//
1139
Karl Schimpf77729782015-09-03 18:06:44 +00001140static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1141 const std::string &Name) {
1142 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1143 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1144 else
1145 return new GlobalVariable(*M, PTy->getElementType(), false,
1146 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1147 nullptr, GlobalVariable::NotThreadLocal,
1148 PTy->getAddressSpace());
1149}
1150
Chris Lattnerac161bf2009-01-02 07:01:27 +00001151/// GetGlobalVal - Get a value with the specified name or ID, creating a
1152/// forward reference record if needed. This can return null if the value
1153/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001154GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001155 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001156 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001157 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001159 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001161
Chris Lattnerac161bf2009-01-02 07:01:27 +00001162 // Look this name up in the normal function symbol table.
1163 GlobalValue *Val =
1164 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001165
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166 // If this is a forward reference for the value, see if we already created a
1167 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001168 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001169 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 if (I != ForwardRefVals.end())
1171 Val = I->second.first;
1172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Chris Lattnerac161bf2009-01-02 07:01:27 +00001174 // If we have the value in the symbol table or fwd-ref table, return it.
1175 if (Val) {
1176 if (Val->getType() == Ty) return Val;
1177 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001178 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001179 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001181
Chris Lattnerac161bf2009-01-02 07:01:27 +00001182 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001183 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001184 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1185 return FwdVal;
1186}
1187
Chris Lattner229907c2011-07-18 04:54:35 +00001188GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1189 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001190 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001192 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001194
Craig Topper2617dcc2014-04-15 06:32:26 +00001195 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001196
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 // If this is a forward reference for the value, see if we already created a
1198 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001199 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001200 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 if (I != ForwardRefValIDs.end())
1202 Val = I->second.first;
1203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001204
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 // If we have the value in the symbol table or fwd-ref table, return it.
1206 if (Val) {
1207 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001208 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001209 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001210 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001211 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001212
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001214 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001215 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1216 return FwdVal;
1217}
1218
1219
1220//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001221// Comdat Reference/Resolution Routines.
1222//===----------------------------------------------------------------------===//
1223
1224Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1225 // Look this name up in the comdat symbol table.
1226 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1227 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1228 if (I != ComdatSymTab.end())
1229 return &I->second;
1230
1231 // Otherwise, create a new forward reference for this value and remember it.
1232 Comdat *C = M->getOrInsertComdat(Name);
1233 ForwardRefComdats[Name] = Loc;
1234 return C;
1235}
1236
1237
1238//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001239// Helper Routines.
1240//===----------------------------------------------------------------------===//
1241
1242/// ParseToken - If the current token has the specified kind, eat it and return
1243/// success. Otherwise, emit the specified error and return failure.
1244bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1245 if (Lex.getKind() != T)
1246 return TokError(ErrMsg);
1247 Lex.Lex();
1248 return false;
1249}
1250
Chris Lattner3822f632009-01-02 08:05:26 +00001251/// ParseStringConstant
1252/// ::= StringConstant
1253bool LLParser::ParseStringConstant(std::string &Result) {
1254 if (Lex.getKind() != lltok::StringConstant)
1255 return TokError("expected string constant");
1256 Result = Lex.getStrVal();
1257 Lex.Lex();
1258 return false;
1259}
1260
1261/// ParseUInt32
1262/// ::= uint32
1263bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001264 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1265 return TokError("expected integer");
1266 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1267 if (Val64 != unsigned(Val64))
1268 return TokError("expected 32-bit integer (too large)");
1269 Val = Val64;
1270 Lex.Lex();
1271 return false;
1272}
1273
Hal Finkelb0407ba2014-07-18 15:51:28 +00001274/// ParseUInt64
1275/// ::= uint64
1276bool LLParser::ParseUInt64(uint64_t &Val) {
1277 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1278 return TokError("expected integer");
1279 Val = Lex.getAPSIntVal().getLimitedValue();
1280 Lex.Lex();
1281 return false;
1282}
1283
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001284/// ParseTLSModel
1285/// := 'localdynamic'
1286/// := 'initialexec'
1287/// := 'localexec'
1288bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1289 switch (Lex.getKind()) {
1290 default:
1291 return TokError("expected localdynamic, initialexec or localexec");
1292 case lltok::kw_localdynamic:
1293 TLM = GlobalVariable::LocalDynamicTLSModel;
1294 break;
1295 case lltok::kw_initialexec:
1296 TLM = GlobalVariable::InitialExecTLSModel;
1297 break;
1298 case lltok::kw_localexec:
1299 TLM = GlobalVariable::LocalExecTLSModel;
1300 break;
1301 }
1302
1303 Lex.Lex();
1304 return false;
1305}
1306
1307/// ParseOptionalThreadLocal
1308/// := /*empty*/
1309/// := 'thread_local'
1310/// := 'thread_local' '(' tlsmodel ')'
1311bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1312 TLM = GlobalVariable::NotThreadLocal;
1313 if (!EatIfPresent(lltok::kw_thread_local))
1314 return false;
1315
1316 TLM = GlobalVariable::GeneralDynamicTLSModel;
1317 if (Lex.getKind() == lltok::lparen) {
1318 Lex.Lex();
1319 return ParseTLSModel(TLM) ||
1320 ParseToken(lltok::rparen, "expected ')' after thread local model");
1321 }
1322 return false;
1323}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001324
1325/// ParseOptionalAddrSpace
1326/// := /*empty*/
1327/// := 'addrspace' '(' uint32 ')'
1328bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1329 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001330 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001331 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001332 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001333 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001334 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001335}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001336
Artur Pilipenko17376c42015-08-03 14:31:49 +00001337/// ParseStringAttribute
1338/// := StringConstant
1339/// := StringConstant '=' StringConstant
1340bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1341 std::string Attr = Lex.getStrVal();
1342 Lex.Lex();
1343 std::string Val;
1344 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1345 return true;
1346 B.addAttribute(Attr, Val);
1347 return false;
1348}
1349
Bill Wendling34c2eb22012-12-04 23:40:58 +00001350/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1351bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1352 bool HaveError = false;
1353
1354 B.clear();
1355
1356 while (1) {
1357 lltok::Kind Token = Lex.getKind();
1358 switch (Token) {
1359 default: // End of attributes.
1360 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001361 case lltok::StringConstant: {
1362 if (ParseStringAttribute(B))
1363 return true;
1364 continue;
1365 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001366 case lltok::kw_align: {
1367 unsigned Alignment;
1368 if (ParseOptionalAlignment(Alignment))
1369 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001370 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001371 continue;
1372 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001373 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001374 case lltok::kw_dereferenceable: {
1375 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001376 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001377 return true;
1378 B.addDereferenceableAttr(Bytes);
1379 continue;
1380 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001381 case lltok::kw_dereferenceable_or_null: {
1382 uint64_t Bytes;
1383 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1384 return true;
1385 B.addDereferenceableOrNullAttr(Bytes);
1386 continue;
1387 }
Reid Klecknera534a382013-12-19 02:14:12 +00001388 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001389 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1390 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1391 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1392 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001393 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001394 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1395 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001396 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001397 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1398 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001399 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001400 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001401 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001402
Stephen Lin7577ed52013-04-20 13:16:13 +00001403 case lltok::kw_alignstack:
1404 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001405 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001406 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001407 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001408 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001409 case lltok::kw_minsize:
1410 case lltok::kw_naked:
1411 case lltok::kw_nobuiltin:
1412 case lltok::kw_noduplicate:
1413 case lltok::kw_noimplicitfloat:
1414 case lltok::kw_noinline:
1415 case lltok::kw_nonlazybind:
1416 case lltok::kw_noredzone:
1417 case lltok::kw_noreturn:
1418 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001419 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001420 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001421 case lltok::kw_returns_twice:
1422 case lltok::kw_sanitize_address:
1423 case lltok::kw_sanitize_memory:
1424 case lltok::kw_sanitize_thread:
1425 case lltok::kw_ssp:
1426 case lltok::kw_sspreq:
1427 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001428 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001429 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001430 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1431 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001432 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001433
Bill Wendling34c2eb22012-12-04 23:40:58 +00001434 Lex.Lex();
1435 }
1436}
1437
1438/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1439bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1440 bool HaveError = false;
1441
1442 B.clear();
1443
1444 while (1) {
1445 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001446 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001447 default: // End of attributes.
1448 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001449 case lltok::StringConstant: {
1450 if (ParseStringAttribute(B))
1451 return true;
1452 continue;
1453 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001454 case lltok::kw_dereferenceable: {
1455 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001456 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001457 return true;
1458 B.addDereferenceableAttr(Bytes);
1459 continue;
1460 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001461 case lltok::kw_dereferenceable_or_null: {
1462 uint64_t Bytes;
1463 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1464 return true;
1465 B.addDereferenceableOrNullAttr(Bytes);
1466 continue;
1467 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001468 case lltok::kw_align: {
1469 unsigned Alignment;
1470 if (ParseOptionalAlignment(Alignment))
1471 return true;
1472 B.addAlignmentAttr(Alignment);
1473 continue;
1474 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001475 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1476 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001477 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001478 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1479 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001480
Bill Wendling34c2eb22012-12-04 23:40:58 +00001481 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001482 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001483 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001484 case lltok::kw_nest:
1485 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001486 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001487 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001488 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001489 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001490 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001491 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001492
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001493 case lltok::kw_alignstack:
1494 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001495 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001496 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001497 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001498 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001499 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001500 case lltok::kw_minsize:
1501 case lltok::kw_naked:
1502 case lltok::kw_nobuiltin:
1503 case lltok::kw_noduplicate:
1504 case lltok::kw_noimplicitfloat:
1505 case lltok::kw_noinline:
1506 case lltok::kw_nonlazybind:
1507 case lltok::kw_noredzone:
1508 case lltok::kw_noreturn:
1509 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001510 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001511 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001512 case lltok::kw_returns_twice:
1513 case lltok::kw_sanitize_address:
1514 case lltok::kw_sanitize_memory:
1515 case lltok::kw_sanitize_thread:
1516 case lltok::kw_ssp:
1517 case lltok::kw_sspreq:
1518 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001519 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001520 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001521 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001522 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001523
1524 case lltok::kw_readnone:
1525 case lltok::kw_readonly:
1526 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001527 }
1528
Chris Lattnerac161bf2009-01-02 07:01:27 +00001529 Lex.Lex();
1530 }
1531}
1532
1533/// ParseOptionalLinkage
1534/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001535/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001536/// ::= 'internal'
1537/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001538/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001539/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001540/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001541/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001542/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001543/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001544/// ::= 'extern_weak'
1545/// ::= 'external'
1546bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1547 HasLinkage = false;
1548 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001549 default: Res=GlobalValue::ExternalLinkage; return false;
1550 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001551 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1552 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1553 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1554 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1555 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001556 case lltok::kw_available_externally:
1557 Res = GlobalValue::AvailableExternallyLinkage;
1558 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001559 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001560 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001561 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1562 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001563 }
1564 Lex.Lex();
1565 HasLinkage = true;
1566 return false;
1567}
1568
1569/// ParseOptionalVisibility
1570/// ::= /*empty*/
1571/// ::= 'default'
1572/// ::= 'hidden'
1573/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001574///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001575bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1576 switch (Lex.getKind()) {
1577 default: Res = GlobalValue::DefaultVisibility; return false;
1578 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1579 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1580 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1581 }
1582 Lex.Lex();
1583 return false;
1584}
1585
Nico Rieck7157bb72014-01-14 15:22:47 +00001586/// ParseOptionalDLLStorageClass
1587/// ::= /*empty*/
1588/// ::= 'dllimport'
1589/// ::= 'dllexport'
1590///
1591bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1592 switch (Lex.getKind()) {
1593 default: Res = GlobalValue::DefaultStorageClass; return false;
1594 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1595 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1596 }
1597 Lex.Lex();
1598 return false;
1599}
1600
Chris Lattnerac161bf2009-01-02 07:01:27 +00001601/// ParseOptionalCallingConv
1602/// ::= /*empty*/
1603/// ::= 'ccc'
1604/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001605/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606/// ::= 'coldcc'
1607/// ::= 'x86_stdcallcc'
1608/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001609/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001610/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001611/// ::= 'arm_apcscc'
1612/// ::= 'arm_aapcscc'
1613/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001614/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001615/// ::= 'avr_intrcc'
1616/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001617/// ::= 'ptx_kernel'
1618/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001619/// ::= 'spir_func'
1620/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001621/// ::= 'x86_64_sysvcc'
1622/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001623/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001624/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001625/// ::= 'preserve_mostcc'
1626/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001627/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001628/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001629/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001630/// ::= 'hhvmcc'
1631/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001632/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001633/// ::= 'amdgpu_vs'
1634/// ::= 'amdgpu_tcs'
1635/// ::= 'amdgpu_tes'
1636/// ::= 'amdgpu_gs'
1637/// ::= 'amdgpu_ps'
1638/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001639/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001640/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001641///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001642bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643 switch (Lex.getKind()) {
1644 default: CC = CallingConv::C; return false;
1645 case lltok::kw_ccc: CC = CallingConv::C; break;
1646 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1647 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1648 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1649 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001650 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001651 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001652 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1653 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1654 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001655 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001656 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1657 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001658 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1659 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001660 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1661 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001662 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001663 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1664 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001665 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001666 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001667 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1668 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001669 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001670 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001671 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001672 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1673 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001674 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001675 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1676 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1677 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1678 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001679 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001680 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001681 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001682 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001683 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001684 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001685
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 Lex.Lex();
1687 return false;
1688}
1689
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001690/// ParseMetadataAttachment
1691/// ::= !dbg !42
1692bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1693 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1694
1695 std::string Name = Lex.getStrVal();
1696 Kind = M->getMDKindID(Name);
1697 Lex.Lex();
1698
1699 return ParseMDNode(MD);
1700}
1701
Chris Lattner5c427632009-12-30 05:31:19 +00001702/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001703/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001704bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001705 do {
1706 if (Lex.getKind() != lltok::MetadataVar)
1707 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001708
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001709 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001710 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001711 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001712 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001713
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001714 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001715 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001716 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001717
Chris Lattner596760d2009-12-29 21:25:40 +00001718 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001719 } while (EatIfPresent(lltok::comma));
1720 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001721}
1722
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001723/// ParseOptionalFunctionMetadata
1724/// ::= (!dbg !57)*
1725bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1726 while (Lex.getKind() == lltok::MetadataVar) {
1727 unsigned MDK;
1728 MDNode *N;
1729 if (ParseMetadataAttachment(MDK, N))
1730 return true;
1731
1732 F.setMetadata(MDK, N);
1733 }
1734 return false;
1735}
1736
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737/// ParseOptionalAlignment
1738/// ::= /* empty */
1739/// ::= 'align' 4
1740bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1741 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001742 if (!EatIfPresent(lltok::kw_align))
1743 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001744 LocTy AlignLoc = Lex.getLoc();
1745 if (ParseUInt32(Alignment)) return true;
1746 if (!isPowerOf2_32(Alignment))
1747 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001748 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001749 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001750 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001751}
1752
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001753/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001754/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001755/// ::= AttrKind '(' 4 ')'
1756///
1757/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1758bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1759 uint64_t &Bytes) {
1760 assert((AttrKind == lltok::kw_dereferenceable ||
1761 AttrKind == lltok::kw_dereferenceable_or_null) &&
1762 "contract!");
1763
Hal Finkelb0407ba2014-07-18 15:51:28 +00001764 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001765 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001766 return false;
1767 LocTy ParenLoc = Lex.getLoc();
1768 if (!EatIfPresent(lltok::lparen))
1769 return Error(ParenLoc, "expected '('");
1770 LocTy DerefLoc = Lex.getLoc();
1771 if (ParseUInt64(Bytes)) return true;
1772 ParenLoc = Lex.getLoc();
1773 if (!EatIfPresent(lltok::rparen))
1774 return Error(ParenLoc, "expected ')'");
1775 if (!Bytes)
1776 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1777 return false;
1778}
1779
Chris Lattnerb2f39502009-12-30 05:44:30 +00001780/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001781/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001782/// ::= ',' align 4
1783///
1784/// This returns with AteExtraComma set to true if it ate an excess comma at the
1785/// end.
1786bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1787 bool &AteExtraComma) {
1788 AteExtraComma = false;
1789 while (EatIfPresent(lltok::comma)) {
1790 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001791 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001792 AteExtraComma = true;
1793 return false;
1794 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001795
Chris Lattner95b0ff42010-04-23 00:50:50 +00001796 if (Lex.getKind() != lltok::kw_align)
1797 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001798
Chris Lattner95b0ff42010-04-23 00:50:50 +00001799 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001800 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001801
Devang Patelea8a4b92009-09-17 23:04:48 +00001802 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001803}
1804
George Burgess IV278199f2016-04-12 01:05:35 +00001805bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1806 Optional<unsigned> &HowManyArg) {
1807 Lex.Lex();
1808
1809 auto StartParen = Lex.getLoc();
1810 if (!EatIfPresent(lltok::lparen))
1811 return Error(StartParen, "expected '('");
1812
1813 if (ParseUInt32(BaseSizeArg))
1814 return true;
1815
1816 if (EatIfPresent(lltok::comma)) {
1817 auto HowManyAt = Lex.getLoc();
1818 unsigned HowMany;
1819 if (ParseUInt32(HowMany))
1820 return true;
1821 if (HowMany == BaseSizeArg)
1822 return Error(HowManyAt,
1823 "'allocsize' indices can't refer to the same parameter");
1824 HowManyArg = HowMany;
1825 } else
1826 HowManyArg = None;
1827
1828 auto EndParen = Lex.getLoc();
1829 if (!EatIfPresent(lltok::rparen))
1830 return Error(EndParen, "expected ')'");
1831 return false;
1832}
1833
Eli Friedmanfee02c62011-07-25 23:16:38 +00001834/// ParseScopeAndOrdering
1835/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1836/// else: ::=
1837///
1838/// This sets Scope and Ordering to the parsed values.
1839bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1840 AtomicOrdering &Ordering) {
1841 if (!isAtomic)
1842 return false;
1843
1844 Scope = CrossThread;
1845 if (EatIfPresent(lltok::kw_singlethread))
1846 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001847
1848 return ParseOrdering(Ordering);
1849}
1850
1851/// ParseOrdering
1852/// ::= AtomicOrdering
1853///
1854/// This sets Ordering to the parsed value.
1855bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001856 switch (Lex.getKind()) {
1857 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001858 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1859 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1860 // Not specified yet:
1861 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1862 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1863 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1864 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1865 case lltok::kw_seq_cst:
1866 Ordering = AtomicOrdering::SequentiallyConsistent;
1867 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001868 }
1869 Lex.Lex();
1870 return false;
1871}
1872
Charles Davisbe5557e2010-02-12 00:31:15 +00001873/// ParseOptionalStackAlignment
1874/// ::= /* empty */
1875/// ::= 'alignstack' '(' 4 ')'
1876bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1877 Alignment = 0;
1878 if (!EatIfPresent(lltok::kw_alignstack))
1879 return false;
1880 LocTy ParenLoc = Lex.getLoc();
1881 if (!EatIfPresent(lltok::lparen))
1882 return Error(ParenLoc, "expected '('");
1883 LocTy AlignLoc = Lex.getLoc();
1884 if (ParseUInt32(Alignment)) return true;
1885 ParenLoc = Lex.getLoc();
1886 if (!EatIfPresent(lltok::rparen))
1887 return Error(ParenLoc, "expected ')'");
1888 if (!isPowerOf2_32(Alignment))
1889 return Error(AlignLoc, "stack alignment is not a power of two");
1890 return false;
1891}
Devang Patelea8a4b92009-09-17 23:04:48 +00001892
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001893/// ParseIndexList - This parses the index list for an insert/extractvalue
1894/// instruction. This sets AteExtraComma in the case where we eat an extra
1895/// comma at the end of the line and find that it is followed by metadata.
1896/// Clients that don't allow metadata can call the version of this function that
1897/// only takes one argument.
1898///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001899/// ParseIndexList
1900/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001901///
1902bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1903 bool &AteExtraComma) {
1904 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001905
Chris Lattnerac161bf2009-01-02 07:01:27 +00001906 if (Lex.getKind() != lltok::comma)
1907 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Chris Lattner3822f632009-01-02 08:05:26 +00001909 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001910 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001911 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001912 AteExtraComma = true;
1913 return false;
1914 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001915 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001916 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917 Indices.push_back(Idx);
1918 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001919
Chris Lattnerac161bf2009-01-02 07:01:27 +00001920 return false;
1921}
1922
1923//===----------------------------------------------------------------------===//
1924// Type Parsing.
1925//===----------------------------------------------------------------------===//
1926
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001927/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001928bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001929 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930 switch (Lex.getKind()) {
1931 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001932 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001933 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001934 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001936 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001937 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939 // Type ::= StructType
1940 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001941 return true;
1942 break;
1943 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001944 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945 Lex.Lex(); // eat the lsquare.
1946 if (ParseArrayVectorType(Result, false))
1947 return true;
1948 break;
1949 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001950 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001951 Lex.Lex();
1952 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001953 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001954 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001955 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 } else if (ParseArrayVectorType(Result, true))
1957 return true;
1958 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001959 case lltok::LocalVar: {
1960 // Type ::= %foo
1961 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001962
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963 // If the type hasn't been defined yet, create a forward definition and
1964 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001965 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001966 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001967 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001969 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 Lex.Lex();
1971 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001972 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001973
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001974 case lltok::LocalVarID: {
1975 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001976 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001977
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001978 // If the type hasn't been defined yet, create a forward definition and
1979 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001980 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001981 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 Lex.Lex();
1986 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001987 }
1988 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001989
1990 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 while (1) {
1992 switch (Lex.getKind()) {
1993 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001994 default:
1995 if (!AllowVoid && Result->isVoidTy())
1996 return Error(TypeLoc, "void type only allowed for function results");
1997 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002000 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002001 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002002 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 if (Result->isVoidTy())
2004 return TokError("pointers to void are invalid - use i8* instead");
2005 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002006 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 Lex.Lex();
2009 break;
2010
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002011 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002012 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002013 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002014 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002016 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002018 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002019 unsigned AddrSpace;
2020 if (ParseOptionalAddrSpace(AddrSpace) ||
2021 ParseToken(lltok::star, "expected '*' in address space"))
2022 return true;
2023
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002025 break;
2026 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002027
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2029 case lltok::lparen:
2030 if (ParseFunctionType(Result))
2031 return true;
2032 break;
2033 }
2034 }
2035}
2036
2037/// ParseParameterList
2038/// ::= '(' ')'
2039/// ::= '(' Arg (',' Arg)* ')'
2040/// Arg
2041/// ::= Type OptionalAttributes Value OptionalAttributes
2042bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002043 PerFunctionState &PFS, bool IsMustTailCall,
2044 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002045 if (ParseToken(lltok::lparen, "expected '(' in call"))
2046 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002047
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002048 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002049 while (Lex.getKind() != lltok::rparen) {
2050 // If this isn't the first argument, we need a comma.
2051 if (!ArgList.empty() &&
2052 ParseToken(lltok::comma, "expected ',' in argument list"))
2053 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002054
Reid Kleckner83498642014-08-26 00:33:28 +00002055 // Parse an ellipsis if this is a musttail call in a variadic function.
2056 if (Lex.getKind() == lltok::dotdotdot) {
2057 const char *Msg = "unexpected ellipsis in argument list for ";
2058 if (!IsMustTailCall)
2059 return TokError(Twine(Msg) + "non-musttail call");
2060 if (!InVarArgsFunc)
2061 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2062 Lex.Lex(); // Lex the '...', it is purely for readability.
2063 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2064 }
2065
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 // Parse the argument.
2067 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002068 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002069 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002070 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002071 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002073
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002074 if (ArgTy->isMetadataTy()) {
2075 if (ParseMetadataAsValue(V, PFS))
2076 return true;
2077 } else {
2078 // Otherwise, handle normal operands.
2079 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2080 return true;
2081 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002082 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2083 AttrIndex++,
2084 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085 }
2086
Reid Kleckner83498642014-08-26 00:33:28 +00002087 if (IsMustTailCall && InVarArgsFunc)
2088 return TokError("expected '...' at end of argument list for musttail call "
2089 "in varargs function");
2090
Chris Lattnerac161bf2009-01-02 07:01:27 +00002091 Lex.Lex(); // Lex the ')'.
2092 return false;
2093}
2094
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002095/// ParseOptionalOperandBundles
2096/// ::= /*empty*/
2097/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2098///
2099/// OperandBundle
2100/// ::= bundle-tag '(' ')'
2101/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2102///
2103/// bundle-tag ::= String Constant
2104bool LLParser::ParseOptionalOperandBundles(
2105 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2106 LocTy BeginLoc = Lex.getLoc();
2107 if (!EatIfPresent(lltok::lsquare))
2108 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002109
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002110 while (Lex.getKind() != lltok::rsquare) {
2111 // If this isn't the first operand bundle, we need a comma.
2112 if (!BundleList.empty() &&
2113 ParseToken(lltok::comma, "expected ',' in input list"))
2114 return true;
2115
2116 std::string Tag;
2117 if (ParseStringConstant(Tag))
2118 return true;
2119
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002120 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2121 return true;
2122
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002123 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002124 while (Lex.getKind() != lltok::rparen) {
2125 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002126 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002127 ParseToken(lltok::comma, "expected ',' in input list"))
2128 return true;
2129
2130 Type *Ty = nullptr;
2131 Value *Input = nullptr;
2132 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2133 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002134 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002135 }
2136
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002137 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2138
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002139 Lex.Lex(); // Lex the ')'.
2140 }
2141
2142 if (BundleList.empty())
2143 return Error(BeginLoc, "operand bundle set must not be empty");
2144
2145 Lex.Lex(); // Lex the ']'.
2146 return false;
2147}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148
Chris Lattner2ed06b42009-01-05 18:34:07 +00002149/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002150/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002151/// ::= '(' ArgTypeListI ')'
2152/// ArgTypeListI
2153/// ::= /*empty*/
2154/// ::= '...'
2155/// ::= ArgTypeList ',' '...'
2156/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002157///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002158bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2159 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002160 isVarArg = false;
2161 assert(Lex.getKind() == lltok::lparen);
2162 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 if (Lex.getKind() == lltok::rparen) {
2165 // empty
2166 } else if (Lex.getKind() == lltok::dotdotdot) {
2167 isVarArg = true;
2168 Lex.Lex();
2169 } else {
2170 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002171 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002172 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002174
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002175 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002176 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002177
Chris Lattnerfdd87902009-10-05 05:54:46 +00002178 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002179 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002180
Chris Lattnerdef19492011-06-17 06:36:20 +00002181 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 Name = Lex.getStrVal();
2183 Lex.Lex();
2184 }
Chris Lattner3822f632009-01-02 08:05:26 +00002185
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002186 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002187 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002188
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002189 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002190 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2191 AttrIndex++, Attrs),
2192 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002193
Chris Lattner3822f632009-01-02 08:05:26 +00002194 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002196 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 break;
2199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 // Otherwise must be an argument type.
2202 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002203 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002204
Chris Lattnerfdd87902009-10-05 05:54:46 +00002205 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002206 return Error(TypeLoc, "argument can not have void type");
2207
Chris Lattnerdef19492011-06-17 06:36:20 +00002208 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 Name = Lex.getStrVal();
2210 Lex.Lex();
2211 } else {
2212 Name = "";
2213 }
Chris Lattner3822f632009-01-02 08:05:26 +00002214
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002215 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002216 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002217
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002218 ArgList.emplace_back(
2219 TypeLoc, ArgTy,
2220 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2221 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 }
2223 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Chris Lattner3822f632009-01-02 08:05:26 +00002225 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228/// ParseFunctionType
2229/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002230bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 assert(Lex.getKind() == lltok::lparen);
2232
Chris Lattnerce473c72009-01-05 08:04:33 +00002233 if (!FunctionType::isValidReturnType(Result))
2234 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002235
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002236 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002238 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002240
Chris Lattnerac161bf2009-01-02 07:01:27 +00002241 // Reject names on the arguments lists.
2242 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2243 if (!ArgList[i].Name.empty())
2244 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002245 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002246 return Error(ArgList[i].Loc,
2247 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Jay Foadb804a2b2011-07-12 14:06:48 +00002250 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002254 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 return false;
2256}
2257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002258/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2259/// other structs.
2260bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2261 SmallVector<Type*, 8> Elts;
2262 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002263
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264 Result = StructType::get(Context, Elts, Packed);
2265 return false;
2266}
2267
2268/// ParseStructDefinition - Parse a struct in a 'type' definition.
2269bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2270 std::pair<Type*, LocTy> &Entry,
2271 Type *&ResultTy) {
2272 // If the type was already defined, diagnose the redefinition.
2273 if (Entry.first && !Entry.second.isValid())
2274 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002275
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002276 // If we have opaque, just return without filling in the definition for the
2277 // struct. This counts as a definition as far as the .ll file goes.
2278 if (EatIfPresent(lltok::kw_opaque)) {
2279 // This type is being defined, so clear the location to indicate this.
2280 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002281
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002282 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002283 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002284 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002285 ResultTy = Entry.first;
2286 return false;
2287 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002288
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289 // If the type starts with '<', then it is either a packed struct or a vector.
2290 bool isPacked = EatIfPresent(lltok::less);
2291
2292 // If we don't have a struct, then we have a random type alias, which we
2293 // accept for compatibility with old files. These types are not allowed to be
2294 // forward referenced and not allowed to be recursive.
2295 if (Lex.getKind() != lltok::lbrace) {
2296 if (Entry.first)
2297 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002298
Craig Topper2617dcc2014-04-15 06:32:26 +00002299 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 if (isPacked)
2301 return ParseArrayVectorType(ResultTy, true);
2302 return ParseType(ResultTy);
2303 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002305 // This type is being defined, so clear the location to indicate this.
2306 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002307
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002308 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002309 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002310 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002312 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002313
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002314 SmallVector<Type*, 8> Body;
2315 if (ParseStructBody(Body) ||
2316 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2317 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002318
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002319 STy->setBody(Body, isPacked);
2320 ResultTy = STy;
2321 return false;
2322}
2323
2324
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002328/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002330/// ::= '<' '{' Type (',' Type)* '}' '>'
2331bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332 assert(Lex.getKind() == lltok::lbrace);
2333 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 // Handle the empty struct.
2336 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338
Chris Lattnerf880ca22009-03-09 04:49:14 +00002339 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002340 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 if (ParseType(Ty)) return true;
2342 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002343
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002344 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002345 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002346
Chris Lattner3822f632009-01-02 08:05:26 +00002347 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002348 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002349 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002350
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002351 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002352 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002353
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002354 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002355 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002356
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358}
2359
2360/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2361/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002362/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002363/// ::= '[' APSINTVAL 'x' Types ']'
2364/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002365bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2367 Lex.getAPSIntVal().getBitWidth() > 64)
2368 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 LocTy SizeLoc = Lex.getLoc();
2371 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002372 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002373
Chris Lattner3822f632009-01-02 08:05:26 +00002374 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2375 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376
2377 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002378 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002379 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002380
Chris Lattner3822f632009-01-02 08:05:26 +00002381 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2382 "expected end of sequential type"))
2383 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002386 if (Size == 0)
2387 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002388 if ((unsigned)Size != Size)
2389 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002390 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002391 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002392 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002394 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 }
2398 return false;
2399}
2400
2401//===----------------------------------------------------------------------===//
2402// Function Semantic Analysis.
2403//===----------------------------------------------------------------------===//
2404
Chris Lattner3432c622009-10-28 03:39:23 +00002405LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2406 int functionNumber)
2407 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408
2409 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002410 for (Argument &A : F.args())
2411 if (!A.hasName())
2412 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413}
2414
2415LLParser::PerFunctionState::~PerFunctionState() {
2416 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002417
David Blaikie9ebdc692015-09-21 21:07:50 +00002418 for (const auto &P : ForwardRefVals) {
2419 if (isa<BasicBlock>(P.second.first))
2420 continue;
2421 P.second.first->replaceAllUsesWith(
2422 UndefValue::get(P.second.first->getType()));
2423 delete P.second.first;
2424 }
2425
2426 for (const auto &P : ForwardRefValIDs) {
2427 if (isa<BasicBlock>(P.second.first))
2428 continue;
2429 P.second.first->replaceAllUsesWith(
2430 UndefValue::get(P.second.first->getType()));
2431 delete P.second.first;
2432 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433}
2434
Chris Lattner3432c622009-10-28 03:39:23 +00002435bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 if (!ForwardRefVals.empty())
2437 return P.Error(ForwardRefVals.begin()->second.second,
2438 "use of undefined value '%" + ForwardRefVals.begin()->first +
2439 "'");
2440 if (!ForwardRefValIDs.empty())
2441 return P.Error(ForwardRefValIDs.begin()->second.second,
2442 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002443 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 return false;
2445}
2446
2447
2448/// GetVal - Get a value with the specified name or ID, creating a
2449/// forward reference record if needed. This can return null if the value
2450/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002451Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002452 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 // Look this name up in the normal function symbol table.
2454 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002455
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 // If this is a forward reference for the value, see if we already created a
2457 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002458 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002459 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460 if (I != ForwardRefVals.end())
2461 Val = I->second.first;
2462 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 // If we have the value in the symbol table or fwd-ref table, return it.
2465 if (Val) {
2466 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002467 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002468 P.Error(Loc, "'%" + Name + "' is not a basic block");
2469 else
2470 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002471 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002472 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002476 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002477 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002478 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 // Otherwise, create a new forward reference for this value and remember it.
2482 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002483 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002484 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002485 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002486 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002487 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2490 return FwdVal;
2491}
2492
David Majnemer8a1c45d2015-12-12 05:38:55 +00002493Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002495 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002496
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 // If this is a forward reference for the value, see if we already created a
2498 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002499 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002500 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 if (I != ForwardRefValIDs.end())
2502 Val = I->second.first;
2503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002504
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 // If we have the value in the symbol table or fwd-ref table, return it.
2506 if (Val) {
2507 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002508 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002509 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002510 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002511 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002512 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002513 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002514 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002515
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002516 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002518 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002520
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 // Otherwise, create a new forward reference for this value and remember it.
2522 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002523 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002524 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002525 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002526 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002527 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002528
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2530 return FwdVal;
2531}
2532
2533/// SetInstName - After an instruction is parsed and inserted into its
2534/// basic block, this installs its name.
2535bool LLParser::PerFunctionState::SetInstName(int NameID,
2536 const std::string &NameStr,
2537 LocTy NameLoc, Instruction *Inst) {
2538 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002539 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 if (NameID != -1 || !NameStr.empty())
2541 return P.Error(NameLoc, "instructions returning void cannot have a name");
2542 return false;
2543 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002544
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 // If this was a numbered instruction, verify that the instruction is the
2546 // expected value and resolve any forward references.
2547 if (NameStr.empty()) {
2548 // If neither a name nor an ID was specified, just use the next ID.
2549 if (NameID == -1)
2550 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002551
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 if (unsigned(NameID) != NumberedVals.size())
2553 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002554 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
David Blaikie9ebdc692015-09-21 21:07:50 +00002556 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002558 Value *Sentinel = FI->second.first;
2559 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002560 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002561 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002562
2563 Sentinel->replaceAllUsesWith(Inst);
2564 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 ForwardRefValIDs.erase(FI);
2566 }
2567
2568 NumberedVals.push_back(Inst);
2569 return false;
2570 }
2571
2572 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002573 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002575 Value *Sentinel = FI->second.first;
2576 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002577 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002578 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002579
2580 Sentinel->replaceAllUsesWith(Inst);
2581 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 ForwardRefVals.erase(FI);
2583 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002584
Chris Lattnerac161bf2009-01-02 07:01:27 +00002585 // Set the name on the instruction.
2586 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002587
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002588 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002589 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002590 NameStr + "'");
2591 return false;
2592}
2593
2594/// GetBB - Get a basic block with the specified name or ID, creating a
2595/// forward reference record if needed.
2596BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2597 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002598 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2599 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600}
2601
2602BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002603 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2604 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605}
2606
2607/// DefineBB - Define the specified basic block, which is either named or
2608/// unnamed. If there is an error, this returns null otherwise it returns
2609/// the block being defined.
2610BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2611 LocTy Loc) {
2612 BasicBlock *BB;
2613 if (Name.empty())
2614 BB = GetBB(NumberedVals.size(), Loc);
2615 else
2616 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002617 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 // Move the block to the end of the function. Forward ref'd blocks are
2620 // inserted wherever they happen to be referenced.
2621 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002622
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 // Remove the block from forward ref sets.
2624 if (Name.empty()) {
2625 ForwardRefValIDs.erase(NumberedVals.size());
2626 NumberedVals.push_back(BB);
2627 } else {
2628 // BB forward references are already in the function symbol table.
2629 ForwardRefVals.erase(Name);
2630 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002631
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 return BB;
2633}
2634
2635//===----------------------------------------------------------------------===//
2636// Constants.
2637//===----------------------------------------------------------------------===//
2638
2639/// ParseValID - Parse an abstract value that doesn't necessarily have a
2640/// type implied. For example, if we parse "4" we don't know what integer type
2641/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002642/// sanity. PFS is used to convert function-local operands of metadata (since
2643/// metadata operands are not just parsed here but also converted to values).
2644/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002645bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002646 ID.Loc = Lex.getLoc();
2647 switch (Lex.getKind()) {
2648 default: return TokError("expected value token");
2649 case lltok::GlobalID: // @42
2650 ID.UIntVal = Lex.getUIntVal();
2651 ID.Kind = ValID::t_GlobalID;
2652 break;
2653 case lltok::GlobalVar: // @foo
2654 ID.StrVal = Lex.getStrVal();
2655 ID.Kind = ValID::t_GlobalName;
2656 break;
2657 case lltok::LocalVarID: // %42
2658 ID.UIntVal = Lex.getUIntVal();
2659 ID.Kind = ValID::t_LocalID;
2660 break;
2661 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002662 ID.StrVal = Lex.getStrVal();
2663 ID.Kind = ValID::t_LocalName;
2664 break;
2665 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667 ID.Kind = ValID::t_APSInt;
2668 break;
2669 case lltok::APFloat:
2670 ID.APFloatVal = Lex.getAPFloatVal();
2671 ID.Kind = ValID::t_APFloat;
2672 break;
2673 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002674 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 ID.Kind = ValID::t_Constant;
2676 break;
2677 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002678 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002679 ID.Kind = ValID::t_Constant;
2680 break;
2681 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2682 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2683 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002684 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002685
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 case lltok::lbrace: {
2687 // ValID ::= '{' ConstVector '}'
2688 Lex.Lex();
2689 SmallVector<Constant*, 16> Elts;
2690 if (ParseGlobalValueVector(Elts) ||
2691 ParseToken(lltok::rbrace, "expected end of struct constant"))
2692 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
David Blaikieadbda4b2015-08-03 20:08:41 +00002694 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002695 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002696 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2697 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002698 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 return false;
2700 }
2701 case lltok::less: {
2702 // ValID ::= '<' ConstVector '>' --> Vector.
2703 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2704 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002705 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002706
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 SmallVector<Constant*, 16> Elts;
2708 LocTy FirstEltLoc = Lex.getLoc();
2709 if (ParseGlobalValueVector(Elts) ||
2710 (isPackedStruct &&
2711 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2712 ParseToken(lltok::greater, "expected end of constant"))
2713 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002716 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2717 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2718 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002719 ID.UIntVal = Elts.size();
2720 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002721 return false;
2722 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002723
Chris Lattnerac161bf2009-01-02 07:01:27 +00002724 if (Elts.empty())
2725 return Error(ID.Loc, "constant vector must not be empty");
2726
Duncan Sands9dff9be2010-02-15 16:12:20 +00002727 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002728 !Elts[0]->getType()->isFloatingPointTy() &&
2729 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002731 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002732
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733 // Verify that all the vector elements have the same type.
2734 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2735 if (Elts[i]->getType() != Elts[0]->getType())
2736 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002737 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002738 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002739
Chris Lattner69229312011-02-15 00:14:00 +00002740 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002741 ID.Kind = ValID::t_Constant;
2742 return false;
2743 }
2744 case lltok::lsquare: { // Array Constant
2745 Lex.Lex();
2746 SmallVector<Constant*, 16> Elts;
2747 LocTy FirstEltLoc = Lex.getLoc();
2748 if (ParseGlobalValueVector(Elts) ||
2749 ParseToken(lltok::rsquare, "expected end of array constant"))
2750 return true;
2751
2752 // Handle empty element.
2753 if (Elts.empty()) {
2754 // Use undef instead of an array because it's inconvenient to determine
2755 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002756 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002757 return false;
2758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002759
Chris Lattnerac161bf2009-01-02 07:01:27 +00002760 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002761 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002762 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002763
Owen Anderson4056ca92009-07-29 22:17:13 +00002764 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002765
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002767 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 if (Elts[i]->getType() != Elts[0]->getType())
2769 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002770 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002771 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002773
Jay Foad83be3612011-06-22 09:24:39 +00002774 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 ID.Kind = ValID::t_Constant;
2776 return false;
2777 }
2778 case lltok::kw_c: // c "foo"
2779 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002780 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2781 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2783 ID.Kind = ValID::t_Constant;
2784 return false;
2785
2786 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002787 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2788 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002789 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 Lex.Lex();
2791 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002792 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002793 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002794 ParseStringConstant(ID.StrVal) ||
2795 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 ParseToken(lltok::StringConstant, "expected constraint string"))
2797 return true;
2798 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002799 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002800 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002801 ID.Kind = ValID::t_InlineAsm;
2802 return false;
2803 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002804
Chris Lattner3432c622009-10-28 03:39:23 +00002805 case lltok::kw_blockaddress: {
2806 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2807 Lex.Lex();
2808
2809 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002810
Chris Lattner3432c622009-10-28 03:39:23 +00002811 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2812 ParseValID(Fn) ||
2813 ParseToken(lltok::comma, "expected comma in block address expression")||
2814 ParseValID(Label) ||
2815 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2816 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002817
Chris Lattner3432c622009-10-28 03:39:23 +00002818 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2819 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002820 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002821 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002822
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002823 // Try to find the function (but skip it if it's forward-referenced).
2824 GlobalValue *GV = nullptr;
2825 if (Fn.Kind == ValID::t_GlobalID) {
2826 if (Fn.UIntVal < NumberedVals.size())
2827 GV = NumberedVals[Fn.UIntVal];
2828 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2829 GV = M->getNamedValue(Fn.StrVal);
2830 }
2831 Function *F = nullptr;
2832 if (GV) {
2833 // Confirm that it's actually a function with a definition.
2834 if (!isa<Function>(GV))
2835 return Error(Fn.Loc, "expected function name in blockaddress");
2836 F = cast<Function>(GV);
2837 if (F->isDeclaration())
2838 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2839 }
2840
2841 if (!F) {
2842 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002843 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002844 ForwardRefBlockAddresses.insert(std::make_pair(
2845 std::move(Fn),
2846 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002847 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2848 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002849 if (!FwdRef)
2850 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2851 GlobalValue::InternalLinkage, nullptr, "");
2852 ID.ConstantVal = FwdRef;
2853 ID.Kind = ValID::t_Constant;
2854 return false;
2855 }
2856
2857 // We found the function; now find the basic block. Don't use PFS, since we
2858 // might be inside a constant expression.
2859 BasicBlock *BB;
2860 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2861 if (Label.Kind == ValID::t_LocalID)
2862 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2863 else
2864 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2865 if (!BB)
2866 return Error(Label.Loc, "referenced value is not a basic block");
2867 } else {
2868 if (Label.Kind == ValID::t_LocalID)
2869 return Error(Label.Loc, "cannot take address of numeric label after "
2870 "the function is defined");
2871 BB = dyn_cast_or_null<BasicBlock>(
2872 F->getValueSymbolTable().lookup(Label.StrVal));
2873 if (!BB)
2874 return Error(Label.Loc, "referenced value is not a basic block");
2875 }
2876
2877 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002878 ID.Kind = ValID::t_Constant;
2879 return false;
2880 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002881
Chris Lattnerac161bf2009-01-02 07:01:27 +00002882 case lltok::kw_trunc:
2883 case lltok::kw_zext:
2884 case lltok::kw_sext:
2885 case lltok::kw_fptrunc:
2886 case lltok::kw_fpext:
2887 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002888 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 case lltok::kw_uitofp:
2890 case lltok::kw_sitofp:
2891 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002892 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002894 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002895 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002896 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 Constant *SrcVal;
2898 Lex.Lex();
2899 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2900 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002901 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002902 ParseType(DestTy) ||
2903 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2904 return true;
2905 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2906 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002907 getTypeString(SrcVal->getType()) + "' to '" +
2908 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002909 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002910 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002911 ID.Kind = ValID::t_Constant;
2912 return false;
2913 }
2914 case lltok::kw_extractvalue: {
2915 Lex.Lex();
2916 Constant *Val;
2917 SmallVector<unsigned, 4> Indices;
2918 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2919 ParseGlobalTypeAndValue(Val) ||
2920 ParseIndexList(Indices) ||
2921 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2922 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002923
Chris Lattner392be582010-02-12 20:49:41 +00002924 if (!Val->getType()->isAggregateType())
2925 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002926 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002928 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929 ID.Kind = ValID::t_Constant;
2930 return false;
2931 }
2932 case lltok::kw_insertvalue: {
2933 Lex.Lex();
2934 Constant *Val0, *Val1;
2935 SmallVector<unsigned, 4> Indices;
2936 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2937 ParseGlobalTypeAndValue(Val0) ||
2938 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2939 ParseGlobalTypeAndValue(Val1) ||
2940 ParseIndexList(Indices) ||
2941 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2942 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002943 if (!Val0->getType()->isAggregateType())
2944 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002945 Type *IndexedType =
2946 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2947 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002948 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002949 if (IndexedType != Val1->getType())
2950 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2951 getTypeString(Val1->getType()) +
2952 "' instead of '" + getTypeString(IndexedType) +
2953 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002954 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002955 ID.Kind = ValID::t_Constant;
2956 return false;
2957 }
2958 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002959 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 unsigned PredVal, Opc = Lex.getUIntVal();
2961 Constant *Val0, *Val1;
2962 Lex.Lex();
2963 if (ParseCmpPredicate(PredVal, Opc) ||
2964 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2965 ParseGlobalTypeAndValue(Val0) ||
2966 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2967 ParseGlobalTypeAndValue(Val1) ||
2968 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2969 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002970
Chris Lattnerac161bf2009-01-02 07:01:27 +00002971 if (Val0->getType() != Val1->getType())
2972 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002973
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002975
Chris Lattnerac161bf2009-01-02 07:01:27 +00002976 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002977 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002979 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002980 } else {
2981 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002982 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002983 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002984 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002985 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 }
2987 ID.Kind = ValID::t_Constant;
2988 return false;
2989 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002990
Chris Lattnerac161bf2009-01-02 07:01:27 +00002991 // Binary Operators.
2992 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002993 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002995 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002997 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 case lltok::kw_udiv:
2999 case lltok::kw_sdiv:
3000 case lltok::kw_fdiv:
3001 case lltok::kw_urem:
3002 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003003 case lltok::kw_frem:
3004 case lltok::kw_shl:
3005 case lltok::kw_lshr:
3006 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003007 bool NUW = false;
3008 bool NSW = false;
3009 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003010 unsigned Opc = Lex.getUIntVal();
3011 Constant *Val0, *Val1;
3012 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003013 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003014 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3015 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003016 if (EatIfPresent(lltok::kw_nuw))
3017 NUW = true;
3018 if (EatIfPresent(lltok::kw_nsw)) {
3019 NSW = true;
3020 if (EatIfPresent(lltok::kw_nuw))
3021 NUW = true;
3022 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003023 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3024 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003025 if (EatIfPresent(lltok::kw_exact))
3026 Exact = true;
3027 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003028 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3029 ParseGlobalTypeAndValue(Val0) ||
3030 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3031 ParseGlobalTypeAndValue(Val1) ||
3032 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3033 return true;
3034 if (Val0->getType() != Val1->getType())
3035 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003036 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003037 if (NUW)
3038 return Error(ModifierLoc, "nuw only applies to integer operations");
3039 if (NSW)
3040 return Error(ModifierLoc, "nsw only applies to integer operations");
3041 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003042 // Check that the type is valid for the operator.
3043 switch (Opc) {
3044 case Instruction::Add:
3045 case Instruction::Sub:
3046 case Instruction::Mul:
3047 case Instruction::UDiv:
3048 case Instruction::SDiv:
3049 case Instruction::URem:
3050 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003051 case Instruction::Shl:
3052 case Instruction::AShr:
3053 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003054 if (!Val0->getType()->isIntOrIntVectorTy())
3055 return Error(ID.Loc, "constexpr requires integer operands");
3056 break;
3057 case Instruction::FAdd:
3058 case Instruction::FSub:
3059 case Instruction::FMul:
3060 case Instruction::FDiv:
3061 case Instruction::FRem:
3062 if (!Val0->getType()->isFPOrFPVectorTy())
3063 return Error(ID.Loc, "constexpr requires fp operands");
3064 break;
3065 default: llvm_unreachable("Unknown binary operator!");
3066 }
Dan Gohman1b849082009-09-07 23:54:19 +00003067 unsigned Flags = 0;
3068 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3069 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003070 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003071 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003072 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003073 ID.Kind = ValID::t_Constant;
3074 return false;
3075 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003076
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 case lltok::kw_and:
3079 case lltok::kw_or:
3080 case lltok::kw_xor: {
3081 unsigned Opc = Lex.getUIntVal();
3082 Constant *Val0, *Val1;
3083 Lex.Lex();
3084 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3085 ParseGlobalTypeAndValue(Val0) ||
3086 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3087 ParseGlobalTypeAndValue(Val1) ||
3088 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3089 return true;
3090 if (Val0->getType() != Val1->getType())
3091 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003092 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 return Error(ID.Loc,
3094 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003095 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003096 ID.Kind = ValID::t_Constant;
3097 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003098 }
3099
Chris Lattnerac161bf2009-01-02 07:01:27 +00003100 case lltok::kw_getelementptr:
3101 case lltok::kw_shufflevector:
3102 case lltok::kw_insertelement:
3103 case lltok::kw_extractelement:
3104 case lltok::kw_select: {
3105 unsigned Opc = Lex.getUIntVal();
3106 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003107 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003108 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003109 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003110
Dan Gohman1639c392009-07-27 21:53:46 +00003111 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003112 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003113
3114 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3115 return true;
3116
3117 LocTy ExplicitTypeLoc = Lex.getLoc();
3118 if (Opc == Instruction::GetElementPtr) {
3119 if (ParseType(Ty) ||
3120 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3121 return true;
3122 }
3123
3124 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003125 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3126 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003127
Chris Lattnerac161bf2009-01-02 07:01:27 +00003128 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003129 if (Elts.size() == 0 ||
3130 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003131 return Error(ID.Loc, "base of getelementptr must be a pointer");
3132
3133 Type *BaseType = Elts[0]->getType();
3134 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003135 if (Ty != BasePointerType->getElementType())
3136 return Error(
3137 ExplicitTypeLoc,
3138 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003139
Jay Foaded8db7d2011-07-21 14:31:17 +00003140 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003141 for (Constant *Val : Indices) {
3142 Type *ValTy = Val->getType();
3143 if (!ValTy->getScalarType()->isIntegerTy())
3144 return Error(ID.Loc, "getelementptr index must be an integer");
3145 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3146 return Error(ID.Loc, "getelementptr index type missmatch");
3147 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003148 unsigned ValNumEl = ValTy->getVectorNumElements();
3149 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003150 if (ValNumEl != PtrNumEl)
3151 return Error(
3152 ID.Loc,
3153 "getelementptr vector index has a wrong number of elements");
3154 }
3155 }
3156
Craig Toppere3dcce92015-08-01 22:20:21 +00003157 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003158 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003159 return Error(ID.Loc, "base element of getelementptr must be sized");
3160
David Blaikie4a2e73b2015-04-02 18:55:32 +00003161 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003162 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003163 ID.ConstantVal =
3164 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 } else if (Opc == Instruction::Select) {
3166 if (Elts.size() != 3)
3167 return Error(ID.Loc, "expected three operands to select");
3168 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3169 Elts[2]))
3170 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003171 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003172 } else if (Opc == Instruction::ShuffleVector) {
3173 if (Elts.size() != 3)
3174 return Error(ID.Loc, "expected three operands to shufflevector");
3175 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3176 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003177 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003178 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003179 } else if (Opc == Instruction::ExtractElement) {
3180 if (Elts.size() != 2)
3181 return Error(ID.Loc, "expected two operands to extractelement");
3182 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3183 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003184 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003185 } else {
3186 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3187 if (Elts.size() != 3)
3188 return Error(ID.Loc, "expected three operands to insertelement");
3189 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3190 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003191 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003192 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003194
Chris Lattnerac161bf2009-01-02 07:01:27 +00003195 ID.Kind = ValID::t_Constant;
3196 return false;
3197 }
3198 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003199
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 Lex.Lex();
3201 return false;
3202}
3203
3204/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003205bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003206 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003207 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003208 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003209 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003210 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003211 if (V && !(C = dyn_cast<Constant>(V)))
3212 return Error(ID.Loc, "global values must be constants");
3213 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003214}
3215
Victor Hernandez9d75c962010-01-11 22:31:58 +00003216bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003217 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003218 return ParseType(Ty) ||
3219 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003220}
3221
Rafael Espindola83a362c2015-01-06 22:55:16 +00003222bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003223 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003224
3225 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003226 if (!EatIfPresent(lltok::kw_comdat))
3227 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003228
3229 if (EatIfPresent(lltok::lparen)) {
3230 if (Lex.getKind() != lltok::ComdatVar)
3231 return TokError("expected comdat variable");
3232 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3233 Lex.Lex();
3234 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3235 return true;
3236 } else {
3237 if (GlobalName.empty())
3238 return TokError("comdat cannot be unnamed");
3239 C = getComdat(GlobalName, KwLoc);
3240 }
3241
David Majnemerdad0a642014-06-27 18:19:56 +00003242 return false;
3243}
3244
Victor Hernandez9d75c962010-01-11 22:31:58 +00003245/// ParseGlobalValueVector
3246/// ::= /*empty*/
3247/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003248bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003249 // Empty list.
3250 if (Lex.getKind() == lltok::rbrace ||
3251 Lex.getKind() == lltok::rsquare ||
3252 Lex.getKind() == lltok::greater ||
3253 Lex.getKind() == lltok::rparen)
3254 return false;
3255
3256 Constant *C;
3257 if (ParseGlobalTypeAndValue(C)) return true;
3258 Elts.push_back(C);
3259
3260 while (EatIfPresent(lltok::comma)) {
3261 if (ParseGlobalTypeAndValue(C)) return true;
3262 Elts.push_back(C);
3263 }
3264
3265 return false;
3266}
3267
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003268bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003269 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003270 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003271 return true;
3272
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003273 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003274 return false;
3275}
3276
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003277/// MDNode:
3278/// ::= !{ ... }
3279/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003280/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003281bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003282 if (Lex.getKind() == lltok::MetadataVar)
3283 return ParseSpecializedMDNode(N);
3284
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003285 return ParseToken(lltok::exclaim, "expected '!' here") ||
3286 ParseMDNodeTail(N);
3287}
3288
3289bool LLParser::ParseMDNodeTail(MDNode *&N) {
3290 // !{ ... }
3291 if (Lex.getKind() == lltok::lbrace)
3292 return ParseMDTuple(N);
3293
3294 // !42
3295 return ParseMDNodeID(N);
3296}
3297
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003298namespace {
3299
3300/// Structure to represent an optional metadata field.
3301template <class FieldTy> struct MDFieldImpl {
3302 typedef MDFieldImpl ImplTy;
3303 FieldTy Val;
3304 bool Seen;
3305
3306 void assign(FieldTy Val) {
3307 Seen = true;
3308 this->Val = std::move(Val);
3309 }
3310
3311 explicit MDFieldImpl(FieldTy Default)
3312 : Val(std::move(Default)), Seen(false) {}
3313};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003314
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003315struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3316 uint64_t Max;
3317
3318 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3319 : ImplTy(Default), Max(Max) {}
3320};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003321struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003322 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003323};
3324struct ColumnField : public MDUnsignedField {
3325 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3326};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003327struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003328 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003329 DwarfTagField(dwarf::Tag DefaultTag)
3330 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003331};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003332struct DwarfMacinfoTypeField : public MDUnsignedField {
3333 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3334 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3335 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3336};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003337struct DwarfAttEncodingField : public MDUnsignedField {
3338 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3339};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003340struct DwarfVirtualityField : public MDUnsignedField {
3341 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3342};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003343struct DwarfLangField : public MDUnsignedField {
3344 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3345};
Adrian Prantlb939a252016-03-31 23:56:58 +00003346struct EmissionKindField : public MDUnsignedField {
3347 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3348};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003349
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003350struct DIFlagField : public MDUnsignedField {
3351 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3352};
3353
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003354struct MDSignedField : public MDFieldImpl<int64_t> {
3355 int64_t Min;
3356 int64_t Max;
3357
3358 MDSignedField(int64_t Default = 0)
3359 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3360 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3361 : ImplTy(Default), Min(Min), Max(Max) {}
3362};
3363
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003364struct MDBoolField : public MDFieldImpl<bool> {
3365 MDBoolField(bool Default = false) : ImplTy(Default) {}
3366};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003367struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003368 bool AllowNull;
3369
3370 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003371};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003372struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3373 MDConstant() : ImplTy(nullptr) {}
3374};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003375struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003376 bool AllowEmpty;
3377 MDStringField(bool AllowEmpty = true)
3378 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003379};
3380struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3381 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3382};
3383
3384} // end namespace
3385
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003386namespace llvm {
3387
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003388template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003389bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003390 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003391 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3392 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003393
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003394 auto &U = Lex.getAPSIntVal();
3395 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003396 return TokError("value for '" + Name + "' too large, limit is " +
3397 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003398 Result.assign(U.getZExtValue());
3399 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003400 Lex.Lex();
3401 return false;
3402}
3403
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003404template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003405bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3406 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3407}
3408template <>
3409bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3410 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3411}
3412
3413template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003414bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3415 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003416 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003417
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003418 if (Lex.getKind() != lltok::DwarfTag)
3419 return TokError("expected DWARF tag");
3420
3421 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3422 if (Tag == dwarf::DW_TAG_invalid)
3423 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003424 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003425
3426 Result.assign(Tag);
3427 Lex.Lex();
3428 return false;
3429}
3430
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003431template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003432bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003433 DwarfMacinfoTypeField &Result) {
3434 if (Lex.getKind() == lltok::APSInt)
3435 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3436
3437 if (Lex.getKind() != lltok::DwarfMacinfo)
3438 return TokError("expected DWARF macinfo type");
3439
3440 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3441 if (Macinfo == dwarf::DW_MACINFO_invalid)
3442 return TokError(
3443 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3444 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3445
3446 Result.assign(Macinfo);
3447 Lex.Lex();
3448 return false;
3449}
3450
3451template <>
3452bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003453 DwarfVirtualityField &Result) {
3454 if (Lex.getKind() == lltok::APSInt)
3455 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3456
3457 if (Lex.getKind() != lltok::DwarfVirtuality)
3458 return TokError("expected DWARF virtuality code");
3459
3460 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003461 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003462 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3463 Lex.getStrVal() + "'");
3464 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3465 Result.assign(Virtuality);
3466 Lex.Lex();
3467 return false;
3468}
3469
3470template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003471bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3472 if (Lex.getKind() == lltok::APSInt)
3473 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3474
3475 if (Lex.getKind() != lltok::DwarfLang)
3476 return TokError("expected DWARF language");
3477
3478 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3479 if (!Lang)
3480 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3481 "'");
3482 assert(Lang <= Result.Max && "Expected valid DWARF language");
3483 Result.assign(Lang);
3484 Lex.Lex();
3485 return false;
3486}
3487
3488template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003489bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3490 if (Lex.getKind() == lltok::APSInt)
3491 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3492
3493 if (Lex.getKind() != lltok::EmissionKind)
3494 return TokError("expected emission kind");
3495
3496 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3497 if (!Kind)
3498 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3499 "'");
3500 assert(*Kind <= Result.Max && "Expected valid emission kind");
3501 Result.assign(*Kind);
3502 Lex.Lex();
3503 return false;
3504}
3505
3506template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003507bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003508 DwarfAttEncodingField &Result) {
3509 if (Lex.getKind() == lltok::APSInt)
3510 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3511
3512 if (Lex.getKind() != lltok::DwarfAttEncoding)
3513 return TokError("expected DWARF type attribute encoding");
3514
3515 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3516 if (!Encoding)
3517 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3518 Lex.getStrVal() + "'");
3519 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3520 Result.assign(Encoding);
3521 Lex.Lex();
3522 return false;
3523}
3524
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003525/// DIFlagField
3526/// ::= uint32
3527/// ::= DIFlagVector
3528/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3529template <>
3530bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3531 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3532
3533 // Parser for a single flag.
3534 auto parseFlag = [&](unsigned &Val) {
3535 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3536 return ParseUInt32(Val);
3537
3538 if (Lex.getKind() != lltok::DIFlag)
3539 return TokError("expected debug info flag");
3540
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003541 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003542 if (!Val)
3543 return TokError(Twine("invalid debug info flag flag '") +
3544 Lex.getStrVal() + "'");
3545 Lex.Lex();
3546 return false;
3547 };
3548
3549 // Parse the flags and combine them together.
3550 unsigned Combined = 0;
3551 do {
3552 unsigned Val;
3553 if (parseFlag(Val))
3554 return true;
3555 Combined |= Val;
3556 } while (EatIfPresent(lltok::bar));
3557
3558 Result.assign(Combined);
3559 return false;
3560}
3561
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003562template <>
3563bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003564 MDSignedField &Result) {
3565 if (Lex.getKind() != lltok::APSInt)
3566 return TokError("expected signed integer");
3567
3568 auto &S = Lex.getAPSIntVal();
3569 if (S < Result.Min)
3570 return TokError("value for '" + Name + "' too small, limit is " +
3571 Twine(Result.Min));
3572 if (S > Result.Max)
3573 return TokError("value for '" + Name + "' too large, limit is " +
3574 Twine(Result.Max));
3575 Result.assign(S.getExtValue());
3576 assert(Result.Val >= Result.Min && "Expected value in range");
3577 assert(Result.Val <= Result.Max && "Expected value in range");
3578 Lex.Lex();
3579 return false;
3580}
3581
3582template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003583bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3584 switch (Lex.getKind()) {
3585 default:
3586 return TokError("expected 'true' or 'false'");
3587 case lltok::kw_true:
3588 Result.assign(true);
3589 break;
3590 case lltok::kw_false:
3591 Result.assign(false);
3592 break;
3593 }
3594 Lex.Lex();
3595 return false;
3596}
3597
3598template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003599bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003600 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003601 if (!Result.AllowNull)
3602 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003603 Lex.Lex();
3604 Result.assign(nullptr);
3605 return false;
3606 }
3607
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003608 Metadata *MD;
3609 if (ParseMetadata(MD, nullptr))
3610 return true;
3611
3612 Result.assign(MD);
3613 return false;
3614}
3615
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003616template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003617bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3618 Metadata *MD;
3619 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3620 return true;
3621
3622 Result.assign(cast<ConstantAsMetadata>(MD));
3623 return false;
3624}
3625
3626template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003627bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003628 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003629 std::string S;
3630 if (ParseStringConstant(S))
3631 return true;
3632
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003633 if (!Result.AllowEmpty && S.empty())
3634 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3635
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003636 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003637 return false;
3638}
3639
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003640template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003641bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3642 SmallVector<Metadata *, 4> MDs;
3643 if (ParseMDNodeVector(MDs))
3644 return true;
3645
3646 Result.assign(std::move(MDs));
3647 return false;
3648}
3649
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003650} // end namespace llvm
3651
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003652template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003653bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003654 do {
3655 if (Lex.getKind() != lltok::LabelStr)
3656 return TokError("expected field label here");
3657
3658 if (parseField())
3659 return true;
3660 } while (EatIfPresent(lltok::comma));
3661
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003662 return false;
3663}
3664
3665template <class ParserTy>
3666bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3667 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3668 Lex.Lex();
3669
3670 if (ParseToken(lltok::lparen, "expected '(' here"))
3671 return true;
3672 if (Lex.getKind() != lltok::rparen)
3673 if (ParseMDFieldsImplBody(parseField))
3674 return true;
3675
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003676 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003677 return ParseToken(lltok::rparen, "expected ')' here");
3678}
3679
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003680template <class FieldTy>
3681bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3682 if (Result.Seen)
3683 return TokError("field '" + Name + "' cannot be specified more than once");
3684
3685 LocTy Loc = Lex.getLoc();
3686 Lex.Lex();
3687 return ParseMDField(Loc, Name, Result);
3688}
3689
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003690bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3691 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003692
3693#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003694 if (Lex.getStrVal() == #CLASS) \
3695 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003696#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003697
3698 return TokError("expected metadata type");
3699}
3700
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003701#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3702#define NOP_FIELD(NAME, TYPE, INIT)
3703#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3704 if (!NAME.Seen) \
3705 return Error(ClosingLoc, "missing required field '" #NAME "'");
3706#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003707 if (Lex.getStrVal() == #NAME) \
3708 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003709#define PARSE_MD_FIELDS() \
3710 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3711 do { \
3712 LocTy ClosingLoc; \
3713 if (ParseMDFieldsImpl([&]() -> bool { \
3714 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3715 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3716 }, ClosingLoc)) \
3717 return true; \
3718 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3719 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003720#define GET_OR_DISTINCT(CLASS, ARGS) \
3721 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003722
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003723/// ParseDILocationFields:
3724/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3725bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003726#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003727 OPTIONAL(line, LineField, ); \
3728 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003729 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003730 OPTIONAL(inlinedAt, MDField, );
3731 PARSE_MD_FIELDS();
3732#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003733
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003734 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003735 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003736 return false;
3737}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003738
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003739/// ParseGenericDINode:
3740/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3741bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003742#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003743 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003744 OPTIONAL(header, MDStringField, ); \
3745 OPTIONAL(operands, MDFieldList, );
3746 PARSE_MD_FIELDS();
3747#undef VISIT_MD_FIELDS
3748
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003749 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003750 (Context, tag.Val, header.Val, operands.Val));
3751 return false;
3752}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003753
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003754/// ParseDISubrange:
3755/// ::= !DISubrange(count: 30, lowerBound: 2)
3756bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003757#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003758 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003759 OPTIONAL(lowerBound, MDSignedField, );
3760 PARSE_MD_FIELDS();
3761#undef VISIT_MD_FIELDS
3762
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003763 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003764 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003765}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003766
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003767/// ParseDIEnumerator:
3768/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3769bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003770#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003771 REQUIRED(name, MDStringField, ); \
3772 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003773 PARSE_MD_FIELDS();
3774#undef VISIT_MD_FIELDS
3775
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003776 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003777 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003778}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003779
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003780/// ParseDIBasicType:
3781/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3782bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003783#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003784 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003785 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003786 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3787 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003788 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003789 PARSE_MD_FIELDS();
3790#undef VISIT_MD_FIELDS
3791
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003792 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003793 align.Val, encoding.Val));
3794 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003795}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003796
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003797/// ParseDIDerivedType:
3798/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003799/// line: 7, scope: !1, baseType: !2, size: 32,
3800/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003801bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003802#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3803 REQUIRED(tag, DwarfTagField, ); \
3804 OPTIONAL(name, MDStringField, ); \
3805 OPTIONAL(file, MDField, ); \
3806 OPTIONAL(line, LineField, ); \
3807 OPTIONAL(scope, MDField, ); \
3808 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003809 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3810 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3811 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003812 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003813 OPTIONAL(extraData, MDField, );
3814 PARSE_MD_FIELDS();
3815#undef VISIT_MD_FIELDS
3816
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003817 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003818 (Context, tag.Val, name.Val, file.Val, line.Val,
3819 scope.Val, baseType.Val, size.Val, align.Val,
3820 offset.Val, flags.Val, extraData.Val));
3821 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003822}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003823
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003824bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3826 REQUIRED(tag, DwarfTagField, ); \
3827 OPTIONAL(name, MDStringField, ); \
3828 OPTIONAL(file, MDField, ); \
3829 OPTIONAL(line, LineField, ); \
3830 OPTIONAL(scope, MDField, ); \
3831 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003832 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3833 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3834 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003835 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003836 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003837 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003838 OPTIONAL(vtableHolder, MDField, ); \
3839 OPTIONAL(templateParams, MDField, ); \
3840 OPTIONAL(identifier, MDStringField, );
3841 PARSE_MD_FIELDS();
3842#undef VISIT_MD_FIELDS
3843
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003844 // If this has an identifier try to build an ODR type.
3845 if (identifier.Val)
3846 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003847 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3848 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3849 elements.Val, runtimeLang.Val, vtableHolder.Val,
3850 templateParams.Val)) {
3851 Result = CT;
3852 return false;
3853 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003854
3855 // Create a new node, and save it in the context if it belongs in the type
3856 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003857 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003858 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003859 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3860 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3861 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3862 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003863}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003864
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003865bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003866#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003867 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003868 REQUIRED(types, MDField, );
3869 PARSE_MD_FIELDS();
3870#undef VISIT_MD_FIELDS
3871
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003872 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003873 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003874}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003875
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003876/// ParseDIFileType:
3877/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3878bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003879#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3880 REQUIRED(filename, MDStringField, ); \
3881 REQUIRED(directory, MDStringField, );
3882 PARSE_MD_FIELDS();
3883#undef VISIT_MD_FIELDS
3884
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003885 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003886 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003887}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003888
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003889/// ParseDICompileUnit:
3890/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003891/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003892/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003893/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003894/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003895bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003896 if (!IsDistinct)
3897 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3898
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003899#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3900 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003901 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003902 OPTIONAL(producer, MDStringField, ); \
3903 OPTIONAL(isOptimized, MDBoolField, ); \
3904 OPTIONAL(flags, MDStringField, ); \
3905 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3906 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003907 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003908 OPTIONAL(enums, MDField, ); \
3909 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003910 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003911 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003912 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003913 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003914 PARSE_MD_FIELDS();
3915#undef VISIT_MD_FIELDS
3916
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003917 Result = DICompileUnit::getDistinct(
3918 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3919 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Adrian Prantl75819ae2016-04-15 15:57:41 +00003920 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003921 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003922}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003923
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003924/// ParseDISubprogram:
3925/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003926/// file: !1, line: 7, type: !2, isLocal: false,
3927/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003928/// virtuality: DW_VIRTUALTIY_pure_virtual,
3929/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003930/// isOptimized: false, templateParams: !4, declaration: !5,
3931/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003932bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003933 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003934#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3935 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003936 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003937 OPTIONAL(linkageName, MDStringField, ); \
3938 OPTIONAL(file, MDField, ); \
3939 OPTIONAL(line, LineField, ); \
3940 OPTIONAL(type, MDField, ); \
3941 OPTIONAL(isLocal, MDBoolField, ); \
3942 OPTIONAL(isDefinition, MDBoolField, (true)); \
3943 OPTIONAL(scopeLine, LineField, ); \
3944 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003945 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003946 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003947 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003948 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00003949 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003950 OPTIONAL(templateParams, MDField, ); \
3951 OPTIONAL(declaration, MDField, ); \
3952 OPTIONAL(variables, MDField, );
3953 PARSE_MD_FIELDS();
3954#undef VISIT_MD_FIELDS
3955
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003956 if (isDefinition.Val && !IsDistinct)
3957 return Lex.Error(
3958 Loc,
3959 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3960
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003961 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00003962 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3963 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3964 scopeLine.Val, containingType.Val, virtuality.Val,
3965 virtualIndex.Val, flags.Val, isOptimized.Val, unit.Val,
3966 templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003967 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003968}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003969
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003970/// ParseDILexicalBlock:
3971/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3972bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003973#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003974 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003975 OPTIONAL(file, MDField, ); \
3976 OPTIONAL(line, LineField, ); \
3977 OPTIONAL(column, ColumnField, );
3978 PARSE_MD_FIELDS();
3979#undef VISIT_MD_FIELDS
3980
3981 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003982 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003983 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003984}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003985
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003986/// ParseDILexicalBlockFile:
3987/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3988bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003989#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003990 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003991 OPTIONAL(file, MDField, ); \
3992 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3993 PARSE_MD_FIELDS();
3994#undef VISIT_MD_FIELDS
3995
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003996 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003997 (Context, scope.Val, file.Val, discriminator.Val));
3998 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003999}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004000
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004001/// ParseDINamespace:
4002/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4003bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004004#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4005 REQUIRED(scope, MDField, ); \
4006 OPTIONAL(file, MDField, ); \
4007 OPTIONAL(name, MDStringField, ); \
4008 OPTIONAL(line, LineField, );
4009 PARSE_MD_FIELDS();
4010#undef VISIT_MD_FIELDS
4011
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004012 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004013 (Context, scope.Val, file.Val, name.Val, line.Val));
4014 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004015}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004016
Amjad Abouda9bcf162015-12-10 12:56:35 +00004017/// ParseDIMacro:
4018/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4019bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4020#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4021 REQUIRED(type, DwarfMacinfoTypeField, ); \
4022 REQUIRED(line, LineField, ); \
4023 REQUIRED(name, MDStringField, ); \
4024 OPTIONAL(value, MDStringField, );
4025 PARSE_MD_FIELDS();
4026#undef VISIT_MD_FIELDS
4027
4028 Result = GET_OR_DISTINCT(DIMacro,
4029 (Context, type.Val, line.Val, name.Val, value.Val));
4030 return false;
4031}
4032
4033/// ParseDIMacroFile:
4034/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4035bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4036#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4037 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4038 REQUIRED(line, LineField, ); \
4039 REQUIRED(file, MDField, ); \
4040 OPTIONAL(nodes, MDField, );
4041 PARSE_MD_FIELDS();
4042#undef VISIT_MD_FIELDS
4043
4044 Result = GET_OR_DISTINCT(DIMacroFile,
4045 (Context, type.Val, line.Val, file.Val, nodes.Val));
4046 return false;
4047}
4048
4049
Adrian Prantlab1243f2015-06-29 23:03:47 +00004050/// ParseDIModule:
4051/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4052/// includePath: "/usr/include", isysroot: "/")
4053bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4054#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4055 REQUIRED(scope, MDField, ); \
4056 REQUIRED(name, MDStringField, ); \
4057 OPTIONAL(configMacros, MDStringField, ); \
4058 OPTIONAL(includePath, MDStringField, ); \
4059 OPTIONAL(isysroot, MDStringField, );
4060 PARSE_MD_FIELDS();
4061#undef VISIT_MD_FIELDS
4062
4063 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4064 configMacros.Val, includePath.Val, isysroot.Val));
4065 return false;
4066}
4067
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004068/// ParseDITemplateTypeParameter:
4069/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4070bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004071#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004072 OPTIONAL(name, MDStringField, ); \
4073 REQUIRED(type, MDField, );
4074 PARSE_MD_FIELDS();
4075#undef VISIT_MD_FIELDS
4076
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004077 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004078 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004079 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004080}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004081
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004082/// ParseDITemplateValueParameter:
4083/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004084/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004085bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004086#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004087 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004088 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004089 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004090 REQUIRED(value, MDField, );
4091 PARSE_MD_FIELDS();
4092#undef VISIT_MD_FIELDS
4093
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004094 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004095 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004096 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004097}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004098
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004099/// ParseDIGlobalVariable:
4100/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004101/// file: !1, line: 7, type: !2, isLocal: false,
4102/// isDefinition: true, variable: i32* @foo,
4103/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004104bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004105#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004106 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004107 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004108 OPTIONAL(linkageName, MDStringField, ); \
4109 OPTIONAL(file, MDField, ); \
4110 OPTIONAL(line, LineField, ); \
4111 OPTIONAL(type, MDField, ); \
4112 OPTIONAL(isLocal, MDBoolField, ); \
4113 OPTIONAL(isDefinition, MDBoolField, (true)); \
4114 OPTIONAL(variable, MDConstant, ); \
4115 OPTIONAL(declaration, MDField, );
4116 PARSE_MD_FIELDS();
4117#undef VISIT_MD_FIELDS
4118
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004119 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004120 (Context, scope.Val, name.Val, linkageName.Val,
4121 file.Val, line.Val, type.Val, isLocal.Val,
4122 isDefinition.Val, variable.Val, declaration.Val));
4123 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004124}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004125
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004126/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004127/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4128/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4129/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004130/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004131bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004132#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004133 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004134 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004135 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004136 OPTIONAL(file, MDField, ); \
4137 OPTIONAL(line, LineField, ); \
4138 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004139 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004140 PARSE_MD_FIELDS();
4141#undef VISIT_MD_FIELDS
4142
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004143 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004144 (Context, scope.Val, name.Val, file.Val, line.Val,
4145 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004146 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004147}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004148
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004149/// ParseDIExpression:
4150/// ::= !DIExpression(0, 7, -1)
4151bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004152 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4153 Lex.Lex();
4154
4155 if (ParseToken(lltok::lparen, "expected '(' here"))
4156 return true;
4157
4158 SmallVector<uint64_t, 8> Elements;
4159 if (Lex.getKind() != lltok::rparen)
4160 do {
4161 if (Lex.getKind() == lltok::DwarfOp) {
4162 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4163 Lex.Lex();
4164 Elements.push_back(Op);
4165 continue;
4166 }
4167 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4168 }
4169
4170 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4171 return TokError("expected unsigned integer");
4172
4173 auto &U = Lex.getAPSIntVal();
4174 if (U.ugt(UINT64_MAX))
4175 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4176 Elements.push_back(U.getZExtValue());
4177 Lex.Lex();
4178 } while (EatIfPresent(lltok::comma));
4179
4180 if (ParseToken(lltok::rparen, "expected ')' here"))
4181 return true;
4182
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004183 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004184 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004185}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004186
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004187/// ParseDIObjCProperty:
4188/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004189/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004190bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004191#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004192 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004193 OPTIONAL(file, MDField, ); \
4194 OPTIONAL(line, LineField, ); \
4195 OPTIONAL(setter, MDStringField, ); \
4196 OPTIONAL(getter, MDStringField, ); \
4197 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4198 OPTIONAL(type, MDField, );
4199 PARSE_MD_FIELDS();
4200#undef VISIT_MD_FIELDS
4201
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004202 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004203 (Context, name.Val, file.Val, line.Val, setter.Val,
4204 getter.Val, attributes.Val, type.Val));
4205 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004206}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004207
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004208/// ParseDIImportedEntity:
4209/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004210/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004211bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004212#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4213 REQUIRED(tag, DwarfTagField, ); \
4214 REQUIRED(scope, MDField, ); \
4215 OPTIONAL(entity, MDField, ); \
4216 OPTIONAL(line, LineField, ); \
4217 OPTIONAL(name, MDStringField, );
4218 PARSE_MD_FIELDS();
4219#undef VISIT_MD_FIELDS
4220
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004221 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004222 entity.Val, line.Val, name.Val));
4223 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004224}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004225
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004226#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004227#undef NOP_FIELD
4228#undef REQUIRE_FIELD
4229#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004230
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004231/// ParseMetadataAsValue
4232/// ::= metadata i32 %local
4233/// ::= metadata i32 @global
4234/// ::= metadata i32 7
4235/// ::= metadata !0
4236/// ::= metadata !{...}
4237/// ::= metadata !"string"
4238bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4239 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004240 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004241 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004242 return true;
4243
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004244 V = MetadataAsValue::get(Context, MD);
4245 return false;
4246}
4247
4248/// ParseValueAsMetadata
4249/// ::= i32 %local
4250/// ::= i32 @global
4251/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004252bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4253 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004254 Type *Ty;
4255 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004256 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004257 return true;
4258 if (Ty->isMetadataTy())
4259 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4260
4261 Value *V;
4262 if (ParseValue(Ty, V, PFS))
4263 return true;
4264
4265 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004266 return false;
4267}
4268
4269/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004270/// ::= i32 %local
4271/// ::= i32 @global
4272/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004273/// ::= !42
4274/// ::= !{...}
4275/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004276/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004277bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004278 if (Lex.getKind() == lltok::MetadataVar) {
4279 MDNode *N;
4280 if (ParseSpecializedMDNode(N))
4281 return true;
4282 MD = N;
4283 return false;
4284 }
4285
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004286 // ValueAsMetadata:
4287 // <type> <value>
4288 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004289 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004290
4291 // '!'.
4292 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4293 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004294
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004295 // MDString:
4296 // ::= '!' STRINGCONSTANT
4297 if (Lex.getKind() == lltok::StringConstant) {
4298 MDString *S;
4299 if (ParseMDString(S))
4300 return true;
4301 MD = S;
4302 return false;
4303 }
4304
Dan Gohman8939ba332010-07-14 18:26:50 +00004305 // MDNode:
4306 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004307 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004308 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004309 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004310 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004311 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004312 return false;
4313}
4314
Victor Hernandez9d75c962010-01-11 22:31:58 +00004315
4316//===----------------------------------------------------------------------===//
4317// Function Parsing.
4318//===----------------------------------------------------------------------===//
4319
Chris Lattner229907c2011-07-18 04:54:35 +00004320bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004321 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004322 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004324
Chris Lattnerac161bf2009-01-02 07:01:27 +00004325 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004326 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004327 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004328 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004329 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004330 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004331 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004332 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004333 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004334 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004335 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004336 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004337 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4338 (ID.UIntVal >> 1) & 1,
4339 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004340 return false;
4341 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004342 case ValID::t_GlobalName:
4343 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004344 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004345 case ValID::t_GlobalID:
4346 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004347 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004349 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004350 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004351 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004352 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004353 return false;
4354 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004355 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004356 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4357 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004358
Dan Gohman518cda42011-12-17 00:04:22 +00004359 // The lexer has no type info, so builds all half, float, and double FP
4360 // constants as double. Fix this here. Long double does not need this.
4361 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004362 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004363 if (Ty->isHalfTy())
4364 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4365 &Ignored);
4366 else if (Ty->isFloatTy())
4367 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4368 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004369 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004370 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004371
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004372 if (V->getType() != Ty)
4373 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004374 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004375
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 return false;
4377 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004378 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004379 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004380 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004381 return false;
4382 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004383 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004384 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004385 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004386 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004387 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004388 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004389 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004390 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004391 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004392 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004393 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004394 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004395 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004397 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004398 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004399 case ValID::t_None:
4400 if (!Ty->isTokenTy())
4401 return Error(ID.Loc, "invalid type for none constant");
4402 V = Constant::getNullValue(Ty);
4403 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004404 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004405 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004406 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004407
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408 V = ID.ConstantVal;
4409 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004410 case ValID::t_ConstantStruct:
4411 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004412 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004413 if (ST->getNumElements() != ID.UIntVal)
4414 return Error(ID.Loc,
4415 "initializer with struct type has wrong # elements");
4416 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4417 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004419 // Verify that the elements are compatible with the structtype.
4420 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4421 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4422 return Error(ID.Loc, "element " + Twine(i) +
4423 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004424
David Blaikieadbda4b2015-08-03 20:08:41 +00004425 V = ConstantStruct::get(
4426 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004427 } else
4428 return Error(ID.Loc, "constant expression type mismatch");
4429 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004430 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004431 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004432}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004433
Alex Lorenzd2255952015-07-17 22:07:03 +00004434bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4435 C = nullptr;
4436 ValID ID;
4437 auto Loc = Lex.getLoc();
4438 if (ParseValID(ID, /*PFS=*/nullptr))
4439 return true;
4440 switch (ID.Kind) {
4441 case ValID::t_APSInt:
4442 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004443 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004444 case ValID::t_Constant:
4445 case ValID::t_ConstantStruct:
4446 case ValID::t_PackedConstantStruct: {
4447 Value *V;
4448 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4449 return true;
4450 assert(isa<Constant>(V) && "Expected a constant value");
4451 C = cast<Constant>(V);
4452 return false;
4453 }
4454 default:
4455 return Error(Loc, "expected a constant value");
4456 }
4457}
4458
David Majnemer8a1c45d2015-12-12 05:38:55 +00004459bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004460 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004462 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004463}
4464
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004465bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004466 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004467 return ParseType(Ty) ||
4468 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469}
4470
Chris Lattner3ed871f2009-10-27 19:13:16 +00004471bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4472 PerFunctionState &PFS) {
4473 Value *V;
4474 Loc = Lex.getLoc();
4475 if (ParseTypeAndValue(V, PFS)) return true;
4476 if (!isa<BasicBlock>(V))
4477 return Error(Loc, "expected a basic block");
4478 BB = cast<BasicBlock>(V);
4479 return false;
4480}
4481
4482
Chris Lattnerac161bf2009-01-02 07:01:27 +00004483/// FunctionHeader
4484/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004485/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004486/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4488 // Parse the linkage.
4489 LocTy LinkageLoc = Lex.getLoc();
4490 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004491
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004492 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004493 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004494 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004495 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004496 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004497 LocTy RetTypeLoc = Lex.getLoc();
4498 if (ParseOptionalLinkage(Linkage) ||
4499 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004500 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004501 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004502 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004503 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004504 return true;
4505
4506 // Verify that the linkage is ok.
4507 switch ((GlobalValue::LinkageTypes)Linkage) {
4508 case GlobalValue::ExternalLinkage:
4509 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004510 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004511 if (isDefine)
4512 return Error(LinkageLoc, "invalid linkage for function definition");
4513 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004514 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004516 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004517 case GlobalValue::LinkOnceAnyLinkage:
4518 case GlobalValue::LinkOnceODRLinkage:
4519 case GlobalValue::WeakAnyLinkage:
4520 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004521 if (!isDefine)
4522 return Error(LinkageLoc, "invalid linkage for function declaration");
4523 break;
4524 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004525 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 return Error(LinkageLoc, "invalid function linkage type");
4527 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004528
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004529 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4530 return Error(LinkageLoc,
4531 "symbol with local linkage must have default visibility");
4532
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004533 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004534 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004535
Chris Lattnerac161bf2009-01-02 07:01:27 +00004536 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004537
4538 std::string FunctionName;
4539 if (Lex.getKind() == lltok::GlobalVar) {
4540 FunctionName = Lex.getStrVal();
4541 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4542 unsigned NameID = Lex.getUIntVal();
4543
4544 if (NameID != NumberedVals.size())
4545 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004546 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004547 } else {
4548 return TokError("expected function name");
4549 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004550
Chris Lattner3822f632009-01-02 08:05:26 +00004551 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004552
Chris Lattner3822f632009-01-02 08:05:26 +00004553 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004554 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004555
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004556 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004558 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004559 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004560 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004561 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004562 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004563 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004564 bool UnnamedAddr;
4565 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004566 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004567 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004568 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004569 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004570
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004571 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004572 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4573 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004574 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004575 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004576 (EatIfPresent(lltok::kw_section) &&
4577 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004578 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004579 ParseOptionalAlignment(Alignment) ||
4580 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004581 ParseStringConstant(GC)) ||
4582 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004583 ParseGlobalTypeAndValue(Prefix)) ||
4584 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004585 ParseGlobalTypeAndValue(Prologue)) ||
4586 (EatIfPresent(lltok::kw_personality) &&
4587 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004588 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004589
Michael Gottesman41748d72013-06-27 00:25:01 +00004590 if (FuncAttrs.contains(Attribute::Builtin))
4591 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004592
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004594 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004595 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004596 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004598
Chris Lattnerac161bf2009-01-02 07:01:27 +00004599 // Okay, if we got here, the function is syntactically valid. Convert types
4600 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004601 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004602 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004603
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004604 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004605 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4606 AttributeSet::ReturnIndex,
4607 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004608
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004610 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004611 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4612 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004613 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4614 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615 }
4616
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004617 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004618 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4619 AttributeSet::FunctionIndex,
4620 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004621
Bill Wendlinge94d8432012-12-07 23:16:57 +00004622 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004623
Bill Wendling749a43d2012-12-30 13:50:49 +00004624 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004625 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4626
Chris Lattner229907c2011-07-18 04:54:35 +00004627 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004628 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004629 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630
Craig Topper2617dcc2014-04-15 06:32:26 +00004631 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632 if (!FunctionName.empty()) {
4633 // If this was a definition of a forward reference, remove the definition
4634 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004635 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636 if (FRVI != ForwardRefVals.end()) {
4637 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004638 if (!Fn)
4639 return Error(FRVI->second.second, "invalid forward reference to "
4640 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004641 if (Fn->getType() != PFT)
4642 return Error(FRVI->second.second, "invalid forward reference to "
4643 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004644
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645 ForwardRefVals.erase(FRVI);
4646 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004647 // Reject redefinitions.
4648 return Error(NameLoc, "invalid redefinition of function '" +
4649 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004650 } else if (M->getNamedValue(FunctionName)) {
4651 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004653
Dan Gohman399d6ae2009-08-29 23:37:49 +00004654 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004655 // If this is a definition of a forward referenced function, make sure the
4656 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004657 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658 if (I != ForwardRefValIDs.end()) {
4659 Fn = cast<Function>(I->second.first);
4660 if (Fn->getType() != PFT)
4661 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004662 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004663 ForwardRefValIDs.erase(I);
4664 }
4665 }
4666
Craig Topper2617dcc2014-04-15 06:32:26 +00004667 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004668 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4669 else // Move the forward-reference to the correct spot in the module.
4670 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4671
4672 if (FunctionName.empty())
4673 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004674
Chris Lattnerac161bf2009-01-02 07:01:27 +00004675 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4676 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004677 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004678 Fn->setCallingConv(CC);
4679 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004680 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004681 Fn->setAlignment(Alignment);
4682 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004683 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004684 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004685 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004686 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004687 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004688 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004689
Chris Lattnerac161bf2009-01-02 07:01:27 +00004690 // Add all of the arguments we parsed to the function.
4691 Function::arg_iterator ArgIt = Fn->arg_begin();
4692 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4693 // If the argument has a name, insert it into the argument symbol table.
4694 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004695
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 // Set the name, if it conflicted, it will be auto-renamed.
4697 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004698
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004699 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4701 ArgList[i].Name + "'");
4702 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004703
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004704 if (isDefine)
4705 return false;
4706
Robin Morisset039781e2014-08-29 21:53:01 +00004707 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004708 ValID ID;
4709 if (FunctionName.empty()) {
4710 ID.Kind = ValID::t_GlobalID;
4711 ID.UIntVal = NumberedVals.size() - 1;
4712 } else {
4713 ID.Kind = ValID::t_GlobalName;
4714 ID.StrVal = FunctionName;
4715 }
4716 auto Blocks = ForwardRefBlockAddresses.find(ID);
4717 if (Blocks != ForwardRefBlockAddresses.end())
4718 return Error(Blocks->first.Loc,
4719 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004720 return false;
4721}
4722
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004723bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4724 ValID ID;
4725 if (FunctionNumber == -1) {
4726 ID.Kind = ValID::t_GlobalName;
4727 ID.StrVal = F.getName();
4728 } else {
4729 ID.Kind = ValID::t_GlobalID;
4730 ID.UIntVal = FunctionNumber;
4731 }
4732
4733 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4734 if (Blocks == P.ForwardRefBlockAddresses.end())
4735 return false;
4736
4737 for (const auto &I : Blocks->second) {
4738 const ValID &BBID = I.first;
4739 GlobalValue *GV = I.second;
4740
4741 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4742 "Expected local id or name");
4743 BasicBlock *BB;
4744 if (BBID.Kind == ValID::t_LocalName)
4745 BB = GetBB(BBID.StrVal, BBID.Loc);
4746 else
4747 BB = GetBB(BBID.UIntVal, BBID.Loc);
4748 if (!BB)
4749 return P.Error(BBID.Loc, "referenced value is not a basic block");
4750
4751 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4752 GV->eraseFromParent();
4753 }
4754
4755 P.ForwardRefBlockAddresses.erase(Blocks);
4756 return false;
4757}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004758
4759/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004760/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004761bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004762 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763 return TokError("expected '{' in function body");
4764 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004765
Chris Lattner3432c622009-10-28 03:39:23 +00004766 int FunctionNumber = -1;
4767 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004768
Chris Lattner3432c622009-10-28 03:39:23 +00004769 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004770
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004771 // Resolve block addresses and allow basic blocks to be forward-declared
4772 // within this function.
4773 if (PFS.resolveForwardRefBlockAddresses())
4774 return true;
4775 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4776
Chris Lattnerbbddd962010-01-09 19:20:07 +00004777 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004778 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004779 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004780
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004781 while (Lex.getKind() != lltok::rbrace &&
4782 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004783 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004784
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004785 while (Lex.getKind() != lltok::rbrace)
4786 if (ParseUseListOrder(&PFS))
4787 return true;
4788
Chris Lattnerac161bf2009-01-02 07:01:27 +00004789 // Eat the }.
4790 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004791
Chris Lattnerac161bf2009-01-02 07:01:27 +00004792 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004793 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794}
4795
4796/// ParseBasicBlock
4797/// ::= LabelStr? Instruction*
4798bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4799 // If this basic block starts out with a name, remember it.
4800 std::string Name;
4801 LocTy NameLoc = Lex.getLoc();
4802 if (Lex.getKind() == lltok::LabelStr) {
4803 Name = Lex.getStrVal();
4804 Lex.Lex();
4805 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004806
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004808 if (!BB)
4809 return Error(NameLoc,
4810 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004811
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004813
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 // Parse the instructions in this block until we get a terminator.
4815 Instruction *Inst;
4816 do {
4817 // This instruction may have three possibilities for a name: a) none
4818 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4819 LocTy NameLoc = Lex.getLoc();
4820 int NameID = -1;
4821 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004822
Chris Lattnerac161bf2009-01-02 07:01:27 +00004823 if (Lex.getKind() == lltok::LocalVarID) {
4824 NameID = Lex.getUIntVal();
4825 Lex.Lex();
4826 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4827 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004828 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004829 NameStr = Lex.getStrVal();
4830 Lex.Lex();
4831 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4832 return true;
4833 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004834
Chris Lattner77b89dc2009-12-30 05:23:43 +00004835 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004836 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004837 case InstError: return true;
4838 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004839 BB->getInstList().push_back(Inst);
4840
Chris Lattner77b89dc2009-12-30 05:23:43 +00004841 // With a normal result, we check to see if the instruction is followed by
4842 // a comma and metadata.
4843 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004844 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004845 return true;
4846 break;
4847 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004848 BB->getInstList().push_back(Inst);
4849
Chris Lattner77b89dc2009-12-30 05:23:43 +00004850 // If the instruction parser ate an extra comma at the end of it, it
4851 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004852 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004853 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004854 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004855 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004856
Chris Lattnerac161bf2009-01-02 07:01:27 +00004857 // Set the name on the instruction.
4858 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4859 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004860
Chris Lattnerac161bf2009-01-02 07:01:27 +00004861 return false;
4862}
4863
4864//===----------------------------------------------------------------------===//
4865// Instruction Parsing.
4866//===----------------------------------------------------------------------===//
4867
4868/// ParseInstruction - Parse one of the many different instructions.
4869///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004870int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4871 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004872 lltok::Kind Token = Lex.getKind();
4873 if (Token == lltok::Eof)
4874 return TokError("found end of file when expecting more instructions");
4875 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004876 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004877 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004878
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879 switch (Token) {
4880 default: return Error(Loc, "expected instruction opcode");
4881 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004882 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004883 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4884 case lltok::kw_br: return ParseBr(Inst, PFS);
4885 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004886 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004887 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004888 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004889 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4890 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004891 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4892 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004893 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004894 // Binary Operators.
4895 case lltok::kw_add:
4896 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004897 case lltok::kw_mul:
4898 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004899 bool NUW = EatIfPresent(lltok::kw_nuw);
4900 bool NSW = EatIfPresent(lltok::kw_nsw);
4901 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004902
Chris Lattnera676c0f2011-02-07 16:40:21 +00004903 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004904
Chris Lattnera676c0f2011-02-07 16:40:21 +00004905 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4906 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4907 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004908 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004909 case lltok::kw_fadd:
4910 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004911 case lltok::kw_fmul:
4912 case lltok::kw_fdiv:
4913 case lltok::kw_frem: {
4914 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4915 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4916 if (Res != 0)
4917 return Res;
4918 if (FMF.any())
4919 Inst->setFastMathFlags(FMF);
4920 return 0;
4921 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004922
Chris Lattner35315d02011-02-06 21:44:57 +00004923 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004924 case lltok::kw_udiv:
4925 case lltok::kw_lshr:
4926 case lltok::kw_ashr: {
4927 bool Exact = EatIfPresent(lltok::kw_exact);
4928
4929 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4930 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4931 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004932 }
4933
Chris Lattnerac161bf2009-01-02 07:01:27 +00004934 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004935 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004936 case lltok::kw_and:
4937 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004938 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004939 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4940 case lltok::kw_fcmp: {
4941 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4942 int Res = ParseCompare(Inst, PFS, KeywordVal);
4943 if (Res != 0)
4944 return Res;
4945 if (FMF.any())
4946 Inst->setFastMathFlags(FMF);
4947 return 0;
4948 }
4949
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 // Casts.
4951 case lltok::kw_trunc:
4952 case lltok::kw_zext:
4953 case lltok::kw_sext:
4954 case lltok::kw_fptrunc:
4955 case lltok::kw_fpext:
4956 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004957 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004958 case lltok::kw_uitofp:
4959 case lltok::kw_sitofp:
4960 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004961 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004962 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004963 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004964 // Other.
4965 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004966 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004967 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4968 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4969 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4970 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004971 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004972 // Call.
4973 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4974 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4975 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004976 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004977 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004978 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004979 case lltok::kw_load: return ParseLoad(Inst, PFS);
4980 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004981 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4982 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004983 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4985 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4986 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4987 }
4988}
4989
4990/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4991bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004992 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004993 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004994 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4996 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4997 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4998 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4999 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5000 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5001 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5002 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5003 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5004 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5005 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5006 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5007 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5008 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5009 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5010 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5011 }
5012 } else {
5013 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005014 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005015 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5016 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5017 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5018 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5019 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5020 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5021 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5022 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5023 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5024 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5025 }
5026 }
5027 Lex.Lex();
5028 return false;
5029}
5030
5031//===----------------------------------------------------------------------===//
5032// Terminator Instructions.
5033//===----------------------------------------------------------------------===//
5034
5035/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005036/// ::= 'ret' void (',' !dbg, !1)*
5037/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005038bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005039 PerFunctionState &PFS) {
5040 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005041 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005042 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005043
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005044 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005045
Chris Lattnerfdd87902009-10-05 05:54:46 +00005046 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005047 if (!ResType->isVoidTy())
5048 return Error(TypeLoc, "value doesn't match function result type '" +
5049 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005050
Owen Anderson55f1c092009-08-13 21:58:54 +00005051 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005052 return false;
5053 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005054
Chris Lattnerac161bf2009-01-02 07:01:27 +00005055 Value *RV;
5056 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005058 if (ResType != RV->getType())
5059 return Error(TypeLoc, "value doesn't match function result type '" +
5060 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005061
Owen Anderson55f1c092009-08-13 21:58:54 +00005062 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005063 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064}
5065
5066
5067/// ParseBr
5068/// ::= 'br' TypeAndValue
5069/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5070bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5071 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005072 Value *Op0;
5073 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005074 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005075
Chris Lattnerac161bf2009-01-02 07:01:27 +00005076 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5077 Inst = BranchInst::Create(BB);
5078 return false;
5079 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005080
Owen Anderson55f1c092009-08-13 21:58:54 +00005081 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005083
Chris Lattnerac161bf2009-01-02 07:01:27 +00005084 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005085 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005087 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005089
Chris Lattner3ed871f2009-10-27 19:13:16 +00005090 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005091 return false;
5092}
5093
5094/// ParseSwitch
5095/// Instruction
5096/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5097/// JumpTable
5098/// ::= (TypeAndValue ',' TypeAndValue)*
5099bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5100 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005101 Value *Cond;
5102 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5104 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005105 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5107 return true;
5108
Duncan Sands19d0b472010-02-16 11:11:14 +00005109 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005110 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005111
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112 // Parse the jump table pairs.
5113 SmallPtrSet<Value*, 32> SeenCases;
5114 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5115 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005116 Value *Constant;
5117 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005118
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5120 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005121 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005122 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005123
David Blaikie70573dc2014-11-19 07:49:26 +00005124 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005125 return Error(CondLoc, "duplicate case value in switch");
5126 if (!isa<ConstantInt>(Constant))
5127 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005128
Chris Lattner3ed871f2009-10-27 19:13:16 +00005129 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Chris Lattnerac161bf2009-01-02 07:01:27 +00005132 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005133
Chris Lattner3ed871f2009-10-27 19:13:16 +00005134 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005135 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5136 SI->addCase(Table[i].first, Table[i].second);
5137 Inst = SI;
5138 return false;
5139}
5140
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005141/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005142/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005143/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5144bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005145 LocTy AddrLoc;
5146 Value *Address;
5147 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005148 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5149 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005150 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005151
Duncan Sands19d0b472010-02-16 11:11:14 +00005152 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005153 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005154
Chris Lattner3ed871f2009-10-27 19:13:16 +00005155 // Parse the destination list.
5156 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005157
Chris Lattner3ed871f2009-10-27 19:13:16 +00005158 if (Lex.getKind() != lltok::rsquare) {
5159 BasicBlock *DestBB;
5160 if (ParseTypeAndBasicBlock(DestBB, PFS))
5161 return true;
5162 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005163
Chris Lattner3ed871f2009-10-27 19:13:16 +00005164 while (EatIfPresent(lltok::comma)) {
5165 if (ParseTypeAndBasicBlock(DestBB, PFS))
5166 return true;
5167 DestList.push_back(DestBB);
5168 }
5169 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005170
Chris Lattner3ed871f2009-10-27 19:13:16 +00005171 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5172 return true;
5173
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005174 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005175 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5176 IBI->addDestination(DestList[i]);
5177 Inst = IBI;
5178 return false;
5179}
5180
5181
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182/// ParseInvoke
5183/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5184/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5185bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5186 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005187 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005188 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005189 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005190 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005191 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 LocTy RetTypeLoc;
5193 ValID CalleeID;
5194 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005195 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005196
Chris Lattner3ed871f2009-10-27 19:13:16 +00005197 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005198 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005199 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005200 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005201 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5202 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005203 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005205 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005206 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005207 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005209
Chris Lattnerac161bf2009-01-02 07:01:27 +00005210 // If RetType is a non-function pointer type, then this is the short syntax
5211 // for the call, which means that RetType is just the return type. Infer the
5212 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005213 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5214 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005216 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005217 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5218 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005219
Chris Lattnerac161bf2009-01-02 07:01:27 +00005220 if (!FunctionType::isValidReturnType(RetType))
5221 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005222
Owen Anderson4056ca92009-07-29 22:17:13 +00005223 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005225
David Blaikie41ba2b42015-07-27 23:32:19 +00005226 CalleeID.FTy = Ty;
5227
Chris Lattnerac161bf2009-01-02 07:01:27 +00005228 // Look up the callee.
5229 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005230 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5231 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005232
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005233 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005234 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005235 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005236 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5237 AttributeSet::ReturnIndex,
5238 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005239
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005241
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242 // Loop through FunctionType's arguments and ensure they are specified
5243 // correctly. Also, gather any parameter attributes.
5244 FunctionType::param_iterator I = Ty->param_begin();
5245 FunctionType::param_iterator E = Ty->param_end();
5246 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005247 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005248 if (I != E) {
5249 ExpectedTy = *I++;
5250 } else if (!Ty->isVarArg()) {
5251 return Error(ArgList[i].Loc, "too many arguments specified");
5252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005253
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5255 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005256 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005258 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5259 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005260 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5261 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005262 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005263
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 if (I != E)
5265 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005266
David Majnemer8d22abd2015-02-23 00:01:32 +00005267 if (FnAttrs.hasAttributes()) {
5268 if (FnAttrs.hasAlignmentAttr())
5269 return Error(CallLoc, "invoke instructions may not have an alignment");
5270
Bill Wendlingf5075a42013-01-27 02:24:02 +00005271 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5272 AttributeSet::FunctionIndex,
5273 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005274 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005275
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005276 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005277 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005278
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005279 InvokeInst *II =
5280 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005281 II->setCallingConv(CC);
5282 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005283 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005284 Inst = II;
5285 return false;
5286}
5287
Bill Wendlingf891bf82011-07-31 06:30:59 +00005288/// ParseResume
5289/// ::= 'resume' TypeAndValue
5290bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5291 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005292 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5293 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294
Bill Wendlingf891bf82011-07-31 06:30:59 +00005295 ResumeInst *RI = ResumeInst::Create(Exn);
5296 Inst = RI;
5297 return false;
5298}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005299
David Majnemer654e1302015-07-31 17:58:14 +00005300bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5301 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005302 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005303 return true;
5304
5305 while (Lex.getKind() != lltok::rsquare) {
5306 // If this isn't the first argument, we need a comma.
5307 if (!Args.empty() &&
5308 ParseToken(lltok::comma, "expected ',' in argument list"))
5309 return true;
5310
5311 // Parse the argument.
5312 LocTy ArgLoc;
5313 Type *ArgTy = nullptr;
5314 if (ParseType(ArgTy, ArgLoc))
5315 return true;
5316
5317 Value *V;
5318 if (ArgTy->isMetadataTy()) {
5319 if (ParseMetadataAsValue(V, PFS))
5320 return true;
5321 } else {
5322 if (ParseValue(ArgTy, V, PFS))
5323 return true;
5324 }
5325 Args.push_back(V);
5326 }
5327
5328 Lex.Lex(); // Lex the ']'.
5329 return false;
5330}
5331
5332/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005333/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005334bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005335 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005336
David Majnemer8a1c45d2015-12-12 05:38:55 +00005337 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5338 return true;
5339
5340 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005341 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005342
5343 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5344 return true;
5345
5346 BasicBlock *UnwindBB = nullptr;
5347 if (Lex.getKind() == lltok::kw_to) {
5348 Lex.Lex();
5349 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5350 return true;
5351 } else {
5352 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5353 return true;
5354 }
5355 }
5356
David Majnemer8a1c45d2015-12-12 05:38:55 +00005357 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005358 return false;
5359}
5360
5361/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005362/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005363bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005364 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005365
David Majnemer8a1c45d2015-12-12 05:38:55 +00005366 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5367 return true;
5368
5369 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005370 return true;
5371
David Majnemer0bc0eef2015-08-15 02:46:08 +00005372 BasicBlock *BB;
5373 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5374 ParseTypeAndBasicBlock(BB, PFS))
5375 return true;
5376
David Majnemer8a1c45d2015-12-12 05:38:55 +00005377 Inst = CatchReturnInst::Create(CatchPad, BB);
5378 return false;
5379}
5380
5381/// ParseCatchSwitch
5382/// ::= 'catchswitch' within Parent
5383bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5384 Value *ParentPad;
5385 LocTy BBLoc;
5386
5387 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5388 return true;
5389
5390 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5391 Lex.getKind() != lltok::LocalVarID)
5392 return TokError("expected scope value for catchswitch");
5393
5394 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5395 return true;
5396
5397 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5398 return true;
5399
5400 SmallVector<BasicBlock *, 32> Table;
5401 do {
5402 BasicBlock *DestBB;
5403 if (ParseTypeAndBasicBlock(DestBB, PFS))
5404 return true;
5405 Table.push_back(DestBB);
5406 } while (EatIfPresent(lltok::comma));
5407
5408 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5409 return true;
5410
5411 if (ParseToken(lltok::kw_unwind,
5412 "expected 'unwind' after catchswitch scope"))
5413 return true;
5414
5415 BasicBlock *UnwindBB = nullptr;
5416 if (EatIfPresent(lltok::kw_to)) {
5417 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5418 return true;
5419 } else {
5420 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5421 return true;
5422 }
5423
5424 auto *CatchSwitch =
5425 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5426 for (BasicBlock *DestBB : Table)
5427 CatchSwitch->addHandler(DestBB);
5428 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005429 return false;
5430}
5431
5432/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005433/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005434bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005435 Value *CatchSwitch = nullptr;
5436
5437 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5438 return true;
5439
5440 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5441 return TokError("expected scope value for catchpad");
5442
5443 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5444 return true;
5445
David Majnemer654e1302015-07-31 17:58:14 +00005446 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005447 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005448 return true;
5449
David Majnemer8a1c45d2015-12-12 05:38:55 +00005450 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005451 return false;
5452}
5453
David Majnemer654e1302015-07-31 17:58:14 +00005454/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005455/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005456bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005457 Value *ParentPad = nullptr;
5458
5459 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5460 return true;
5461
5462 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5463 Lex.getKind() != lltok::LocalVarID)
5464 return TokError("expected scope value for cleanuppad");
5465
5466 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5467 return true;
5468
David Majnemer654e1302015-07-31 17:58:14 +00005469 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005470 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005471 return true;
5472
David Majnemer8a1c45d2015-12-12 05:38:55 +00005473 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005474 return false;
5475}
5476
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477//===----------------------------------------------------------------------===//
5478// Binary Operators.
5479//===----------------------------------------------------------------------===//
5480
5481/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005482/// ::= ArithmeticOps TypeAndValue ',' Value
5483///
5484/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5485/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005486bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005487 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005488 LocTy Loc; Value *LHS, *RHS;
5489 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5490 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5491 ParseValue(LHS->getType(), RHS, PFS))
5492 return true;
5493
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005494 bool Valid;
5495 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005496 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005497 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005498 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5499 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005500 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005501 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5502 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005504
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005505 if (!Valid)
5506 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005507
Chris Lattnerac161bf2009-01-02 07:01:27 +00005508 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5509 return false;
5510}
5511
5512/// ParseLogical
5513/// ::= ArithmeticOps TypeAndValue ',' Value {
5514bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5515 unsigned Opc) {
5516 LocTy Loc; Value *LHS, *RHS;
5517 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5518 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5519 ParseValue(LHS->getType(), RHS, PFS))
5520 return true;
5521
Duncan Sands9dff9be2010-02-15 16:12:20 +00005522 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005523 return Error(Loc,"instruction requires integer or integer vector operands");
5524
5525 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5526 return false;
5527}
5528
5529
5530/// ParseCompare
5531/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5532/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005533bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5534 unsigned Opc) {
5535 // Parse the integer/fp comparison predicate.
5536 LocTy Loc;
5537 unsigned Pred;
5538 Value *LHS, *RHS;
5539 if (ParseCmpPredicate(Pred, Opc) ||
5540 ParseTypeAndValue(LHS, Loc, PFS) ||
5541 ParseToken(lltok::comma, "expected ',' after compare value") ||
5542 ParseValue(LHS->getType(), RHS, PFS))
5543 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005544
Chris Lattnerac161bf2009-01-02 07:01:27 +00005545 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005546 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005548 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005549 } else {
5550 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005551 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005552 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005554 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005555 }
5556 return false;
5557}
5558
5559//===----------------------------------------------------------------------===//
5560// Other Instructions.
5561//===----------------------------------------------------------------------===//
5562
5563
5564/// ParseCast
5565/// ::= CastOpc TypeAndValue 'to' Type
5566bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5567 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005568 LocTy Loc;
5569 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005570 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005571 if (ParseTypeAndValue(Op, Loc, PFS) ||
5572 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5573 ParseType(DestTy))
5574 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005575
Chris Lattner89d856e2009-03-01 00:53:13 +00005576 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5577 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005578 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005579 getTypeString(Op->getType()) + "' to '" +
5580 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005581 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5583 return false;
5584}
5585
5586/// ParseSelect
5587/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5588bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5589 LocTy Loc;
5590 Value *Op0, *Op1, *Op2;
5591 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5592 ParseToken(lltok::comma, "expected ',' after select condition") ||
5593 ParseTypeAndValue(Op1, PFS) ||
5594 ParseToken(lltok::comma, "expected ',' after select value") ||
5595 ParseTypeAndValue(Op2, PFS))
5596 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005597
Chris Lattnerac161bf2009-01-02 07:01:27 +00005598 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5599 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005600
Chris Lattnerac161bf2009-01-02 07:01:27 +00005601 Inst = SelectInst::Create(Op0, Op1, Op2);
5602 return false;
5603}
5604
Chris Lattnerb55ab542009-01-05 08:18:44 +00005605/// ParseVA_Arg
5606/// ::= 'va_arg' TypeAndValue ',' Type
5607bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005608 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005609 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005610 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005611 if (ParseTypeAndValue(Op, PFS) ||
5612 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005613 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005614 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005615
Chris Lattnerb55ab542009-01-05 08:18:44 +00005616 if (!EltTy->isFirstClassType())
5617 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005618
5619 Inst = new VAArgInst(Op, EltTy);
5620 return false;
5621}
5622
5623/// ParseExtractElement
5624/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5625bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5626 LocTy Loc;
5627 Value *Op0, *Op1;
5628 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5629 ParseToken(lltok::comma, "expected ',' after extract value") ||
5630 ParseTypeAndValue(Op1, PFS))
5631 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005632
Chris Lattnerac161bf2009-01-02 07:01:27 +00005633 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5634 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005635
Eric Christopherc9742252009-07-25 02:28:41 +00005636 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005637 return false;
5638}
5639
5640/// ParseInsertElement
5641/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5642bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5643 LocTy Loc;
5644 Value *Op0, *Op1, *Op2;
5645 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5646 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5647 ParseTypeAndValue(Op1, PFS) ||
5648 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5649 ParseTypeAndValue(Op2, PFS))
5650 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005651
Chris Lattnerac161bf2009-01-02 07:01:27 +00005652 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005653 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005654
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5656 return false;
5657}
5658
5659/// ParseShuffleVector
5660/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5661bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5662 LocTy Loc;
5663 Value *Op0, *Op1, *Op2;
5664 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5665 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5666 ParseTypeAndValue(Op1, PFS) ||
5667 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5668 ParseTypeAndValue(Op2, PFS))
5669 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005670
Chris Lattnerac161bf2009-01-02 07:01:27 +00005671 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005672 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005673
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5675 return false;
5676}
5677
5678/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005679/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005680int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005681 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005682 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005683
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005684 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005685 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5686 ParseValue(Ty, Op0, PFS) ||
5687 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005688 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005689 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5690 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005691
Chris Lattnerf4f03422009-12-30 05:27:33 +00005692 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5694 while (1) {
5695 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005696
Chris Lattner3822f632009-01-02 08:05:26 +00005697 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005698 break;
5699
Chris Lattnerf4f03422009-12-30 05:27:33 +00005700 if (Lex.getKind() == lltok::MetadataVar) {
5701 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005702 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005703 }
Devang Patel8f842d32009-10-16 18:45:49 +00005704
Chris Lattner3822f632009-01-02 08:05:26 +00005705 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005706 ParseValue(Ty, Op0, PFS) ||
5707 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005708 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005709 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5710 return true;
5711 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005712
Chris Lattnerac161bf2009-01-02 07:01:27 +00005713 if (!Ty->isFirstClassType())
5714 return Error(TypeLoc, "phi node must have first class type");
5715
Jay Foad52131342011-03-30 11:28:46 +00005716 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5718 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5719 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005720 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005721}
5722
Bill Wendlingfae14752011-08-12 20:24:12 +00005723/// ParseLandingPad
5724/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5725/// Clause
5726/// ::= 'catch' TypeAndValue
5727/// ::= 'filter'
5728/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5729bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005730 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005731
David Majnemer7fddecc2015-06-17 20:52:32 +00005732 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005733 return true;
5734
David Majnemer7fddecc2015-06-17 20:52:32 +00005735 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005736 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5737
5738 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5739 LandingPadInst::ClauseType CT;
5740 if (EatIfPresent(lltok::kw_catch))
5741 CT = LandingPadInst::Catch;
5742 else if (EatIfPresent(lltok::kw_filter))
5743 CT = LandingPadInst::Filter;
5744 else
5745 return TokError("expected 'catch' or 'filter' clause type");
5746
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005747 Value *V;
5748 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005749 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005750 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005751
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005752 // A 'catch' type expects a non-array constant. A filter clause expects an
5753 // array constant.
5754 if (CT == LandingPadInst::Catch) {
5755 if (isa<ArrayType>(V->getType()))
5756 Error(VLoc, "'catch' clause has an invalid type");
5757 } else {
5758 if (!isa<ArrayType>(V->getType()))
5759 Error(VLoc, "'filter' clause has an invalid type");
5760 }
5761
Owen Andersonf8f259d2015-03-09 07:13:42 +00005762 Constant *CV = dyn_cast<Constant>(V);
5763 if (!CV)
5764 return Error(VLoc, "clause argument must be a constant");
5765 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005766 }
5767
Owen Andersonf8f259d2015-03-09 07:13:42 +00005768 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005769 return false;
5770}
5771
Chris Lattnerac161bf2009-01-02 07:01:27 +00005772/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005773/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5774/// OptionalAttrs Type Value ParameterList OptionalAttrs
5775/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5776/// OptionalAttrs Type Value ParameterList OptionalAttrs
5777/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5778/// OptionalAttrs Type Value ParameterList OptionalAttrs
5779/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5780/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005781bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005782 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005783 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005784 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005785 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005786 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005787 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788 LocTy RetTypeLoc;
5789 ValID CalleeID;
5790 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005791 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005792 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005793
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005794 if (TCK != CallInst::TCK_None &&
5795 ParseToken(lltok::kw_call,
5796 "expected 'tail call', 'musttail call', or 'notail call'"))
5797 return true;
5798
5799 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5800
5801 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005802 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005804 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5805 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005806 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5807 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005809
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005810 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5811 return Error(CallLoc, "fast-math-flags specified for call without "
5812 "floating-point scalar or vector return type");
5813
Chris Lattnerac161bf2009-01-02 07:01:27 +00005814 // If RetType is a non-function pointer type, then this is the short syntax
5815 // for the call, which means that RetType is just the return type. Infer the
5816 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005817 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5818 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005819 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005820 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005821 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5822 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005823
Chris Lattnerac161bf2009-01-02 07:01:27 +00005824 if (!FunctionType::isValidReturnType(RetType))
5825 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005826
Owen Anderson4056ca92009-07-29 22:17:13 +00005827 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005829
David Blaikie41ba2b42015-07-27 23:32:19 +00005830 CalleeID.FTy = Ty;
5831
Chris Lattnerac161bf2009-01-02 07:01:27 +00005832 // Look up the callee.
5833 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005834 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5835 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005836
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005837 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005838 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005839 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005840 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5841 AttributeSet::ReturnIndex,
5842 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005843
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005845
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 // Loop through FunctionType's arguments and ensure they are specified
5847 // correctly. Also, gather any parameter attributes.
5848 FunctionType::param_iterator I = Ty->param_begin();
5849 FunctionType::param_iterator E = Ty->param_end();
5850 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005851 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 if (I != E) {
5853 ExpectedTy = *I++;
5854 } else if (!Ty->isVarArg()) {
5855 return Error(ArgList[i].Loc, "too many arguments specified");
5856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005857
Chris Lattnerac161bf2009-01-02 07:01:27 +00005858 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5859 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005860 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005861 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005862 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5863 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005864 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5865 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005867
Chris Lattnerac161bf2009-01-02 07:01:27 +00005868 if (I != E)
5869 return Error(CallLoc, "not enough parameters specified for call");
5870
David Majnemer8d22abd2015-02-23 00:01:32 +00005871 if (FnAttrs.hasAttributes()) {
5872 if (FnAttrs.hasAlignmentAttr())
5873 return Error(CallLoc, "call instructions may not have an alignment");
5874
Bill Wendlingf5075a42013-01-27 02:24:02 +00005875 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5876 AttributeSet::FunctionIndex,
5877 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005878 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005879
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005880 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005881 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005882
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005883 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005884 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005885 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005886 if (FMF.any())
5887 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005889 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005890 Inst = CI;
5891 return false;
5892}
5893
5894//===----------------------------------------------------------------------===//
5895// Memory Instructions.
5896//===----------------------------------------------------------------------===//
5897
5898/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005899/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5900/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005901int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005902 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005903 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005904 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005905 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005906
5907 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005908 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005909
David Majnemera3b0eb22015-02-16 08:38:03 +00005910 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005911
David Majnemera3b0eb22015-02-16 08:38:03 +00005912 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5913 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005914
Chris Lattnerb2f39502009-12-30 05:44:30 +00005915 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005916 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005917 if (Lex.getKind() == lltok::kw_align) {
5918 if (ParseOptionalAlignment(Alignment)) return true;
5919 } else if (Lex.getKind() == lltok::MetadataVar) {
5920 AteExtraComma = true;
5921 } else {
5922 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5923 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5924 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005925 }
5926 }
5927
Dan Gohman2140a742010-05-28 01:14:11 +00005928 if (Size && !Size->getType()->isIntegerTy())
5929 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005930
Reid Kleckner436c42e2014-01-17 23:58:17 +00005931 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5932 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005933 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005934 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005935 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005936}
5937
5938/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005939/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005940/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005941/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005942int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005943 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005944 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005945 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005946 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005947 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005948 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005949
5950 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005951 isAtomic = true;
5952 Lex.Lex();
5953 }
5954
Chris Lattnerbc639292011-11-27 06:56:53 +00005955 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005956 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005957 isVolatile = true;
5958 Lex.Lex();
5959 }
5960
David Blaikie15d9a4c2015-04-06 20:59:48 +00005961 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005962 LocTy ExplicitTypeLoc = Lex.getLoc();
5963 if (ParseType(Ty) ||
5964 ParseToken(lltok::comma, "expected comma after load's type") ||
5965 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005966 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005967 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5968 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005969
David Blaikie15d9a4c2015-04-06 20:59:48 +00005970 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005971 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005972 if (isAtomic && !Alignment)
5973 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00005974 if (Ordering == AtomicOrdering::Release ||
5975 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00005976 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005977
David Blaikiea79ac142015-02-27 21:17:42 +00005978 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5979 return Error(ExplicitTypeLoc,
5980 "explicit pointee type doesn't match operand's pointee type");
5981
David Blaikie15d9a4c2015-04-06 20:59:48 +00005982 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005983 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005984}
5985
5986/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005987
5988/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5989/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005990/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005991int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005993 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005994 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005995 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00005996 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00005997 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005998
5999 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006000 isAtomic = true;
6001 Lex.Lex();
6002 }
6003
Chris Lattnerbc639292011-11-27 06:56:53 +00006004 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006005 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006006 isVolatile = true;
6007 Lex.Lex();
6008 }
6009
Chris Lattnerac161bf2009-01-02 07:01:27 +00006010 if (ParseTypeAndValue(Val, Loc, PFS) ||
6011 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006012 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006013 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006014 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006016
Duncan Sands19d0b472010-02-16 11:11:14 +00006017 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006018 return Error(PtrLoc, "store operand must be a pointer");
6019 if (!Val->getType()->isFirstClassType())
6020 return Error(Loc, "store operand must be a first class value");
6021 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6022 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006023 if (isAtomic && !Alignment)
6024 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006025 if (Ordering == AtomicOrdering::Acquire ||
6026 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006027 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006028
Eli Friedman59b66882011-08-09 23:02:53 +00006029 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006030 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006031}
6032
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006033/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006034/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6035/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006036int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006037 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6038 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006039 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6040 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006041 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006042 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006043 bool isWeak = false;
6044
6045 if (EatIfPresent(lltok::kw_weak))
6046 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006047
6048 if (EatIfPresent(lltok::kw_volatile))
6049 isVolatile = true;
6050
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006051 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6052 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6053 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6054 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6055 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006056 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6057 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006058 return true;
6059
JF Bastien800f87a2016-04-06 21:19:33 +00006060 if (SuccessOrdering == AtomicOrdering::Unordered ||
6061 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006062 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006063 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6064 return TokError("cmpxchg failure argument shall be no stronger than the "
6065 "success argument");
6066 if (FailureOrdering == AtomicOrdering::Release ||
6067 FailureOrdering == AtomicOrdering::AcquireRelease)
6068 return TokError(
6069 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006070 if (!Ptr->getType()->isPointerTy())
6071 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6072 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6073 return Error(CmpLoc, "compare value and pointer type do not match");
6074 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6075 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006076 if (!New->getType()->isFirstClassType())
6077 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006078 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6079 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006080 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006081 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006082 Inst = CXI;
6083 return AteExtraComma ? InstExtraComma : InstNormal;
6084}
6085
6086/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006087/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6088/// 'singlethread'? AtomicOrdering
6089int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006090 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6091 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006092 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006093 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006094 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006095 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006096
6097 if (EatIfPresent(lltok::kw_volatile))
6098 isVolatile = true;
6099
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006100 switch (Lex.getKind()) {
6101 default: return TokError("expected binary operation in atomicrmw");
6102 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6103 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6104 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6105 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6106 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6107 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6108 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6109 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6110 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6111 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6112 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6113 }
6114 Lex.Lex(); // Eat the operation.
6115
6116 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6117 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6118 ParseTypeAndValue(Val, ValLoc, PFS) ||
6119 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6120 return true;
6121
JF Bastien800f87a2016-04-06 21:19:33 +00006122 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006123 return TokError("atomicrmw cannot be unordered");
6124 if (!Ptr->getType()->isPointerTy())
6125 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6126 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6127 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6128 if (!Val->getType()->isIntegerTy())
6129 return Error(ValLoc, "atomicrmw operand must be an integer");
6130 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6131 if (Size < 8 || (Size & (Size - 1)))
6132 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6133 " integer");
6134
6135 AtomicRMWInst *RMWI =
6136 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6137 RMWI->setVolatile(isVolatile);
6138 Inst = RMWI;
6139 return AteExtraComma ? InstExtraComma : InstNormal;
6140}
6141
Eli Friedmanfee02c62011-07-25 23:16:38 +00006142/// ParseFence
6143/// ::= 'fence' 'singlethread'? AtomicOrdering
6144int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006145 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006146 SynchronizationScope Scope = CrossThread;
6147 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6148 return true;
6149
JF Bastien800f87a2016-04-06 21:19:33 +00006150 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006151 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006152 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006153 return TokError("fence cannot be monotonic");
6154
6155 Inst = new FenceInst(Context, Ordering, Scope);
6156 return InstNormal;
6157}
6158
Chris Lattnerac161bf2009-01-02 07:01:27 +00006159/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006160/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006161int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006162 Value *Ptr = nullptr;
6163 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006164 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006165
Dan Gohman16cbbe42009-07-29 15:58:36 +00006166 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006167
David Blaikie79e6c742015-02-27 19:29:02 +00006168 Type *Ty = nullptr;
6169 LocTy ExplicitTypeLoc = Lex.getLoc();
6170 if (ParseType(Ty) ||
6171 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6172 ParseTypeAndValue(Ptr, Loc, PFS))
6173 return true;
6174
Eli Benderskyd9806682013-04-22 17:03:42 +00006175 Type *BaseType = Ptr->getType();
6176 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6177 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006178 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006179
David Blaikie8d757942015-03-09 23:08:44 +00006180 if (Ty != BasePointerType->getElementType())
6181 return Error(ExplicitTypeLoc,
6182 "explicit pointee type doesn't match operand's pointee type");
6183
Chris Lattnerac161bf2009-01-02 07:01:27 +00006184 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006185 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006186 // GEP returns a vector of pointers if at least one of parameters is a vector.
6187 // All vector parameters should have the same vector width.
6188 unsigned GEPWidth = BaseType->isVectorTy() ?
6189 BaseType->getVectorNumElements() : 0;
6190
Chris Lattner3822f632009-01-02 08:05:26 +00006191 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006192 if (Lex.getKind() == lltok::MetadataVar) {
6193 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006194 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006195 }
Chris Lattner3822f632009-01-02 08:05:26 +00006196 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006197 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006198 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006199
Nadav Rotem3924cb02011-12-05 06:29:09 +00006200 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006201 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6202 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006203 return Error(EltLoc,
6204 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006205 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006206 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006207 Indices.push_back(Val);
6208 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006209
Craig Toppere3dcce92015-08-01 22:20:21 +00006210 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006211 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006212 return Error(Loc, "base element of getelementptr must be sized");
6213
David Blaikied33bad32015-04-17 22:32:13 +00006214 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006215 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006216 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006217 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006218 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006219 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006220}
6221
6222/// ParseExtractValue
6223/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006224int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006225 Value *Val; LocTy Loc;
6226 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006227 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006228 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006229 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006230 return true;
6231
Chris Lattner392be582010-02-12 20:49:41 +00006232 if (!Val->getType()->isAggregateType())
6233 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006234
Jay Foad57aa6362011-07-13 10:26:04 +00006235 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006236 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006237 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006238 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006239}
6240
6241/// ParseInsertValue
6242/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006243int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006244 Value *Val0, *Val1; LocTy Loc0, Loc1;
6245 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006246 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006247 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6248 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6249 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006250 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006251 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006252
Chris Lattner392be582010-02-12 20:49:41 +00006253 if (!Val0->getType()->isAggregateType())
6254 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006255
David Majnemer30074532015-02-11 07:43:58 +00006256 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6257 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006258 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006259 if (IndexedType != Val1->getType())
6260 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6261 getTypeString(Val1->getType()) + "' instead of '" +
6262 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006263 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006264 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006265}
Nick Lewycky49f89192009-04-04 07:22:01 +00006266
6267//===----------------------------------------------------------------------===//
6268// Embedded metadata.
6269//===----------------------------------------------------------------------===//
6270
6271/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006272/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006273/// Element
6274/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006275bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006276 if (ParseToken(lltok::lbrace, "expected '{' here"))
6277 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006278
Dan Gohman1e0213a2010-07-13 19:33:27 +00006279 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006280 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006281 return false;
6282
Nick Lewycky49f89192009-04-04 07:22:01 +00006283 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006284 // Null is a special case since it is typeless.
6285 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006286 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006287 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006288 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006289
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006290 Metadata *MD;
6291 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006292 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006293 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006294 } while (EatIfPresent(lltok::comma));
6295
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006296 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006297}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006298
6299//===----------------------------------------------------------------------===//
6300// Use-list order directives.
6301//===----------------------------------------------------------------------===//
6302bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6303 SMLoc Loc) {
6304 if (V->use_empty())
6305 return Error(Loc, "value has no uses");
6306
6307 unsigned NumUses = 0;
6308 SmallDenseMap<const Use *, unsigned, 16> Order;
6309 for (const Use &U : V->uses()) {
6310 if (++NumUses > Indexes.size())
6311 break;
6312 Order[&U] = Indexes[NumUses - 1];
6313 }
6314 if (NumUses < 2)
6315 return Error(Loc, "value only has one use");
6316 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6317 return Error(Loc, "wrong number of indexes, expected " +
6318 Twine(std::distance(V->use_begin(), V->use_end())));
6319
6320 V->sortUseList([&](const Use &L, const Use &R) {
6321 return Order.lookup(&L) < Order.lookup(&R);
6322 });
6323 return false;
6324}
6325
6326/// ParseUseListOrderIndexes
6327/// ::= '{' uint32 (',' uint32)+ '}'
6328bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6329 SMLoc Loc = Lex.getLoc();
6330 if (ParseToken(lltok::lbrace, "expected '{' here"))
6331 return true;
6332 if (Lex.getKind() == lltok::rbrace)
6333 return Lex.Error("expected non-empty list of uselistorder indexes");
6334
6335 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6336 // indexes should be distinct numbers in the range [0, size-1], and should
6337 // not be in order.
6338 unsigned Offset = 0;
6339 unsigned Max = 0;
6340 bool IsOrdered = true;
6341 assert(Indexes.empty() && "Expected empty order vector");
6342 do {
6343 unsigned Index;
6344 if (ParseUInt32(Index))
6345 return true;
6346
6347 // Update consistency checks.
6348 Offset += Index - Indexes.size();
6349 Max = std::max(Max, Index);
6350 IsOrdered &= Index == Indexes.size();
6351
6352 Indexes.push_back(Index);
6353 } while (EatIfPresent(lltok::comma));
6354
6355 if (ParseToken(lltok::rbrace, "expected '}' here"))
6356 return true;
6357
6358 if (Indexes.size() < 2)
6359 return Error(Loc, "expected >= 2 uselistorder indexes");
6360 if (Offset != 0 || Max >= Indexes.size())
6361 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6362 if (IsOrdered)
6363 return Error(Loc, "expected uselistorder indexes to change the order");
6364
6365 return false;
6366}
6367
6368/// ParseUseListOrder
6369/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6370bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6371 SMLoc Loc = Lex.getLoc();
6372 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6373 return true;
6374
6375 Value *V;
6376 SmallVector<unsigned, 16> Indexes;
6377 if (ParseTypeAndValue(V, PFS) ||
6378 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6379 ParseUseListOrderIndexes(Indexes))
6380 return true;
6381
6382 return sortUseListOrder(V, Indexes, Loc);
6383}
6384
6385/// ParseUseListOrderBB
6386/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6387bool LLParser::ParseUseListOrderBB() {
6388 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6389 SMLoc Loc = Lex.getLoc();
6390 Lex.Lex();
6391
6392 ValID Fn, Label;
6393 SmallVector<unsigned, 16> Indexes;
6394 if (ParseValID(Fn) ||
6395 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6396 ParseValID(Label) ||
6397 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6398 ParseUseListOrderIndexes(Indexes))
6399 return true;
6400
6401 // Check the function.
6402 GlobalValue *GV;
6403 if (Fn.Kind == ValID::t_GlobalName)
6404 GV = M->getNamedValue(Fn.StrVal);
6405 else if (Fn.Kind == ValID::t_GlobalID)
6406 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6407 else
6408 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6409 if (!GV)
6410 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6411 auto *F = dyn_cast<Function>(GV);
6412 if (!F)
6413 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6414 if (F->isDeclaration())
6415 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6416
6417 // Check the basic block.
6418 if (Label.Kind == ValID::t_LocalID)
6419 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6420 if (Label.Kind != ValID::t_LocalName)
6421 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6422 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6423 if (!V)
6424 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6425 if (!isa<BasicBlock>(V))
6426 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6427
6428 return sortUseListOrder(V, Indexes, Loc);
6429}