blob: e97202dd989835038b669032e77100c7556c85f5 [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"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000023#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000024#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/InlineAsm.h"
27#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000028#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
31#include "llvm/IR/Operator.h"
32#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000033#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000034#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000035#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000036#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000037#include "llvm/Support/raw_ostream.h"
38using namespace llvm;
39
Chris Lattner229907c2011-07-18 04:54:35 +000040static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000041 std::string Result;
42 raw_string_ostream Tmp(Result);
43 Tmp << *T;
44 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000045}
46
Chris Lattner3822f632009-01-02 08:05:26 +000047/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000048bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000049 // Prime the lexer.
50 Lex.Lex();
51
Mehdi Amini50af49f2016-04-02 03:46:17 +000052 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000053 return Error(
54 Lex.getLoc(),
55 "Can't read textual IR with a Context that discards named Values");
56
Chris Lattnerad6f3352009-01-04 20:44:11 +000057 return ParseTopLevelEntities() ||
58 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000059}
60
Alex Lorenz1de2acd2015-08-21 21:32:39 +000061bool LLParser::parseStandaloneConstantValue(Constant *&C,
62 const SlotMapping *Slots) {
63 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000064 Lex.Lex();
65
66 Type *Ty = nullptr;
67 if (ParseType(Ty) || parseConstantValue(Ty, C))
68 return true;
69 if (Lex.getKind() != lltok::Eof)
70 return Error(Lex.getLoc(), "expected end of string");
71 return false;
72}
73
Quentin Colombetdafed5d2016-03-08 00:37:07 +000074bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
75 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000076 restoreParsingState(Slots);
77 Lex.Lex();
78
Quentin Colombetdafed5d2016-03-08 00:37:07 +000079 Read = 0;
80 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000081 Ty = nullptr;
82 if (ParseType(Ty))
83 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000084 SMLoc End = Lex.getLoc();
85 Read = End.getPointer() - Start.getPointer();
86
Quentin Colombet81e72b42016-03-07 22:09:05 +000087 return false;
88}
89
Alex Lorenz1de2acd2015-08-21 21:32:39 +000090void LLParser::restoreParsingState(const SlotMapping *Slots) {
91 if (!Slots)
92 return;
93 NumberedVals = Slots->GlobalValues;
94 NumberedMetadata = Slots->MetadataNodes;
95 for (const auto &I : Slots->NamedTypes)
96 NamedTypes.insert(
97 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
98 for (const auto &I : Slots->Types)
99 NumberedTypes.insert(
100 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
101}
102
Chris Lattnerac161bf2009-01-02 07:01:27 +0000103/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
104/// module.
105bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000106 // Handle any function attribute group forward references.
107 for (std::map<Value*, std::vector<unsigned> >::iterator
108 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
109 I != E; ++I) {
110 Value *V = I->first;
111 std::vector<unsigned> &Vec = I->second;
112 AttrBuilder B;
113
114 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
115 VI != VE; ++VI)
116 B.merge(NumberedAttrBuilders[*VI]);
117
118 if (Function *Fn = dyn_cast<Function>(V)) {
119 AttributeSet AS = Fn->getAttributes();
120 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
121 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
122 AS.getFnAttributes());
123
124 FnAttrs.merge(B);
125
126 // If the alignment was parsed as an attribute, move to the alignment
127 // field.
128 if (FnAttrs.hasAlignmentAttr()) {
129 Fn->setAlignment(FnAttrs.getAlignment());
130 FnAttrs.removeAttribute(Attribute::Alignment);
131 }
132
133 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134 AttributeSet::get(Context,
135 AttributeSet::FunctionIndex,
136 FnAttrs));
137 Fn->setAttributes(AS);
138 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
139 AttributeSet AS = CI->getAttributes();
140 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
141 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
142 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000143 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000144 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
145 AttributeSet::get(Context,
146 AttributeSet::FunctionIndex,
147 FnAttrs));
148 CI->setAttributes(AS);
149 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
150 AttributeSet AS = II->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
152 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
153 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000155 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
156 AttributeSet::get(Context,
157 AttributeSet::FunctionIndex,
158 FnAttrs));
159 II->setAttributes(AS);
160 } else {
161 llvm_unreachable("invalid object with forward attribute group reference");
162 }
163 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000164
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000165 // If there are entries in ForwardRefBlockAddresses at this point, the
166 // function was never defined.
167 if (!ForwardRefBlockAddresses.empty())
168 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
169 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000170
David Majnemer19b51052015-02-11 07:43:56 +0000171 for (const auto &NT : NumberedTypes)
172 if (NT.second.second.isValid())
173 return Error(NT.second.second,
174 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000175
176 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
177 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
178 if (I->second.second.isValid())
179 return Error(I->second.second,
180 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000181
David Majnemerdad0a642014-06-27 18:19:56 +0000182 if (!ForwardRefComdats.empty())
183 return Error(ForwardRefComdats.begin()->second,
184 "use of undefined comdat '$" +
185 ForwardRefComdats.begin()->first + "'");
186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 if (!ForwardRefVals.empty())
188 return Error(ForwardRefVals.begin()->second.second,
189 "use of undefined value '@" + ForwardRefVals.begin()->first +
190 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000191
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 if (!ForwardRefValIDs.empty())
193 return Error(ForwardRefValIDs.begin()->second.second,
194 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000195 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000196
Devang Pateld2541152009-07-08 19:23:54 +0000197 if (!ForwardRefMDNodes.empty())
198 return Error(ForwardRefMDNodes.begin()->second.second,
199 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000200 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000201
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000203 for (auto &N : NumberedMetadata) {
204 if (N.second && !N.second->isResolved())
205 N.second->resolveCycles();
206 }
Devang Pateld2541152009-07-08 19:23:54 +0000207
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000208 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
209 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
210
Chris Lattnerac161bf2009-01-02 07:01:27 +0000211 // Look for intrinsic functions and CallInst that need to be upgraded
212 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000213 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000214
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000215 // Some types could be renamed during loading if several modules are
216 // loaded in the same LLVMContext (LTO scenario). In this case we should
217 // remangle intrinsics names as well.
218 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
219 Function *F = &*FI++;
220 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
221 F->replaceAllUsesWith(Remangled.getValue());
222 F->eraseFromParent();
223 }
224 }
225
Manman Ren8b4306c2013-12-02 21:29:56 +0000226 UpgradeDebugInfo(*M);
227
Manman Renb5d7ff42016-05-25 23:14:48 +0000228 UpgradeModuleFlags(*M);
229
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000230 if (!Slots)
231 return false;
232 // Initialize the slot mapping.
233 // Because by this point we've parsed and validated everything, we can "steal"
234 // the mapping from LLParser as it doesn't need it anymore.
235 Slots->GlobalValues = std::move(NumberedVals);
236 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000237 for (const auto &I : NamedTypes)
238 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
239 for (const auto &I : NumberedTypes)
240 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000241
Chris Lattnerac161bf2009-01-02 07:01:27 +0000242 return false;
243}
244
245//===----------------------------------------------------------------------===//
246// Top-Level Entities
247//===----------------------------------------------------------------------===//
248
249bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000250 while (1) {
251 switch (Lex.getKind()) {
252 default: return TokError("expected top-level entity");
253 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000254 case lltok::kw_declare: if (ParseDeclare()) return true; break;
255 case lltok::kw_define: if (ParseDefine()) return true; break;
256 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
257 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000258 case lltok::kw_source_filename:
259 if (ParseSourceFileName())
260 return true;
261 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000262 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000263 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000264 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000265 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000267 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000268 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000269 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000270 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000271 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
272 case lltok::kw_uselistorder_bb:
273 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000274 }
275 }
276}
277
278
279/// toplevelentity
280/// ::= 'module' 'asm' STRINGCONSTANT
281bool LLParser::ParseModuleAsm() {
282 assert(Lex.getKind() == lltok::kw_module);
283 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000284
285 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000286 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
287 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000288
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000289 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return false;
291}
292
293/// toplevelentity
294/// ::= 'target' 'triple' '=' STRINGCONSTANT
295/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
296bool LLParser::ParseTargetDefinition() {
297 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000298 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299 switch (Lex.Lex()) {
300 default: return TokError("unknown target property");
301 case lltok::kw_triple:
302 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000303 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
304 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000306 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000307 return false;
308 case lltok::kw_datalayout:
309 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000310 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
311 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000313 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 return false;
315 }
316}
317
Bill Wendling706d3d62012-11-28 08:41:48 +0000318/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000319/// ::= 'source_filename' '=' STRINGCONSTANT
320bool LLParser::ParseSourceFileName() {
321 assert(Lex.getKind() == lltok::kw_source_filename);
322 std::string Str;
323 Lex.Lex();
324 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
325 ParseStringConstant(Str))
326 return true;
327 M->setSourceFileName(Str);
328 return false;
329}
330
331/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000332/// ::= 'deplibs' '=' '[' ']'
333/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334/// FIXME: Remove in 4.0. Currently parse, but ignore.
335bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
337 Lex.Lex();
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
340 return true;
341
342 if (EatIfPresent(lltok::rsquare))
343 return false;
344
345 do {
346 std::string Str;
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
349
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
351}
352
Dan Gohman466876b2009-08-12 23:32:33 +0000353/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000354/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000355bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000356 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000358 Lex.Lex(); // eat LocalVarID;
359
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
362 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000363
Craig Topper2617dcc2014-04-15 06:32:26 +0000364 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000365 if (ParseStructDefinition(TypeLoc, "",
366 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000368 if (!isa<StructType>(Result)) {
369 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
370 if (Entry.first)
371 return Error(TypeLoc, "non-struct types may not be recursive");
372 Entry.first = Result;
373 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000375
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376 return false;
377}
378
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380/// toplevelentity
381/// ::= LocalVar '=' 'type' type
382bool LLParser::ParseNamedType() {
383 std::string Name = Lex.getStrVal();
384 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000385 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000386
Chris Lattner3822f632009-01-02 08:05:26 +0000387 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000388 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000389 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000390
Craig Topper2617dcc2014-04-15 06:32:26 +0000391 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000392 if (ParseStructDefinition(NameLoc, Name,
393 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000394
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000395 if (!isa<StructType>(Result)) {
396 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
397 if (Entry.first)
398 return Error(NameLoc, "non-struct types may not be recursive");
399 Entry.first = Result;
400 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000401 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404}
405
406
407/// toplevelentity
408/// ::= 'declare' FunctionHeader
409bool LLParser::ParseDeclare() {
410 assert(Lex.getKind() == lltok::kw_declare);
411 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000412
Peter Collingbourne21521892016-06-21 23:42:48 +0000413 std::vector<std::pair<unsigned, MDNode *>> MDs;
414 while (Lex.getKind() == lltok::MetadataVar) {
415 unsigned MDK;
416 MDNode *N;
417 if (ParseMetadataAttachment(MDK, N))
418 return true;
419 MDs.push_back({MDK, N});
420 }
421
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000423 if (ParseFunctionHeader(F, false))
424 return true;
425 for (auto &MD : MDs)
426 F->addMetadata(MD.first, *MD.second);
427 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000428}
429
430/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000431/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000432bool LLParser::ParseDefine() {
433 assert(Lex.getKind() == lltok::kw_define);
434 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000435
Chris Lattnerac161bf2009-01-02 07:01:27 +0000436 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000437 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000438 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000439 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440}
441
Chris Lattner3822f632009-01-02 08:05:26 +0000442/// ParseGlobalType
443/// ::= 'constant'
444/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445bool LLParser::ParseGlobalType(bool &IsConstant) {
446 if (Lex.getKind() == lltok::kw_constant)
447 IsConstant = true;
448 else if (Lex.getKind() == lltok::kw_global)
449 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000450 else {
451 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000453 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454 Lex.Lex();
455 return false;
456}
457
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000458bool LLParser::ParseOptionalUnnamedAddr(
459 GlobalVariable::UnnamedAddr &UnnamedAddr) {
460 if (EatIfPresent(lltok::kw_unnamed_addr))
461 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
462 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
463 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
464 else
465 UnnamedAddr = GlobalValue::UnnamedAddr::None;
466 return false;
467}
468
Dan Gohman466876b2009-08-12 23:32:33 +0000469/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000470/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000471/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000473/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000474/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000476bool LLParser::ParseUnnamedGlobal() {
477 unsigned VarID = NumberedVals.size();
478 std::string Name;
479 LocTy NameLoc = Lex.getLoc();
480
481 // Handle the GlobalID form.
482 if (Lex.getKind() == lltok::GlobalID) {
483 if (Lex.getUIntVal() != VarID)
484 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000485 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000486 Lex.Lex(); // eat GlobalID;
487
488 if (ParseToken(lltok::equal, "expected '=' after name"))
489 return true;
490 }
491
492 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000493 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000494 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000495 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000496 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000497 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000498 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000499
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000500 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000501 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000502 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000503
504 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
505 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000506}
507
Chris Lattnerac161bf2009-01-02 07:01:27 +0000508/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000509/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000510/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
511/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000512bool LLParser::ParseNamedGlobal() {
513 assert(Lex.getKind() == lltok::GlobalVar);
514 LocTy NameLoc = Lex.getLoc();
515 std::string Name = Lex.getStrVal();
516 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000517
Chris Lattnerac161bf2009-01-02 07:01:27 +0000518 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000519 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000520 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000521 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000522 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000523 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000524 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000527 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000528 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000529 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000530
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000531 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
532 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000533}
534
David Majnemerdad0a642014-06-27 18:19:56 +0000535bool LLParser::parseComdat() {
536 assert(Lex.getKind() == lltok::ComdatVar);
537 std::string Name = Lex.getStrVal();
538 LocTy NameLoc = Lex.getLoc();
539 Lex.Lex();
540
541 if (ParseToken(lltok::equal, "expected '=' here"))
542 return true;
543
544 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
545 return TokError("expected comdat type");
546
547 Comdat::SelectionKind SK;
548 switch (Lex.getKind()) {
549 default:
550 return TokError("unknown selection kind");
551 case lltok::kw_any:
552 SK = Comdat::Any;
553 break;
554 case lltok::kw_exactmatch:
555 SK = Comdat::ExactMatch;
556 break;
557 case lltok::kw_largest:
558 SK = Comdat::Largest;
559 break;
560 case lltok::kw_noduplicates:
561 SK = Comdat::NoDuplicates;
562 break;
563 case lltok::kw_samesize:
564 SK = Comdat::SameSize;
565 break;
566 }
567 Lex.Lex();
568
569 // See if the comdat was forward referenced, if so, use the comdat.
570 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
571 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
572 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
573 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
574
575 Comdat *C;
576 if (I != ComdatSymTab.end())
577 C = &I->second;
578 else
579 C = M->getOrInsertComdat(Name);
580 C->setSelectionKind(SK);
581
582 return false;
583}
584
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000585// MDString:
586// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000587bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000588 std::string Str;
589 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000590 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000591 return false;
592}
593
594// MDNode:
595// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000596bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000597 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000598 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000599 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000600 if (ParseUInt32(MID))
601 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000602
Chris Lattner8eff0152010-04-01 05:14:45 +0000603 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000604 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000605 Result = NumberedMetadata[MID];
606 return false;
607 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000608
Chris Lattner8eff0152010-04-01 05:14:45 +0000609 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000610 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000611 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000612
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000613 Result = FwdRef.first.get();
614 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000616}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000617
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000618/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000619/// !foo = !{ !1, !2 }
620bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000621 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000622 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000623 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000624
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000625 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000626 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000627 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000628 return true;
629
Dan Gohman2637cc12010-07-21 23:38:33 +0000630 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000631 if (Lex.getKind() != lltok::rbrace)
632 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000633 if (ParseToken(lltok::exclaim, "Expected '!' here"))
634 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000635
Craig Topper2617dcc2014-04-15 06:32:26 +0000636 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000637 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000638 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000639 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000640
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000641 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000642}
643
Devang Patel39e64d42009-07-01 19:21:12 +0000644/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000645/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000646bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000647 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000648 Lex.Lex();
649 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000650
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000651 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000652 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000653 ParseToken(lltok::equal, "expected '=' here"))
654 return true;
655
656 // Detect common error, from old metadata syntax.
657 if (Lex.getKind() == lltok::Type)
658 return TokError("unexpected type in metadata definition");
659
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000660 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000661 if (Lex.getKind() == lltok::MetadataVar) {
662 if (ParseSpecializedMDNode(Init, IsDistinct))
663 return true;
664 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
665 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000666 return true;
667
Chris Lattnerfc58af22009-12-30 04:51:58 +0000668 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000669 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000670 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000671 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000672 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000673
Chris Lattnerfc58af22009-12-30 04:51:58 +0000674 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
675 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000676 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000677 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000678 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000679 }
680
Devang Patel39e64d42009-07-01 19:21:12 +0000681 return false;
682}
683
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000684static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
685 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
686 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
687}
688
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000689/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000690/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
691/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000692/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000693///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000694/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000695/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696///
Eric Christopher536f0a92015-05-28 23:07:39 +0000697/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000698///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000699bool LLParser::parseIndirectSymbol(
700 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
701 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
702 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000703 bool IsAlias;
704 if (Lex.getKind() == lltok::kw_alias)
705 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000706 else if (Lex.getKind() == lltok::kw_ifunc)
707 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000708 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000709 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000710 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711
Rafael Espindola78527052013-10-06 15:10:43 +0000712 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
713
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000714 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000715 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000716
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000717 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000718 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000719 "symbol with local linkage must have default visibility");
720
David Blaikie2f408302015-09-11 03:22:04 +0000721 Type *Ty;
722 LocTy ExplicitTypeLoc = Lex.getLoc();
723 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000724 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000725 return true;
726
Rafael Espindola64c1e182014-06-03 02:41:57 +0000727 Constant *Aliasee;
728 LocTy AliaseeLoc = Lex.getLoc();
729 if (Lex.getKind() != lltok::kw_bitcast &&
730 Lex.getKind() != lltok::kw_getelementptr &&
731 Lex.getKind() != lltok::kw_addrspacecast &&
732 Lex.getKind() != lltok::kw_inttoptr) {
733 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000734 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000735 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000736 // The bitcast dest type is not present, it is implied by the dest type.
737 ValID ID;
738 if (ParseValID(ID))
739 return true;
740 if (ID.Kind != ValID::t_Constant)
741 return Error(AliaseeLoc, "invalid aliasee");
742 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000743 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000744
Rafael Espindola64c1e182014-06-03 02:41:57 +0000745 Type *AliaseeType = Aliasee->getType();
746 auto *PTy = dyn_cast<PointerType>(AliaseeType);
747 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000748 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000749 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000751 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000752 return Error(
753 ExplicitTypeLoc,
754 "explicit pointee type doesn't match operand's pointee type");
755
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000756 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
757 return Error(
758 ExplicitTypeLoc,
759 "explicit pointee type should be a function type");
760
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000761 GlobalValue *GVal = nullptr;
762
763 // See if the alias was forward referenced, if so, prepare to replace the
764 // forward reference.
765 if (!Name.empty()) {
766 GVal = M->getNamedValue(Name);
767 if (GVal) {
768 if (!ForwardRefVals.erase(Name))
769 return Error(NameLoc, "redefinition of global '@" + Name + "'");
770 }
771 } else {
772 auto I = ForwardRefValIDs.find(NumberedVals.size());
773 if (I != ForwardRefValIDs.end()) {
774 GVal = I->second.first;
775 ForwardRefValIDs.erase(I);
776 }
777 }
778
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000780 std::unique_ptr<GlobalIndirectSymbol> GA;
781 if (IsAlias)
782 GA.reset(GlobalAlias::create(Ty, AddrSpace,
783 (GlobalValue::LinkageTypes)Linkage, Name,
784 Aliasee, /*Parent*/ nullptr));
785 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000786 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
787 (GlobalValue::LinkageTypes)Linkage, Name,
788 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000789 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000790 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000791 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000792 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000793
Rafael Espindola54fc2982015-06-17 17:53:31 +0000794 if (Name.empty())
795 NumberedVals.push_back(GA.get());
796
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000797 if (GVal) {
798 // Verify that types agree.
799 if (GVal->getType() != GA->getType())
800 return Error(
801 ExplicitTypeLoc,
802 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerac161bf2009-01-02 07:01:27 +0000804 // If they agree, just RAUW the old value with the alias and remove the
805 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000806 GVal->replaceAllUsesWith(GA.get());
807 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Chris Lattnerac161bf2009-01-02 07:01:27 +0000810 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000811 if (IsAlias)
812 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
813 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000814 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000815 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Rafael Espindolaaa273822014-05-09 21:49:17 +0000817 // The module owns this now
818 GA.release();
819
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 return false;
821}
822
823/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000824/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000825/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000826/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000827/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000828/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000829/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000830///
Eric Christopher536f0a92015-05-28 23:07:39 +0000831/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000832/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833///
834bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
835 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000836 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000837 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000838 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000839 if (!isValidVisibilityForLinkage(Visibility, Linkage))
840 return Error(NameLoc,
841 "symbol with local linkage must have default visibility");
842
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000844 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000845 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000847
Craig Topper2617dcc2014-04-15 06:32:26 +0000848 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000849 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000850 ParseOptionalToken(lltok::kw_externally_initialized,
851 IsExternallyInitialized,
852 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000853 ParseGlobalType(IsConstant) ||
854 ParseType(Ty, TyLoc))
855 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000856
Chris Lattnerac161bf2009-01-02 07:01:27 +0000857 // If the linkage is specified and is external, then no initializer is
858 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000859 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000860 if (!HasLinkage ||
861 !GlobalValue::isValidDeclarationLinkage(
862 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000863 if (ParseGlobalValue(Ty, Init))
864 return true;
865 }
866
David Majnemer49b3d9b2015-02-16 08:41:08 +0000867 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000868 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
David Majnemer598bd052014-12-09 05:56:09 +0000870 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000871
872 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000873 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000874 GVal = M->getNamedValue(Name);
875 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000876 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000877 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000878 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000879 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000880 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000881 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000882 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000883 ForwardRefValIDs.erase(I);
884 }
885 }
886
David Majnemer598bd052014-12-09 05:56:09 +0000887 GlobalVariable *GV;
888 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000889 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
890 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000891 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000893 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 return Error(TyLoc,
895 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000896
David Majnemer598bd052014-12-09 05:56:09 +0000897 GV = cast<GlobalVariable>(GVal);
898
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 // Move the forward-reference to the correct spot in the module.
900 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
901 }
902
903 if (Name.empty())
904 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000905
Chris Lattnerac161bf2009-01-02 07:01:27 +0000906 // Set the parsed properties on the global.
907 if (Init)
908 GV->setInitializer(Init);
909 GV->setConstant(IsConstant);
910 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
911 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000912 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000913 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000914 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000915 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000916
Chris Lattnerac161bf2009-01-02 07:01:27 +0000917 // Parse attributes on the global.
918 while (Lex.getKind() == lltok::comma) {
919 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000920
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 if (Lex.getKind() == lltok::kw_section) {
922 Lex.Lex();
923 GV->setSection(Lex.getStrVal());
924 if (ParseToken(lltok::StringConstant, "expected global section string"))
925 return true;
926 } else if (Lex.getKind() == lltok::kw_align) {
927 unsigned Alignment;
928 if (ParseOptionalAlignment(Alignment)) return true;
929 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000930 } else if (Lex.getKind() == lltok::MetadataVar) {
931 if (ParseGlobalObjectMetadataAttachment(*GV))
932 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000933 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000934 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000935 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000936 return true;
937 if (C)
938 GV->setComdat(C);
939 else
940 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000941 }
942 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000943
Chris Lattnerac161bf2009-01-02 07:01:27 +0000944 return false;
945}
946
Bill Wendling63b88192013-02-06 06:52:58 +0000947/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000948/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000949bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000950 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000951 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000952 Lex.Lex();
953
David Majnemerb39e22b2014-12-09 18:33:57 +0000954 if (Lex.getKind() != lltok::AttrGrpID)
955 return TokError("expected attribute group id");
956
Bill Wendling63b88192013-02-06 06:52:58 +0000957 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000958 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000959 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000960 Lex.Lex();
961
962 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000963 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000964 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000965 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000966 ParseToken(lltok::rbrace, "expected end of attribute group"))
967 return true;
968
Bill Wendlingb32b0412013-02-08 06:32:06 +0000969 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000970 return Error(AttrGrpLoc, "attribute group has no attributes");
971
972 return false;
973}
974
Bill Wendling8b0321d2013-02-08 00:52:31 +0000975/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000976/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000977bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
978 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000979 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000980 bool HaveError = false;
981
982 B.clear();
983
Bill Wendling63b88192013-02-06 06:52:58 +0000984 while (true) {
985 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000986 if (Token == lltok::kw_builtin)
987 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000988 switch (Token) {
989 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000991 return Error(Lex.getLoc(), "unterminated attribute group");
992 case lltok::rbrace:
993 // Finished.
994 return false;
995
Bill Wendlingb32b0412013-02-08 06:32:06 +0000996 case lltok::AttrGrpID: {
997 // Allow a function to reference an attribute group:
998 //
999 // define void @foo() #1 { ... }
1000 if (inAttrGrp)
1001 HaveError |=
1002 Error(Lex.getLoc(),
1003 "cannot have an attribute group reference in an attribute group");
1004
1005 unsigned AttrGrpNum = Lex.getUIntVal();
1006 if (inAttrGrp) break;
1007
1008 // Save the reference to the attribute group. We'll fill it in later.
1009 FwdRefAttrGrps.push_back(AttrGrpNum);
1010 break;
1011 }
Bill Wendling63b88192013-02-06 06:52:58 +00001012 // Target-dependent attributes:
1013 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001014 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001015 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001016 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001017 }
1018
1019 // Target-independent attributes:
1020 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001021 // As a hack, we allow function alignment to be initially parsed as an
1022 // attribute on a function declaration/definition or added to an attribute
1023 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001024 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001025 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001026 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001027 if (ParseToken(lltok::equal, "expected '=' here") ||
1028 ParseUInt32(Alignment))
1029 return true;
1030 } else {
1031 if (ParseOptionalAlignment(Alignment))
1032 return true;
1033 }
Bill Wendling63b88192013-02-06 06:52:58 +00001034 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001035 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001036 }
1037 case lltok::kw_alignstack: {
1038 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001039 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001040 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001041 if (ParseToken(lltok::equal, "expected '=' here") ||
1042 ParseUInt32(Alignment))
1043 return true;
1044 } else {
1045 if (ParseOptionalStackAlignment(Alignment))
1046 return true;
1047 }
Bill Wendling63b88192013-02-06 06:52:58 +00001048 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001049 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001050 }
George Burgess IV278199f2016-04-12 01:05:35 +00001051 case lltok::kw_allocsize: {
1052 unsigned ElemSizeArg;
1053 Optional<unsigned> NumElemsArg;
1054 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1055 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1056 return true;
1057 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1058 continue;
1059 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001060 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1061 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1062 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1063 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1064 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001065 case lltok::kw_inaccessiblememonly:
1066 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1067 case lltok::kw_inaccessiblemem_or_argmemonly:
1068 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001069 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1070 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1071 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1072 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1073 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1074 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1075 case lltok::kw_noimplicitfloat:
1076 B.addAttribute(Attribute::NoImplicitFloat); break;
1077 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1078 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1079 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1080 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001081 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001082 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1083 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1084 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1085 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1086 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1087 case lltok::kw_returns_twice:
1088 B.addAttribute(Attribute::ReturnsTwice); break;
1089 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1090 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1091 case lltok::kw_sspstrong:
1092 B.addAttribute(Attribute::StackProtectStrong); break;
1093 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1094 case lltok::kw_sanitize_address:
1095 B.addAttribute(Attribute::SanitizeAddress); break;
1096 case lltok::kw_sanitize_thread:
1097 B.addAttribute(Attribute::SanitizeThread); break;
1098 case lltok::kw_sanitize_memory:
1099 B.addAttribute(Attribute::SanitizeMemory); break;
1100 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001101 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001102
1103 // Error handling.
1104 case lltok::kw_inreg:
1105 case lltok::kw_signext:
1106 case lltok::kw_zeroext:
1107 HaveError |=
1108 Error(Lex.getLoc(),
1109 "invalid use of attribute on a function");
1110 break;
1111 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001112 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001113 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001114 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001115 case lltok::kw_nest:
1116 case lltok::kw_noalias:
1117 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001118 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001119 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001120 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001121 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001122 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001123 HaveError |=
1124 Error(Lex.getLoc(),
1125 "invalid use of parameter-only attribute on a function");
1126 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001127 }
1128
1129 Lex.Lex();
1130 }
1131}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001132
1133//===----------------------------------------------------------------------===//
1134// GlobalValue Reference/Resolution Routines.
1135//===----------------------------------------------------------------------===//
1136
Karl Schimpf77729782015-09-03 18:06:44 +00001137static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1138 const std::string &Name) {
1139 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1140 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1141 else
1142 return new GlobalVariable(*M, PTy->getElementType(), false,
1143 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1144 nullptr, GlobalVariable::NotThreadLocal,
1145 PTy->getAddressSpace());
1146}
1147
Chris Lattnerac161bf2009-01-02 07:01:27 +00001148/// GetGlobalVal - Get a value with the specified name or ID, creating a
1149/// forward reference record if needed. This can return null if the value
1150/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001151GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001153 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001154 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001155 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001156 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001157 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001158
Chris Lattnerac161bf2009-01-02 07:01:27 +00001159 // Look this name up in the normal function symbol table.
1160 GlobalValue *Val =
1161 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001162
Chris Lattnerac161bf2009-01-02 07:01:27 +00001163 // If this is a forward reference for the value, see if we already created a
1164 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001165 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001166 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 if (I != ForwardRefVals.end())
1168 Val = I->second.first;
1169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001170
Chris Lattnerac161bf2009-01-02 07:01:27 +00001171 // If we have the value in the symbol table or fwd-ref table, return it.
1172 if (Val) {
1173 if (Val->getType() == Ty) return Val;
1174 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001175 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001176 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001177 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001178
Chris Lattnerac161bf2009-01-02 07:01:27 +00001179 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001180 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1182 return FwdVal;
1183}
1184
Chris Lattner229907c2011-07-18 04:54:35 +00001185GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1186 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001187 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001188 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001189 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001191
Craig Topper2617dcc2014-04-15 06:32:26 +00001192 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001193
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194 // If this is a forward reference for the value, see if we already created a
1195 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001196 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001197 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001198 if (I != ForwardRefValIDs.end())
1199 Val = I->second.first;
1200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001201
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202 // If we have the value in the symbol table or fwd-ref table, return it.
1203 if (Val) {
1204 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001205 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001206 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001207 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001209
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001211 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1213 return FwdVal;
1214}
1215
1216
1217//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001218// Comdat Reference/Resolution Routines.
1219//===----------------------------------------------------------------------===//
1220
1221Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1222 // Look this name up in the comdat symbol table.
1223 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1224 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1225 if (I != ComdatSymTab.end())
1226 return &I->second;
1227
1228 // Otherwise, create a new forward reference for this value and remember it.
1229 Comdat *C = M->getOrInsertComdat(Name);
1230 ForwardRefComdats[Name] = Loc;
1231 return C;
1232}
1233
1234
1235//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001236// Helper Routines.
1237//===----------------------------------------------------------------------===//
1238
1239/// ParseToken - If the current token has the specified kind, eat it and return
1240/// success. Otherwise, emit the specified error and return failure.
1241bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1242 if (Lex.getKind() != T)
1243 return TokError(ErrMsg);
1244 Lex.Lex();
1245 return false;
1246}
1247
Chris Lattner3822f632009-01-02 08:05:26 +00001248/// ParseStringConstant
1249/// ::= StringConstant
1250bool LLParser::ParseStringConstant(std::string &Result) {
1251 if (Lex.getKind() != lltok::StringConstant)
1252 return TokError("expected string constant");
1253 Result = Lex.getStrVal();
1254 Lex.Lex();
1255 return false;
1256}
1257
1258/// ParseUInt32
1259/// ::= uint32
1260bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001261 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1262 return TokError("expected integer");
1263 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1264 if (Val64 != unsigned(Val64))
1265 return TokError("expected 32-bit integer (too large)");
1266 Val = Val64;
1267 Lex.Lex();
1268 return false;
1269}
1270
Hal Finkelb0407ba2014-07-18 15:51:28 +00001271/// ParseUInt64
1272/// ::= uint64
1273bool LLParser::ParseUInt64(uint64_t &Val) {
1274 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1275 return TokError("expected integer");
1276 Val = Lex.getAPSIntVal().getLimitedValue();
1277 Lex.Lex();
1278 return false;
1279}
1280
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001281/// ParseTLSModel
1282/// := 'localdynamic'
1283/// := 'initialexec'
1284/// := 'localexec'
1285bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1286 switch (Lex.getKind()) {
1287 default:
1288 return TokError("expected localdynamic, initialexec or localexec");
1289 case lltok::kw_localdynamic:
1290 TLM = GlobalVariable::LocalDynamicTLSModel;
1291 break;
1292 case lltok::kw_initialexec:
1293 TLM = GlobalVariable::InitialExecTLSModel;
1294 break;
1295 case lltok::kw_localexec:
1296 TLM = GlobalVariable::LocalExecTLSModel;
1297 break;
1298 }
1299
1300 Lex.Lex();
1301 return false;
1302}
1303
1304/// ParseOptionalThreadLocal
1305/// := /*empty*/
1306/// := 'thread_local'
1307/// := 'thread_local' '(' tlsmodel ')'
1308bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1309 TLM = GlobalVariable::NotThreadLocal;
1310 if (!EatIfPresent(lltok::kw_thread_local))
1311 return false;
1312
1313 TLM = GlobalVariable::GeneralDynamicTLSModel;
1314 if (Lex.getKind() == lltok::lparen) {
1315 Lex.Lex();
1316 return ParseTLSModel(TLM) ||
1317 ParseToken(lltok::rparen, "expected ')' after thread local model");
1318 }
1319 return false;
1320}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001321
1322/// ParseOptionalAddrSpace
1323/// := /*empty*/
1324/// := 'addrspace' '(' uint32 ')'
1325bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1326 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001327 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001328 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001329 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001330 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001331 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001332}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001333
Artur Pilipenko17376c42015-08-03 14:31:49 +00001334/// ParseStringAttribute
1335/// := StringConstant
1336/// := StringConstant '=' StringConstant
1337bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1338 std::string Attr = Lex.getStrVal();
1339 Lex.Lex();
1340 std::string Val;
1341 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1342 return true;
1343 B.addAttribute(Attr, Val);
1344 return false;
1345}
1346
Bill Wendling34c2eb22012-12-04 23:40:58 +00001347/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1348bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1349 bool HaveError = false;
1350
1351 B.clear();
1352
1353 while (1) {
1354 lltok::Kind Token = Lex.getKind();
1355 switch (Token) {
1356 default: // End of attributes.
1357 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001358 case lltok::StringConstant: {
1359 if (ParseStringAttribute(B))
1360 return true;
1361 continue;
1362 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001363 case lltok::kw_align: {
1364 unsigned Alignment;
1365 if (ParseOptionalAlignment(Alignment))
1366 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001367 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001368 continue;
1369 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001370 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001371 case lltok::kw_dereferenceable: {
1372 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001373 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001374 return true;
1375 B.addDereferenceableAttr(Bytes);
1376 continue;
1377 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001378 case lltok::kw_dereferenceable_or_null: {
1379 uint64_t Bytes;
1380 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1381 return true;
1382 B.addDereferenceableOrNullAttr(Bytes);
1383 continue;
1384 }
Reid Klecknera534a382013-12-19 02:14:12 +00001385 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001386 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1387 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1388 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1389 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001390 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001391 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1392 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001393 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001394 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1395 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001396 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001397 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001398 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001399 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001400
Stephen Lin7577ed52013-04-20 13:16:13 +00001401 case lltok::kw_alignstack:
1402 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001403 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001404 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001405 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001406 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001407 case lltok::kw_minsize:
1408 case lltok::kw_naked:
1409 case lltok::kw_nobuiltin:
1410 case lltok::kw_noduplicate:
1411 case lltok::kw_noimplicitfloat:
1412 case lltok::kw_noinline:
1413 case lltok::kw_nonlazybind:
1414 case lltok::kw_noredzone:
1415 case lltok::kw_noreturn:
1416 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001417 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001418 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001419 case lltok::kw_returns_twice:
1420 case lltok::kw_sanitize_address:
1421 case lltok::kw_sanitize_memory:
1422 case lltok::kw_sanitize_thread:
1423 case lltok::kw_ssp:
1424 case lltok::kw_sspreq:
1425 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001426 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001427 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001428 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1429 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001430 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001431
Bill Wendling34c2eb22012-12-04 23:40:58 +00001432 Lex.Lex();
1433 }
1434}
1435
1436/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1437bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1438 bool HaveError = false;
1439
1440 B.clear();
1441
1442 while (1) {
1443 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001444 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001445 default: // End of attributes.
1446 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001447 case lltok::StringConstant: {
1448 if (ParseStringAttribute(B))
1449 return true;
1450 continue;
1451 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001452 case lltok::kw_dereferenceable: {
1453 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001454 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001455 return true;
1456 B.addDereferenceableAttr(Bytes);
1457 continue;
1458 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001459 case lltok::kw_dereferenceable_or_null: {
1460 uint64_t Bytes;
1461 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1462 return true;
1463 B.addDereferenceableOrNullAttr(Bytes);
1464 continue;
1465 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001466 case lltok::kw_align: {
1467 unsigned Alignment;
1468 if (ParseOptionalAlignment(Alignment))
1469 return true;
1470 B.addAlignmentAttr(Alignment);
1471 continue;
1472 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001473 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1474 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001475 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001476 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1477 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001478
Bill Wendling34c2eb22012-12-04 23:40:58 +00001479 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001480 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001481 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001482 case lltok::kw_nest:
1483 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001484 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001485 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001486 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001487 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001488 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001489 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001490
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001491 case lltok::kw_alignstack:
1492 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001493 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001494 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001495 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001496 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001497 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001498 case lltok::kw_minsize:
1499 case lltok::kw_naked:
1500 case lltok::kw_nobuiltin:
1501 case lltok::kw_noduplicate:
1502 case lltok::kw_noimplicitfloat:
1503 case lltok::kw_noinline:
1504 case lltok::kw_nonlazybind:
1505 case lltok::kw_noredzone:
1506 case lltok::kw_noreturn:
1507 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001508 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001509 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001510 case lltok::kw_returns_twice:
1511 case lltok::kw_sanitize_address:
1512 case lltok::kw_sanitize_memory:
1513 case lltok::kw_sanitize_thread:
1514 case lltok::kw_ssp:
1515 case lltok::kw_sspreq:
1516 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001517 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001518 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001519 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001520 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001521
1522 case lltok::kw_readnone:
1523 case lltok::kw_readonly:
1524 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001525 }
1526
Chris Lattnerac161bf2009-01-02 07:01:27 +00001527 Lex.Lex();
1528 }
1529}
1530
Rafael Espindolac6269912016-05-10 17:16:45 +00001531static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1532 HasLinkage = true;
1533 switch (Kind) {
1534 default:
1535 HasLinkage = false;
1536 return GlobalValue::ExternalLinkage;
1537 case lltok::kw_private:
1538 return GlobalValue::PrivateLinkage;
1539 case lltok::kw_internal:
1540 return GlobalValue::InternalLinkage;
1541 case lltok::kw_weak:
1542 return GlobalValue::WeakAnyLinkage;
1543 case lltok::kw_weak_odr:
1544 return GlobalValue::WeakODRLinkage;
1545 case lltok::kw_linkonce:
1546 return GlobalValue::LinkOnceAnyLinkage;
1547 case lltok::kw_linkonce_odr:
1548 return GlobalValue::LinkOnceODRLinkage;
1549 case lltok::kw_available_externally:
1550 return GlobalValue::AvailableExternallyLinkage;
1551 case lltok::kw_appending:
1552 return GlobalValue::AppendingLinkage;
1553 case lltok::kw_common:
1554 return GlobalValue::CommonLinkage;
1555 case lltok::kw_extern_weak:
1556 return GlobalValue::ExternalWeakLinkage;
1557 case lltok::kw_external:
1558 return GlobalValue::ExternalLinkage;
1559 }
1560}
1561
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562/// ParseOptionalLinkage
1563/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001564/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001565/// ::= 'internal'
1566/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001567/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001568/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001569/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001570/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001571/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001572/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573/// ::= 'extern_weak'
1574/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001575bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1576 unsigned &Visibility,
1577 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001578 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1579 if (HasLinkage)
1580 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001581 ParseOptionalVisibility(Visibility);
1582 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001583 return false;
1584}
1585
1586/// ParseOptionalVisibility
1587/// ::= /*empty*/
1588/// ::= 'default'
1589/// ::= 'hidden'
1590/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001591///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001592void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001593 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001594 default:
1595 Res = GlobalValue::DefaultVisibility;
1596 return;
1597 case lltok::kw_default:
1598 Res = GlobalValue::DefaultVisibility;
1599 break;
1600 case lltok::kw_hidden:
1601 Res = GlobalValue::HiddenVisibility;
1602 break;
1603 case lltok::kw_protected:
1604 Res = GlobalValue::ProtectedVisibility;
1605 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606 }
1607 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001608}
1609
Nico Rieck7157bb72014-01-14 15:22:47 +00001610/// ParseOptionalDLLStorageClass
1611/// ::= /*empty*/
1612/// ::= 'dllimport'
1613/// ::= 'dllexport'
1614///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001615void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001616 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001617 default:
1618 Res = GlobalValue::DefaultStorageClass;
1619 return;
1620 case lltok::kw_dllimport:
1621 Res = GlobalValue::DLLImportStorageClass;
1622 break;
1623 case lltok::kw_dllexport:
1624 Res = GlobalValue::DLLExportStorageClass;
1625 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001626 }
1627 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001628}
1629
Chris Lattnerac161bf2009-01-02 07:01:27 +00001630/// ParseOptionalCallingConv
1631/// ::= /*empty*/
1632/// ::= 'ccc'
1633/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001634/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001635/// ::= 'coldcc'
1636/// ::= 'x86_stdcallcc'
1637/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001638/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001639/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001640/// ::= 'arm_apcscc'
1641/// ::= 'arm_aapcscc'
1642/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001643/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001644/// ::= 'avr_intrcc'
1645/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001646/// ::= 'ptx_kernel'
1647/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001648/// ::= 'spir_func'
1649/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001650/// ::= 'x86_64_sysvcc'
1651/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001652/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001653/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001654/// ::= 'preserve_mostcc'
1655/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001656/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001657/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001658/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001659/// ::= 'hhvmcc'
1660/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001661/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001662/// ::= 'amdgpu_vs'
1663/// ::= 'amdgpu_tcs'
1664/// ::= 'amdgpu_tes'
1665/// ::= 'amdgpu_gs'
1666/// ::= 'amdgpu_ps'
1667/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001668/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001669/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001670///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001671bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001672 switch (Lex.getKind()) {
1673 default: CC = CallingConv::C; return false;
1674 case lltok::kw_ccc: CC = CallingConv::C; break;
1675 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1676 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1677 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1678 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001679 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001680 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001681 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1682 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1683 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001684 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001685 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1686 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001687 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1688 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001689 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1690 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001691 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001692 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1693 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001694 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001695 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001696 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1697 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001698 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001699 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001700 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001701 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1702 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001703 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001704 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1705 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1706 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1707 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001708 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001709 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001710 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001711 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001712 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001714
Chris Lattnerac161bf2009-01-02 07:01:27 +00001715 Lex.Lex();
1716 return false;
1717}
1718
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001719/// ParseMetadataAttachment
1720/// ::= !dbg !42
1721bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1722 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1723
1724 std::string Name = Lex.getStrVal();
1725 Kind = M->getMDKindID(Name);
1726 Lex.Lex();
1727
1728 return ParseMDNode(MD);
1729}
1730
Chris Lattner5c427632009-12-30 05:31:19 +00001731/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001732/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001733bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001734 do {
1735 if (Lex.getKind() != lltok::MetadataVar)
1736 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001737
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001738 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001739 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001740 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001741 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001742
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001743 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001744 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001745 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001746
Chris Lattner596760d2009-12-29 21:25:40 +00001747 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001748 } while (EatIfPresent(lltok::comma));
1749 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001750}
1751
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001752/// ParseGlobalObjectMetadataAttachment
1753/// ::= !dbg !57
1754bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1755 unsigned MDK;
1756 MDNode *N;
1757 if (ParseMetadataAttachment(MDK, N))
1758 return true;
1759
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001760 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001761 return false;
1762}
1763
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001764/// ParseOptionalFunctionMetadata
1765/// ::= (!dbg !57)*
1766bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001767 while (Lex.getKind() == lltok::MetadataVar)
1768 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001769 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001770 return false;
1771}
1772
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773/// ParseOptionalAlignment
1774/// ::= /* empty */
1775/// ::= 'align' 4
1776bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1777 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001778 if (!EatIfPresent(lltok::kw_align))
1779 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001780 LocTy AlignLoc = Lex.getLoc();
1781 if (ParseUInt32(Alignment)) return true;
1782 if (!isPowerOf2_32(Alignment))
1783 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001784 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001785 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001786 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787}
1788
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001789/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001790/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001791/// ::= AttrKind '(' 4 ')'
1792///
1793/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1794bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1795 uint64_t &Bytes) {
1796 assert((AttrKind == lltok::kw_dereferenceable ||
1797 AttrKind == lltok::kw_dereferenceable_or_null) &&
1798 "contract!");
1799
Hal Finkelb0407ba2014-07-18 15:51:28 +00001800 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001801 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001802 return false;
1803 LocTy ParenLoc = Lex.getLoc();
1804 if (!EatIfPresent(lltok::lparen))
1805 return Error(ParenLoc, "expected '('");
1806 LocTy DerefLoc = Lex.getLoc();
1807 if (ParseUInt64(Bytes)) return true;
1808 ParenLoc = Lex.getLoc();
1809 if (!EatIfPresent(lltok::rparen))
1810 return Error(ParenLoc, "expected ')'");
1811 if (!Bytes)
1812 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1813 return false;
1814}
1815
Chris Lattnerb2f39502009-12-30 05:44:30 +00001816/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001817/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001818/// ::= ',' align 4
1819///
1820/// This returns with AteExtraComma set to true if it ate an excess comma at the
1821/// end.
1822bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1823 bool &AteExtraComma) {
1824 AteExtraComma = false;
1825 while (EatIfPresent(lltok::comma)) {
1826 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001827 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001828 AteExtraComma = true;
1829 return false;
1830 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001831
Chris Lattner95b0ff42010-04-23 00:50:50 +00001832 if (Lex.getKind() != lltok::kw_align)
1833 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001834
Chris Lattner95b0ff42010-04-23 00:50:50 +00001835 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001836 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001837
Devang Patelea8a4b92009-09-17 23:04:48 +00001838 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839}
1840
George Burgess IV278199f2016-04-12 01:05:35 +00001841bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1842 Optional<unsigned> &HowManyArg) {
1843 Lex.Lex();
1844
1845 auto StartParen = Lex.getLoc();
1846 if (!EatIfPresent(lltok::lparen))
1847 return Error(StartParen, "expected '('");
1848
1849 if (ParseUInt32(BaseSizeArg))
1850 return true;
1851
1852 if (EatIfPresent(lltok::comma)) {
1853 auto HowManyAt = Lex.getLoc();
1854 unsigned HowMany;
1855 if (ParseUInt32(HowMany))
1856 return true;
1857 if (HowMany == BaseSizeArg)
1858 return Error(HowManyAt,
1859 "'allocsize' indices can't refer to the same parameter");
1860 HowManyArg = HowMany;
1861 } else
1862 HowManyArg = None;
1863
1864 auto EndParen = Lex.getLoc();
1865 if (!EatIfPresent(lltok::rparen))
1866 return Error(EndParen, "expected ')'");
1867 return false;
1868}
1869
Eli Friedmanfee02c62011-07-25 23:16:38 +00001870/// ParseScopeAndOrdering
1871/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1872/// else: ::=
1873///
1874/// This sets Scope and Ordering to the parsed values.
1875bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1876 AtomicOrdering &Ordering) {
1877 if (!isAtomic)
1878 return false;
1879
1880 Scope = CrossThread;
1881 if (EatIfPresent(lltok::kw_singlethread))
1882 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001883
1884 return ParseOrdering(Ordering);
1885}
1886
1887/// ParseOrdering
1888/// ::= AtomicOrdering
1889///
1890/// This sets Ordering to the parsed value.
1891bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001892 switch (Lex.getKind()) {
1893 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001894 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1895 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1896 // Not specified yet:
1897 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1898 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1899 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1900 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1901 case lltok::kw_seq_cst:
1902 Ordering = AtomicOrdering::SequentiallyConsistent;
1903 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001904 }
1905 Lex.Lex();
1906 return false;
1907}
1908
Charles Davisbe5557e2010-02-12 00:31:15 +00001909/// ParseOptionalStackAlignment
1910/// ::= /* empty */
1911/// ::= 'alignstack' '(' 4 ')'
1912bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1913 Alignment = 0;
1914 if (!EatIfPresent(lltok::kw_alignstack))
1915 return false;
1916 LocTy ParenLoc = Lex.getLoc();
1917 if (!EatIfPresent(lltok::lparen))
1918 return Error(ParenLoc, "expected '('");
1919 LocTy AlignLoc = Lex.getLoc();
1920 if (ParseUInt32(Alignment)) return true;
1921 ParenLoc = Lex.getLoc();
1922 if (!EatIfPresent(lltok::rparen))
1923 return Error(ParenLoc, "expected ')'");
1924 if (!isPowerOf2_32(Alignment))
1925 return Error(AlignLoc, "stack alignment is not a power of two");
1926 return false;
1927}
Devang Patelea8a4b92009-09-17 23:04:48 +00001928
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001929/// ParseIndexList - This parses the index list for an insert/extractvalue
1930/// instruction. This sets AteExtraComma in the case where we eat an extra
1931/// comma at the end of the line and find that it is followed by metadata.
1932/// Clients that don't allow metadata can call the version of this function that
1933/// only takes one argument.
1934///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001935/// ParseIndexList
1936/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001937///
1938bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1939 bool &AteExtraComma) {
1940 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001941
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 if (Lex.getKind() != lltok::comma)
1943 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944
Chris Lattner3822f632009-01-02 08:05:26 +00001945 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001946 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001947 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001948 AteExtraComma = true;
1949 return false;
1950 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001951 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001952 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001953 Indices.push_back(Idx);
1954 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 return false;
1957}
1958
1959//===----------------------------------------------------------------------===//
1960// Type Parsing.
1961//===----------------------------------------------------------------------===//
1962
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001964bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001965 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001966 switch (Lex.getKind()) {
1967 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001968 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001969 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001970 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001972 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001974 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001975 // Type ::= StructType
1976 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001977 return true;
1978 break;
1979 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981 Lex.Lex(); // eat the lsquare.
1982 if (ParseArrayVectorType(Result, false))
1983 return true;
1984 break;
1985 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001986 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001987 Lex.Lex();
1988 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001990 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001992 } else if (ParseArrayVectorType(Result, true))
1993 return true;
1994 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001995 case lltok::LocalVar: {
1996 // Type ::= %foo
1997 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001998
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 // If the type hasn't been defined yet, create a forward definition and
2000 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002001 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002002 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002004 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 Lex.Lex();
2007 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 case lltok::LocalVarID: {
2011 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002012 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 // If the type hasn't been defined yet, create a forward definition and
2015 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002016 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002017 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002018 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002019 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002020 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002021 Lex.Lex();
2022 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023 }
2024 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002025
2026 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002027 while (1) {
2028 switch (Lex.getKind()) {
2029 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 default:
2031 if (!AllowVoid && Result->isVoidTy())
2032 return Error(TypeLoc, "void type only allowed for function results");
2033 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002034
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002036 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002038 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002039 if (Result->isVoidTy())
2040 return TokError("pointers to void are invalid - use i8* instead");
2041 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002042 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044 Lex.Lex();
2045 break;
2046
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002052 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002054 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055 unsigned AddrSpace;
2056 if (ParseOptionalAddrSpace(AddrSpace) ||
2057 ParseToken(lltok::star, "expected '*' in address space"))
2058 return true;
2059
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 break;
2062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002063
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2065 case lltok::lparen:
2066 if (ParseFunctionType(Result))
2067 return true;
2068 break;
2069 }
2070 }
2071}
2072
2073/// ParseParameterList
2074/// ::= '(' ')'
2075/// ::= '(' Arg (',' Arg)* ')'
2076/// Arg
2077/// ::= Type OptionalAttributes Value OptionalAttributes
2078bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002079 PerFunctionState &PFS, bool IsMustTailCall,
2080 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081 if (ParseToken(lltok::lparen, "expected '(' in call"))
2082 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002083
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002084 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085 while (Lex.getKind() != lltok::rparen) {
2086 // If this isn't the first argument, we need a comma.
2087 if (!ArgList.empty() &&
2088 ParseToken(lltok::comma, "expected ',' in argument list"))
2089 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002090
Reid Kleckner83498642014-08-26 00:33:28 +00002091 // Parse an ellipsis if this is a musttail call in a variadic function.
2092 if (Lex.getKind() == lltok::dotdotdot) {
2093 const char *Msg = "unexpected ellipsis in argument list for ";
2094 if (!IsMustTailCall)
2095 return TokError(Twine(Msg) + "non-musttail call");
2096 if (!InVarArgsFunc)
2097 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2098 Lex.Lex(); // Lex the '...', it is purely for readability.
2099 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2100 }
2101
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 // Parse the argument.
2103 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002104 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002105 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002107 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002108 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002109
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002110 if (ArgTy->isMetadataTy()) {
2111 if (ParseMetadataAsValue(V, PFS))
2112 return true;
2113 } else {
2114 // Otherwise, handle normal operands.
2115 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2116 return true;
2117 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002118 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2119 AttrIndex++,
2120 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 }
2122
Reid Kleckner83498642014-08-26 00:33:28 +00002123 if (IsMustTailCall && InVarArgsFunc)
2124 return TokError("expected '...' at end of argument list for musttail call "
2125 "in varargs function");
2126
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 Lex.Lex(); // Lex the ')'.
2128 return false;
2129}
2130
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002131/// ParseOptionalOperandBundles
2132/// ::= /*empty*/
2133/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2134///
2135/// OperandBundle
2136/// ::= bundle-tag '(' ')'
2137/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2138///
2139/// bundle-tag ::= String Constant
2140bool LLParser::ParseOptionalOperandBundles(
2141 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2142 LocTy BeginLoc = Lex.getLoc();
2143 if (!EatIfPresent(lltok::lsquare))
2144 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002145
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002146 while (Lex.getKind() != lltok::rsquare) {
2147 // If this isn't the first operand bundle, we need a comma.
2148 if (!BundleList.empty() &&
2149 ParseToken(lltok::comma, "expected ',' in input list"))
2150 return true;
2151
2152 std::string Tag;
2153 if (ParseStringConstant(Tag))
2154 return true;
2155
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002156 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2157 return true;
2158
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002159 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002160 while (Lex.getKind() != lltok::rparen) {
2161 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002162 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002163 ParseToken(lltok::comma, "expected ',' in input list"))
2164 return true;
2165
2166 Type *Ty = nullptr;
2167 Value *Input = nullptr;
2168 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2169 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002170 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002171 }
2172
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002173 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2174
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002175 Lex.Lex(); // Lex the ')'.
2176 }
2177
2178 if (BundleList.empty())
2179 return Error(BeginLoc, "operand bundle set must not be empty");
2180
2181 Lex.Lex(); // Lex the ']'.
2182 return false;
2183}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184
Chris Lattner2ed06b42009-01-05 18:34:07 +00002185/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002186/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187/// ::= '(' ArgTypeListI ')'
2188/// ArgTypeListI
2189/// ::= /*empty*/
2190/// ::= '...'
2191/// ::= ArgTypeList ',' '...'
2192/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002193///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002194bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2195 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 isVarArg = false;
2197 assert(Lex.getKind() == lltok::lparen);
2198 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002199
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200 if (Lex.getKind() == lltok::rparen) {
2201 // empty
2202 } else if (Lex.getKind() == lltok::dotdotdot) {
2203 isVarArg = true;
2204 Lex.Lex();
2205 } else {
2206 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002207 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002208 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002211 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002212 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002213
Chris Lattnerfdd87902009-10-05 05:54:46 +00002214 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002215 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerdef19492011-06-17 06:36:20 +00002217 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218 Name = Lex.getStrVal();
2219 Lex.Lex();
2220 }
Chris Lattner3822f632009-01-02 08:05:26 +00002221
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002222 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002223 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002225 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002226 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2227 AttrIndex++, Attrs),
2228 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002229
Chris Lattner3822f632009-01-02 08:05:26 +00002230 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002232 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 break;
2235 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 // Otherwise must be an argument type.
2238 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002239 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002240
Chris Lattnerfdd87902009-10-05 05:54:46 +00002241 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002242 return Error(TypeLoc, "argument can not have void type");
2243
Chris Lattnerdef19492011-06-17 06:36:20 +00002244 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 Name = Lex.getStrVal();
2246 Lex.Lex();
2247 } else {
2248 Name = "";
2249 }
Chris Lattner3822f632009-01-02 08:05:26 +00002250
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002251 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002252 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002254 ArgList.emplace_back(
2255 TypeLoc, ArgTy,
2256 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2257 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 }
2259 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002260
Chris Lattner3822f632009-01-02 08:05:26 +00002261 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002263
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264/// ParseFunctionType
2265/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002266bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 assert(Lex.getKind() == lltok::lparen);
2268
Chris Lattnerce473c72009-01-05 08:04:33 +00002269 if (!FunctionType::isValidReturnType(Result))
2270 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002271
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002272 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002274 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002276
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277 // Reject names on the arguments lists.
2278 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2279 if (!ArgList[i].Name.empty())
2280 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002281 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002282 return Error(ArgList[i].Loc,
2283 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002285
Jay Foadb804a2b2011-07-12 14:06:48 +00002286 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002287 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002288 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002289
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002290 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 return false;
2292}
2293
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002294/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2295/// other structs.
2296bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2297 SmallVector<Type*, 8> Elts;
2298 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002299
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 Result = StructType::get(Context, Elts, Packed);
2301 return false;
2302}
2303
2304/// ParseStructDefinition - Parse a struct in a 'type' definition.
2305bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2306 std::pair<Type*, LocTy> &Entry,
2307 Type *&ResultTy) {
2308 // If the type was already defined, diagnose the redefinition.
2309 if (Entry.first && !Entry.second.isValid())
2310 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002312 // If we have opaque, just return without filling in the definition for the
2313 // struct. This counts as a definition as far as the .ll file goes.
2314 if (EatIfPresent(lltok::kw_opaque)) {
2315 // This type is being defined, so clear the location to indicate this.
2316 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002317
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002318 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002319 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002320 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 ResultTy = Entry.first;
2322 return false;
2323 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002325 // If the type starts with '<', then it is either a packed struct or a vector.
2326 bool isPacked = EatIfPresent(lltok::less);
2327
2328 // If we don't have a struct, then we have a random type alias, which we
2329 // accept for compatibility with old files. These types are not allowed to be
2330 // forward referenced and not allowed to be recursive.
2331 if (Lex.getKind() != lltok::lbrace) {
2332 if (Entry.first)
2333 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002334
Craig Topper2617dcc2014-04-15 06:32:26 +00002335 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002336 if (isPacked)
2337 return ParseArrayVectorType(ResultTy, true);
2338 return ParseType(ResultTy);
2339 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 // This type is being defined, so clear the location to indicate this.
2342 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002343
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002344 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002345 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002346 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002348 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002349
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002350 SmallVector<Type*, 8> Body;
2351 if (ParseStructBody(Body) ||
2352 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2353 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002354
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002355 STy->setBody(Body, isPacked);
2356 ResultTy = STy;
2357 return false;
2358}
2359
2360
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002362/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002363/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002364/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002365/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002366/// ::= '<' '{' Type (',' Type)* '}' '>'
2367bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368 assert(Lex.getKind() == lltok::lbrace);
2369 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002370
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002371 // Handle the empty struct.
2372 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374
Chris Lattnerf880ca22009-03-09 04:49:14 +00002375 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002376 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002377 if (ParseType(Ty)) return true;
2378 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002379
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002380 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002381 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002382
Chris Lattner3822f632009-01-02 08:05:26 +00002383 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002384 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002387 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002388 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002389
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002390 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002391 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002393 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394}
2395
2396/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2397/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002398/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399/// ::= '[' APSINTVAL 'x' Types ']'
2400/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002401bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2403 Lex.getAPSIntVal().getBitWidth() > 64)
2404 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002405
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406 LocTy SizeLoc = Lex.getLoc();
2407 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002408 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002409
Chris Lattner3822f632009-01-02 08:05:26 +00002410 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2411 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412
2413 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002414 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002415 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002416
Chris Lattner3822f632009-01-02 08:05:26 +00002417 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2418 "expected end of sequential type"))
2419 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002420
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002422 if (Size == 0)
2423 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424 if ((unsigned)Size != Size)
2425 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002426 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002427 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002428 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002430 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002432 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433 }
2434 return false;
2435}
2436
2437//===----------------------------------------------------------------------===//
2438// Function Semantic Analysis.
2439//===----------------------------------------------------------------------===//
2440
Chris Lattner3432c622009-10-28 03:39:23 +00002441LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2442 int functionNumber)
2443 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444
2445 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002446 for (Argument &A : F.args())
2447 if (!A.hasName())
2448 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449}
2450
2451LLParser::PerFunctionState::~PerFunctionState() {
2452 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453
David Blaikie9ebdc692015-09-21 21:07:50 +00002454 for (const auto &P : ForwardRefVals) {
2455 if (isa<BasicBlock>(P.second.first))
2456 continue;
2457 P.second.first->replaceAllUsesWith(
2458 UndefValue::get(P.second.first->getType()));
2459 delete P.second.first;
2460 }
2461
2462 for (const auto &P : ForwardRefValIDs) {
2463 if (isa<BasicBlock>(P.second.first))
2464 continue;
2465 P.second.first->replaceAllUsesWith(
2466 UndefValue::get(P.second.first->getType()));
2467 delete P.second.first;
2468 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469}
2470
Chris Lattner3432c622009-10-28 03:39:23 +00002471bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 if (!ForwardRefVals.empty())
2473 return P.Error(ForwardRefVals.begin()->second.second,
2474 "use of undefined value '%" + ForwardRefVals.begin()->first +
2475 "'");
2476 if (!ForwardRefValIDs.empty())
2477 return P.Error(ForwardRefValIDs.begin()->second.second,
2478 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002479 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480 return false;
2481}
2482
2483
2484/// GetVal - Get a value with the specified name or ID, creating a
2485/// forward reference record if needed. This can return null if the value
2486/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002487Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002488 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 // Look this name up in the normal function symbol table.
2490 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 // If this is a forward reference for the value, see if we already created a
2493 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002494 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002495 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 if (I != ForwardRefVals.end())
2497 Val = I->second.first;
2498 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 // If we have the value in the symbol table or fwd-ref table, return it.
2501 if (Val) {
2502 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002503 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 P.Error(Loc, "'%" + Name + "' is not a basic block");
2505 else
2506 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002507 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002508 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002509 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002510
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002512 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002513 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002514 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002516
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 // Otherwise, create a new forward reference for this value and remember it.
2518 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002519 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002520 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002521 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002522 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002524
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2526 return FwdVal;
2527}
2528
David Majnemer8a1c45d2015-12-12 05:38:55 +00002529Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002530 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002531 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002532
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 // If this is a forward reference for the value, see if we already created a
2534 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002535 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002536 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 if (I != ForwardRefValIDs.end())
2538 Val = I->second.first;
2539 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002540
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 // If we have the value in the symbol table or fwd-ref table, return it.
2542 if (Val) {
2543 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002544 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002545 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002546 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002547 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002548 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002549 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002550 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002551
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002552 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002554 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002556
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 // Otherwise, create a new forward reference for this value and remember it.
2558 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002559 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002560 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002561 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002562 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002564
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2566 return FwdVal;
2567}
2568
2569/// SetInstName - After an instruction is parsed and inserted into its
2570/// basic block, this installs its name.
2571bool LLParser::PerFunctionState::SetInstName(int NameID,
2572 const std::string &NameStr,
2573 LocTy NameLoc, Instruction *Inst) {
2574 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002575 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 if (NameID != -1 || !NameStr.empty())
2577 return P.Error(NameLoc, "instructions returning void cannot have a name");
2578 return false;
2579 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002580
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581 // If this was a numbered instruction, verify that the instruction is the
2582 // expected value and resolve any forward references.
2583 if (NameStr.empty()) {
2584 // If neither a name nor an ID was specified, just use the next ID.
2585 if (NameID == -1)
2586 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002587
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588 if (unsigned(NameID) != NumberedVals.size())
2589 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002590 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002591
David Blaikie9ebdc692015-09-21 21:07:50 +00002592 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002593 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002594 Value *Sentinel = FI->second.first;
2595 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002596 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002597 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002598
2599 Sentinel->replaceAllUsesWith(Inst);
2600 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002601 ForwardRefValIDs.erase(FI);
2602 }
2603
2604 NumberedVals.push_back(Inst);
2605 return false;
2606 }
2607
2608 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002609 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002610 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002611 Value *Sentinel = FI->second.first;
2612 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002613 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002614 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002615
2616 Sentinel->replaceAllUsesWith(Inst);
2617 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002618 ForwardRefVals.erase(FI);
2619 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002620
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 // Set the name on the instruction.
2622 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002623
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002624 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002625 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 NameStr + "'");
2627 return false;
2628}
2629
2630/// GetBB - Get a basic block with the specified name or ID, creating a
2631/// forward reference record if needed.
2632BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2633 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002634 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2635 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002636}
2637
2638BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002639 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2640 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641}
2642
2643/// DefineBB - Define the specified basic block, which is either named or
2644/// unnamed. If there is an error, this returns null otherwise it returns
2645/// the block being defined.
2646BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2647 LocTy Loc) {
2648 BasicBlock *BB;
2649 if (Name.empty())
2650 BB = GetBB(NumberedVals.size(), Loc);
2651 else
2652 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002653 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002654
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 // Move the block to the end of the function. Forward ref'd blocks are
2656 // inserted wherever they happen to be referenced.
2657 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002658
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 // Remove the block from forward ref sets.
2660 if (Name.empty()) {
2661 ForwardRefValIDs.erase(NumberedVals.size());
2662 NumberedVals.push_back(BB);
2663 } else {
2664 // BB forward references are already in the function symbol table.
2665 ForwardRefVals.erase(Name);
2666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002667
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 return BB;
2669}
2670
2671//===----------------------------------------------------------------------===//
2672// Constants.
2673//===----------------------------------------------------------------------===//
2674
2675/// ParseValID - Parse an abstract value that doesn't necessarily have a
2676/// type implied. For example, if we parse "4" we don't know what integer type
2677/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002678/// sanity. PFS is used to convert function-local operands of metadata (since
2679/// metadata operands are not just parsed here but also converted to values).
2680/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002681bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002682 ID.Loc = Lex.getLoc();
2683 switch (Lex.getKind()) {
2684 default: return TokError("expected value token");
2685 case lltok::GlobalID: // @42
2686 ID.UIntVal = Lex.getUIntVal();
2687 ID.Kind = ValID::t_GlobalID;
2688 break;
2689 case lltok::GlobalVar: // @foo
2690 ID.StrVal = Lex.getStrVal();
2691 ID.Kind = ValID::t_GlobalName;
2692 break;
2693 case lltok::LocalVarID: // %42
2694 ID.UIntVal = Lex.getUIntVal();
2695 ID.Kind = ValID::t_LocalID;
2696 break;
2697 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698 ID.StrVal = Lex.getStrVal();
2699 ID.Kind = ValID::t_LocalName;
2700 break;
2701 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002702 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002703 ID.Kind = ValID::t_APSInt;
2704 break;
2705 case lltok::APFloat:
2706 ID.APFloatVal = Lex.getAPFloatVal();
2707 ID.Kind = ValID::t_APFloat;
2708 break;
2709 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002710 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002711 ID.Kind = ValID::t_Constant;
2712 break;
2713 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002714 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 ID.Kind = ValID::t_Constant;
2716 break;
2717 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2718 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2719 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002720 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002721
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 case lltok::lbrace: {
2723 // ValID ::= '{' ConstVector '}'
2724 Lex.Lex();
2725 SmallVector<Constant*, 16> Elts;
2726 if (ParseGlobalValueVector(Elts) ||
2727 ParseToken(lltok::rbrace, "expected end of struct constant"))
2728 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002729
David Blaikieadbda4b2015-08-03 20:08:41 +00002730 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002731 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002732 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2733 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002734 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002735 return false;
2736 }
2737 case lltok::less: {
2738 // ValID ::= '<' ConstVector '>' --> Vector.
2739 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2740 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002741 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 SmallVector<Constant*, 16> Elts;
2744 LocTy FirstEltLoc = Lex.getLoc();
2745 if (ParseGlobalValueVector(Elts) ||
2746 (isPackedStruct &&
2747 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2748 ParseToken(lltok::greater, "expected end of constant"))
2749 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750
Chris Lattnerac161bf2009-01-02 07:01:27 +00002751 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002752 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2753 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2754 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002755 ID.UIntVal = Elts.size();
2756 ID.Kind = ValID::t_PackedConstantStruct;
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.empty())
2761 return Error(ID.Loc, "constant vector must not be empty");
2762
Duncan Sands9dff9be2010-02-15 16:12:20 +00002763 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002764 !Elts[0]->getType()->isFloatingPointTy() &&
2765 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002767 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002768
Chris Lattnerac161bf2009-01-02 07:01:27 +00002769 // Verify that all the vector elements have the same type.
2770 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2771 if (Elts[i]->getType() != Elts[0]->getType())
2772 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002773 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002774 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775
Chris Lattner69229312011-02-15 00:14:00 +00002776 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 ID.Kind = ValID::t_Constant;
2778 return false;
2779 }
2780 case lltok::lsquare: { // Array Constant
2781 Lex.Lex();
2782 SmallVector<Constant*, 16> Elts;
2783 LocTy FirstEltLoc = Lex.getLoc();
2784 if (ParseGlobalValueVector(Elts) ||
2785 ParseToken(lltok::rsquare, "expected end of array constant"))
2786 return true;
2787
2788 // Handle empty element.
2789 if (Elts.empty()) {
2790 // Use undef instead of an array because it's inconvenient to determine
2791 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002792 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 return false;
2794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002795
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002798 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002799
Owen Anderson4056ca92009-07-29 22:17:13 +00002800 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002801
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002803 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 if (Elts[i]->getType() != Elts[0]->getType())
2805 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002806 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002807 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002809
Jay Foad83be3612011-06-22 09:24:39 +00002810 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 ID.Kind = ValID::t_Constant;
2812 return false;
2813 }
2814 case lltok::kw_c: // c "foo"
2815 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002816 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2817 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002818 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2819 ID.Kind = ValID::t_Constant;
2820 return false;
2821
2822 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002823 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2824 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002825 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 Lex.Lex();
2827 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002828 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002829 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002830 ParseStringConstant(ID.StrVal) ||
2831 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 ParseToken(lltok::StringConstant, "expected constraint string"))
2833 return true;
2834 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002835 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002836 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 ID.Kind = ValID::t_InlineAsm;
2838 return false;
2839 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Chris Lattner3432c622009-10-28 03:39:23 +00002841 case lltok::kw_blockaddress: {
2842 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2843 Lex.Lex();
2844
2845 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002846
Chris Lattner3432c622009-10-28 03:39:23 +00002847 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2848 ParseValID(Fn) ||
2849 ParseToken(lltok::comma, "expected comma in block address expression")||
2850 ParseValID(Label) ||
2851 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2852 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002853
Chris Lattner3432c622009-10-28 03:39:23 +00002854 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2855 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002856 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002857 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002858
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002859 // Try to find the function (but skip it if it's forward-referenced).
2860 GlobalValue *GV = nullptr;
2861 if (Fn.Kind == ValID::t_GlobalID) {
2862 if (Fn.UIntVal < NumberedVals.size())
2863 GV = NumberedVals[Fn.UIntVal];
2864 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2865 GV = M->getNamedValue(Fn.StrVal);
2866 }
2867 Function *F = nullptr;
2868 if (GV) {
2869 // Confirm that it's actually a function with a definition.
2870 if (!isa<Function>(GV))
2871 return Error(Fn.Loc, "expected function name in blockaddress");
2872 F = cast<Function>(GV);
2873 if (F->isDeclaration())
2874 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2875 }
2876
2877 if (!F) {
2878 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002879 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002880 ForwardRefBlockAddresses.insert(std::make_pair(
2881 std::move(Fn),
2882 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002883 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2884 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002885 if (!FwdRef)
2886 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2887 GlobalValue::InternalLinkage, nullptr, "");
2888 ID.ConstantVal = FwdRef;
2889 ID.Kind = ValID::t_Constant;
2890 return false;
2891 }
2892
2893 // We found the function; now find the basic block. Don't use PFS, since we
2894 // might be inside a constant expression.
2895 BasicBlock *BB;
2896 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2897 if (Label.Kind == ValID::t_LocalID)
2898 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2899 else
2900 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2901 if (!BB)
2902 return Error(Label.Loc, "referenced value is not a basic block");
2903 } else {
2904 if (Label.Kind == ValID::t_LocalID)
2905 return Error(Label.Loc, "cannot take address of numeric label after "
2906 "the function is defined");
2907 BB = dyn_cast_or_null<BasicBlock>(
2908 F->getValueSymbolTable().lookup(Label.StrVal));
2909 if (!BB)
2910 return Error(Label.Loc, "referenced value is not a basic block");
2911 }
2912
2913 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002914 ID.Kind = ValID::t_Constant;
2915 return false;
2916 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002917
Chris Lattnerac161bf2009-01-02 07:01:27 +00002918 case lltok::kw_trunc:
2919 case lltok::kw_zext:
2920 case lltok::kw_sext:
2921 case lltok::kw_fptrunc:
2922 case lltok::kw_fpext:
2923 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002924 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002925 case lltok::kw_uitofp:
2926 case lltok::kw_sitofp:
2927 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002928 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002930 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002932 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933 Constant *SrcVal;
2934 Lex.Lex();
2935 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2936 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002937 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002938 ParseType(DestTy) ||
2939 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2940 return true;
2941 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2942 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002943 getTypeString(SrcVal->getType()) + "' to '" +
2944 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002945 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002946 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002947 ID.Kind = ValID::t_Constant;
2948 return false;
2949 }
2950 case lltok::kw_extractvalue: {
2951 Lex.Lex();
2952 Constant *Val;
2953 SmallVector<unsigned, 4> Indices;
2954 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2955 ParseGlobalTypeAndValue(Val) ||
2956 ParseIndexList(Indices) ||
2957 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2958 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002959
Chris Lattner392be582010-02-12 20:49:41 +00002960 if (!Val->getType()->isAggregateType())
2961 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002962 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002963 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002964 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002965 ID.Kind = ValID::t_Constant;
2966 return false;
2967 }
2968 case lltok::kw_insertvalue: {
2969 Lex.Lex();
2970 Constant *Val0, *Val1;
2971 SmallVector<unsigned, 4> Indices;
2972 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2973 ParseGlobalTypeAndValue(Val0) ||
2974 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2975 ParseGlobalTypeAndValue(Val1) ||
2976 ParseIndexList(Indices) ||
2977 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2978 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002979 if (!Val0->getType()->isAggregateType())
2980 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002981 Type *IndexedType =
2982 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2983 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002984 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002985 if (IndexedType != Val1->getType())
2986 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2987 getTypeString(Val1->getType()) +
2988 "' instead of '" + getTypeString(IndexedType) +
2989 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002990 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002991 ID.Kind = ValID::t_Constant;
2992 return false;
2993 }
2994 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002995 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 unsigned PredVal, Opc = Lex.getUIntVal();
2997 Constant *Val0, *Val1;
2998 Lex.Lex();
2999 if (ParseCmpPredicate(PredVal, Opc) ||
3000 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3001 ParseGlobalTypeAndValue(Val0) ||
3002 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3003 ParseGlobalTypeAndValue(Val1) ||
3004 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3005 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003006
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 if (Val0->getType() != Val1->getType())
3008 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003009
Chris Lattnerac161bf2009-01-02 07:01:27 +00003010 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003011
Chris Lattnerac161bf2009-01-02 07:01:27 +00003012 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003013 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003014 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003015 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003016 } else {
3017 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003018 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003019 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003020 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003021 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 }
3023 ID.Kind = ValID::t_Constant;
3024 return false;
3025 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003026
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 // Binary Operators.
3028 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003029 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003031 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003033 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003034 case lltok::kw_udiv:
3035 case lltok::kw_sdiv:
3036 case lltok::kw_fdiv:
3037 case lltok::kw_urem:
3038 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003039 case lltok::kw_frem:
3040 case lltok::kw_shl:
3041 case lltok::kw_lshr:
3042 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003043 bool NUW = false;
3044 bool NSW = false;
3045 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 unsigned Opc = Lex.getUIntVal();
3047 Constant *Val0, *Val1;
3048 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003049 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003050 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3051 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003052 if (EatIfPresent(lltok::kw_nuw))
3053 NUW = true;
3054 if (EatIfPresent(lltok::kw_nsw)) {
3055 NSW = true;
3056 if (EatIfPresent(lltok::kw_nuw))
3057 NUW = true;
3058 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003059 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3060 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003061 if (EatIfPresent(lltok::kw_exact))
3062 Exact = true;
3063 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3065 ParseGlobalTypeAndValue(Val0) ||
3066 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3067 ParseGlobalTypeAndValue(Val1) ||
3068 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3069 return true;
3070 if (Val0->getType() != Val1->getType())
3071 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003072 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003073 if (NUW)
3074 return Error(ModifierLoc, "nuw only applies to integer operations");
3075 if (NSW)
3076 return Error(ModifierLoc, "nsw only applies to integer operations");
3077 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003078 // Check that the type is valid for the operator.
3079 switch (Opc) {
3080 case Instruction::Add:
3081 case Instruction::Sub:
3082 case Instruction::Mul:
3083 case Instruction::UDiv:
3084 case Instruction::SDiv:
3085 case Instruction::URem:
3086 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003087 case Instruction::Shl:
3088 case Instruction::AShr:
3089 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003090 if (!Val0->getType()->isIntOrIntVectorTy())
3091 return Error(ID.Loc, "constexpr requires integer operands");
3092 break;
3093 case Instruction::FAdd:
3094 case Instruction::FSub:
3095 case Instruction::FMul:
3096 case Instruction::FDiv:
3097 case Instruction::FRem:
3098 if (!Val0->getType()->isFPOrFPVectorTy())
3099 return Error(ID.Loc, "constexpr requires fp operands");
3100 break;
3101 default: llvm_unreachable("Unknown binary operator!");
3102 }
Dan Gohman1b849082009-09-07 23:54:19 +00003103 unsigned Flags = 0;
3104 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3105 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003106 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003107 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003108 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003109 ID.Kind = ValID::t_Constant;
3110 return false;
3111 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003112
Chris Lattnerac161bf2009-01-02 07:01:27 +00003113 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003114 case lltok::kw_and:
3115 case lltok::kw_or:
3116 case lltok::kw_xor: {
3117 unsigned Opc = Lex.getUIntVal();
3118 Constant *Val0, *Val1;
3119 Lex.Lex();
3120 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3121 ParseGlobalTypeAndValue(Val0) ||
3122 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3123 ParseGlobalTypeAndValue(Val1) ||
3124 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3125 return true;
3126 if (Val0->getType() != Val1->getType())
3127 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003128 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129 return Error(ID.Loc,
3130 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003131 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003132 ID.Kind = ValID::t_Constant;
3133 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003134 }
3135
Chris Lattnerac161bf2009-01-02 07:01:27 +00003136 case lltok::kw_getelementptr:
3137 case lltok::kw_shufflevector:
3138 case lltok::kw_insertelement:
3139 case lltok::kw_extractelement:
3140 case lltok::kw_select: {
3141 unsigned Opc = Lex.getUIntVal();
3142 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003143 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003144 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003145 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003146
Dan Gohman1639c392009-07-27 21:53:46 +00003147 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003148 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003149
3150 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3151 return true;
3152
3153 LocTy ExplicitTypeLoc = Lex.getLoc();
3154 if (Opc == Instruction::GetElementPtr) {
3155 if (ParseType(Ty) ||
3156 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3157 return true;
3158 }
3159
3160 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003161 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3162 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003163
Chris Lattnerac161bf2009-01-02 07:01:27 +00003164 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003165 if (Elts.size() == 0 ||
3166 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003167 return Error(ID.Loc, "base of getelementptr must be a pointer");
3168
3169 Type *BaseType = Elts[0]->getType();
3170 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003171 if (Ty != BasePointerType->getElementType())
3172 return Error(
3173 ExplicitTypeLoc,
3174 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003175
Jay Foaded8db7d2011-07-21 14:31:17 +00003176 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003177 for (Constant *Val : Indices) {
3178 Type *ValTy = Val->getType();
3179 if (!ValTy->getScalarType()->isIntegerTy())
3180 return Error(ID.Loc, "getelementptr index must be an integer");
3181 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3182 return Error(ID.Loc, "getelementptr index type missmatch");
3183 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003184 unsigned ValNumEl = ValTy->getVectorNumElements();
3185 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003186 if (ValNumEl != PtrNumEl)
3187 return Error(
3188 ID.Loc,
3189 "getelementptr vector index has a wrong number of elements");
3190 }
3191 }
3192
Craig Toppere3dcce92015-08-01 22:20:21 +00003193 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003194 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003195 return Error(ID.Loc, "base element of getelementptr must be sized");
3196
David Blaikie4a2e73b2015-04-02 18:55:32 +00003197 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003198 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003199 ID.ConstantVal =
3200 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003201 } else if (Opc == Instruction::Select) {
3202 if (Elts.size() != 3)
3203 return Error(ID.Loc, "expected three operands to select");
3204 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3205 Elts[2]))
3206 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003207 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 } else if (Opc == Instruction::ShuffleVector) {
3209 if (Elts.size() != 3)
3210 return Error(ID.Loc, "expected three operands to shufflevector");
3211 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3212 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003213 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003214 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003215 } else if (Opc == Instruction::ExtractElement) {
3216 if (Elts.size() != 2)
3217 return Error(ID.Loc, "expected two operands to extractelement");
3218 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3219 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003220 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003221 } else {
3222 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3223 if (Elts.size() != 3)
3224 return Error(ID.Loc, "expected three operands to insertelement");
3225 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3226 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003227 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003228 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003229 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003230
Chris Lattnerac161bf2009-01-02 07:01:27 +00003231 ID.Kind = ValID::t_Constant;
3232 return false;
3233 }
3234 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003235
Chris Lattnerac161bf2009-01-02 07:01:27 +00003236 Lex.Lex();
3237 return false;
3238}
3239
3240/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003241bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003242 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003243 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003244 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003245 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003246 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003247 if (V && !(C = dyn_cast<Constant>(V)))
3248 return Error(ID.Loc, "global values must be constants");
3249 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003250}
3251
Victor Hernandez9d75c962010-01-11 22:31:58 +00003252bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003253 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003254 return ParseType(Ty) ||
3255 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003256}
3257
Rafael Espindola83a362c2015-01-06 22:55:16 +00003258bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003259 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003260
3261 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003262 if (!EatIfPresent(lltok::kw_comdat))
3263 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003264
3265 if (EatIfPresent(lltok::lparen)) {
3266 if (Lex.getKind() != lltok::ComdatVar)
3267 return TokError("expected comdat variable");
3268 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3269 Lex.Lex();
3270 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3271 return true;
3272 } else {
3273 if (GlobalName.empty())
3274 return TokError("comdat cannot be unnamed");
3275 C = getComdat(GlobalName, KwLoc);
3276 }
3277
David Majnemerdad0a642014-06-27 18:19:56 +00003278 return false;
3279}
3280
Victor Hernandez9d75c962010-01-11 22:31:58 +00003281/// ParseGlobalValueVector
3282/// ::= /*empty*/
3283/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003284bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003285 // Empty list.
3286 if (Lex.getKind() == lltok::rbrace ||
3287 Lex.getKind() == lltok::rsquare ||
3288 Lex.getKind() == lltok::greater ||
3289 Lex.getKind() == lltok::rparen)
3290 return false;
3291
3292 Constant *C;
3293 if (ParseGlobalTypeAndValue(C)) return true;
3294 Elts.push_back(C);
3295
3296 while (EatIfPresent(lltok::comma)) {
3297 if (ParseGlobalTypeAndValue(C)) return true;
3298 Elts.push_back(C);
3299 }
3300
3301 return false;
3302}
3303
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003304bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003305 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003306 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003307 return true;
3308
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003309 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003310 return false;
3311}
3312
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003313/// MDNode:
3314/// ::= !{ ... }
3315/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003316/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003317bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003318 if (Lex.getKind() == lltok::MetadataVar)
3319 return ParseSpecializedMDNode(N);
3320
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003321 return ParseToken(lltok::exclaim, "expected '!' here") ||
3322 ParseMDNodeTail(N);
3323}
3324
3325bool LLParser::ParseMDNodeTail(MDNode *&N) {
3326 // !{ ... }
3327 if (Lex.getKind() == lltok::lbrace)
3328 return ParseMDTuple(N);
3329
3330 // !42
3331 return ParseMDNodeID(N);
3332}
3333
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003334namespace {
3335
3336/// Structure to represent an optional metadata field.
3337template <class FieldTy> struct MDFieldImpl {
3338 typedef MDFieldImpl ImplTy;
3339 FieldTy Val;
3340 bool Seen;
3341
3342 void assign(FieldTy Val) {
3343 Seen = true;
3344 this->Val = std::move(Val);
3345 }
3346
3347 explicit MDFieldImpl(FieldTy Default)
3348 : Val(std::move(Default)), Seen(false) {}
3349};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003350
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003351struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3352 uint64_t Max;
3353
3354 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3355 : ImplTy(Default), Max(Max) {}
3356};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003357struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003358 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003359};
3360struct ColumnField : public MDUnsignedField {
3361 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3362};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003363struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003364 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003365 DwarfTagField(dwarf::Tag DefaultTag)
3366 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003367};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003368struct DwarfMacinfoTypeField : public MDUnsignedField {
3369 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3370 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3371 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3372};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003373struct DwarfAttEncodingField : public MDUnsignedField {
3374 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3375};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003376struct DwarfVirtualityField : public MDUnsignedField {
3377 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3378};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003379struct DwarfLangField : public MDUnsignedField {
3380 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3381};
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003382struct DwarfCCField : public MDUnsignedField {
3383 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3384};
Adrian Prantlb939a252016-03-31 23:56:58 +00003385struct EmissionKindField : public MDUnsignedField {
3386 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3387};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003388
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003389struct DIFlagField : public MDUnsignedField {
3390 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3391};
3392
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003393struct MDSignedField : public MDFieldImpl<int64_t> {
3394 int64_t Min;
3395 int64_t Max;
3396
3397 MDSignedField(int64_t Default = 0)
3398 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3399 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3400 : ImplTy(Default), Min(Min), Max(Max) {}
3401};
3402
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003403struct MDBoolField : public MDFieldImpl<bool> {
3404 MDBoolField(bool Default = false) : ImplTy(Default) {}
3405};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003406struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003407 bool AllowNull;
3408
3409 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003410};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003411struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3412 MDConstant() : ImplTy(nullptr) {}
3413};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003414struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003415 bool AllowEmpty;
3416 MDStringField(bool AllowEmpty = true)
3417 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003418};
3419struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3420 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3421};
3422
3423} // end namespace
3424
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003425namespace llvm {
3426
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003427template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003428bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003429 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003430 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3431 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003432
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003433 auto &U = Lex.getAPSIntVal();
3434 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003435 return TokError("value for '" + Name + "' too large, limit is " +
3436 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003437 Result.assign(U.getZExtValue());
3438 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003439 Lex.Lex();
3440 return false;
3441}
3442
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003443template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003444bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3445 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3446}
3447template <>
3448bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3449 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3450}
3451
3452template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003453bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3454 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003455 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003456
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003457 if (Lex.getKind() != lltok::DwarfTag)
3458 return TokError("expected DWARF tag");
3459
3460 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3461 if (Tag == dwarf::DW_TAG_invalid)
3462 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003463 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003464
3465 Result.assign(Tag);
3466 Lex.Lex();
3467 return false;
3468}
3469
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003470template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003471bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003472 DwarfMacinfoTypeField &Result) {
3473 if (Lex.getKind() == lltok::APSInt)
3474 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3475
3476 if (Lex.getKind() != lltok::DwarfMacinfo)
3477 return TokError("expected DWARF macinfo type");
3478
3479 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3480 if (Macinfo == dwarf::DW_MACINFO_invalid)
3481 return TokError(
3482 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3483 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3484
3485 Result.assign(Macinfo);
3486 Lex.Lex();
3487 return false;
3488}
3489
3490template <>
3491bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003492 DwarfVirtualityField &Result) {
3493 if (Lex.getKind() == lltok::APSInt)
3494 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3495
3496 if (Lex.getKind() != lltok::DwarfVirtuality)
3497 return TokError("expected DWARF virtuality code");
3498
3499 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003500 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003501 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3502 Lex.getStrVal() + "'");
3503 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3504 Result.assign(Virtuality);
3505 Lex.Lex();
3506 return false;
3507}
3508
3509template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003510bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3511 if (Lex.getKind() == lltok::APSInt)
3512 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3513
3514 if (Lex.getKind() != lltok::DwarfLang)
3515 return TokError("expected DWARF language");
3516
3517 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3518 if (!Lang)
3519 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3520 "'");
3521 assert(Lang <= Result.Max && "Expected valid DWARF language");
3522 Result.assign(Lang);
3523 Lex.Lex();
3524 return false;
3525}
3526
3527template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003528bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3529 if (Lex.getKind() == lltok::APSInt)
3530 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3531
3532 if (Lex.getKind() != lltok::DwarfCC)
3533 return TokError("expected DWARF calling convention");
3534
3535 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3536 if (!CC)
3537 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3538 "'");
3539 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3540 Result.assign(CC);
3541 Lex.Lex();
3542 return false;
3543}
3544
3545template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003546bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3547 if (Lex.getKind() == lltok::APSInt)
3548 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3549
3550 if (Lex.getKind() != lltok::EmissionKind)
3551 return TokError("expected emission kind");
3552
3553 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3554 if (!Kind)
3555 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3556 "'");
3557 assert(*Kind <= Result.Max && "Expected valid emission kind");
3558 Result.assign(*Kind);
3559 Lex.Lex();
3560 return false;
3561}
3562
3563template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003564bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003565 DwarfAttEncodingField &Result) {
3566 if (Lex.getKind() == lltok::APSInt)
3567 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3568
3569 if (Lex.getKind() != lltok::DwarfAttEncoding)
3570 return TokError("expected DWARF type attribute encoding");
3571
3572 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3573 if (!Encoding)
3574 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3575 Lex.getStrVal() + "'");
3576 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3577 Result.assign(Encoding);
3578 Lex.Lex();
3579 return false;
3580}
3581
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003582/// DIFlagField
3583/// ::= uint32
3584/// ::= DIFlagVector
3585/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3586template <>
3587bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3588 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3589
3590 // Parser for a single flag.
3591 auto parseFlag = [&](unsigned &Val) {
3592 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3593 return ParseUInt32(Val);
3594
3595 if (Lex.getKind() != lltok::DIFlag)
3596 return TokError("expected debug info flag");
3597
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003598 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003599 if (!Val)
3600 return TokError(Twine("invalid debug info flag flag '") +
3601 Lex.getStrVal() + "'");
3602 Lex.Lex();
3603 return false;
3604 };
3605
3606 // Parse the flags and combine them together.
3607 unsigned Combined = 0;
3608 do {
3609 unsigned Val;
3610 if (parseFlag(Val))
3611 return true;
3612 Combined |= Val;
3613 } while (EatIfPresent(lltok::bar));
3614
3615 Result.assign(Combined);
3616 return false;
3617}
3618
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003619template <>
3620bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003621 MDSignedField &Result) {
3622 if (Lex.getKind() != lltok::APSInt)
3623 return TokError("expected signed integer");
3624
3625 auto &S = Lex.getAPSIntVal();
3626 if (S < Result.Min)
3627 return TokError("value for '" + Name + "' too small, limit is " +
3628 Twine(Result.Min));
3629 if (S > Result.Max)
3630 return TokError("value for '" + Name + "' too large, limit is " +
3631 Twine(Result.Max));
3632 Result.assign(S.getExtValue());
3633 assert(Result.Val >= Result.Min && "Expected value in range");
3634 assert(Result.Val <= Result.Max && "Expected value in range");
3635 Lex.Lex();
3636 return false;
3637}
3638
3639template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003640bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3641 switch (Lex.getKind()) {
3642 default:
3643 return TokError("expected 'true' or 'false'");
3644 case lltok::kw_true:
3645 Result.assign(true);
3646 break;
3647 case lltok::kw_false:
3648 Result.assign(false);
3649 break;
3650 }
3651 Lex.Lex();
3652 return false;
3653}
3654
3655template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003656bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003657 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003658 if (!Result.AllowNull)
3659 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003660 Lex.Lex();
3661 Result.assign(nullptr);
3662 return false;
3663 }
3664
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003665 Metadata *MD;
3666 if (ParseMetadata(MD, nullptr))
3667 return true;
3668
3669 Result.assign(MD);
3670 return false;
3671}
3672
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003673template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003674bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3675 Metadata *MD;
3676 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3677 return true;
3678
3679 Result.assign(cast<ConstantAsMetadata>(MD));
3680 return false;
3681}
3682
3683template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003684bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003685 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003686 std::string S;
3687 if (ParseStringConstant(S))
3688 return true;
3689
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003690 if (!Result.AllowEmpty && S.empty())
3691 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3692
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003693 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003694 return false;
3695}
3696
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003697template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003698bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3699 SmallVector<Metadata *, 4> MDs;
3700 if (ParseMDNodeVector(MDs))
3701 return true;
3702
3703 Result.assign(std::move(MDs));
3704 return false;
3705}
3706
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003707} // end namespace llvm
3708
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003709template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003710bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003711 do {
3712 if (Lex.getKind() != lltok::LabelStr)
3713 return TokError("expected field label here");
3714
3715 if (parseField())
3716 return true;
3717 } while (EatIfPresent(lltok::comma));
3718
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003719 return false;
3720}
3721
3722template <class ParserTy>
3723bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3724 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3725 Lex.Lex();
3726
3727 if (ParseToken(lltok::lparen, "expected '(' here"))
3728 return true;
3729 if (Lex.getKind() != lltok::rparen)
3730 if (ParseMDFieldsImplBody(parseField))
3731 return true;
3732
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003733 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003734 return ParseToken(lltok::rparen, "expected ')' here");
3735}
3736
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003737template <class FieldTy>
3738bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3739 if (Result.Seen)
3740 return TokError("field '" + Name + "' cannot be specified more than once");
3741
3742 LocTy Loc = Lex.getLoc();
3743 Lex.Lex();
3744 return ParseMDField(Loc, Name, Result);
3745}
3746
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003747bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3748 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003749
3750#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003751 if (Lex.getStrVal() == #CLASS) \
3752 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003753#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003754
3755 return TokError("expected metadata type");
3756}
3757
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003758#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3759#define NOP_FIELD(NAME, TYPE, INIT)
3760#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3761 if (!NAME.Seen) \
3762 return Error(ClosingLoc, "missing required field '" #NAME "'");
3763#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003764 if (Lex.getStrVal() == #NAME) \
3765 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003766#define PARSE_MD_FIELDS() \
3767 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3768 do { \
3769 LocTy ClosingLoc; \
3770 if (ParseMDFieldsImpl([&]() -> bool { \
3771 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3772 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3773 }, ClosingLoc)) \
3774 return true; \
3775 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3776 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003777#define GET_OR_DISTINCT(CLASS, ARGS) \
3778 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003779
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003780/// ParseDILocationFields:
3781/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3782bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003783#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003784 OPTIONAL(line, LineField, ); \
3785 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003786 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003787 OPTIONAL(inlinedAt, MDField, );
3788 PARSE_MD_FIELDS();
3789#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003790
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003791 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003792 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003793 return false;
3794}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003795
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003796/// ParseGenericDINode:
3797/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3798bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003799#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003800 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003801 OPTIONAL(header, MDStringField, ); \
3802 OPTIONAL(operands, MDFieldList, );
3803 PARSE_MD_FIELDS();
3804#undef VISIT_MD_FIELDS
3805
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003806 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003807 (Context, tag.Val, header.Val, operands.Val));
3808 return false;
3809}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003810
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003811/// ParseDISubrange:
3812/// ::= !DISubrange(count: 30, lowerBound: 2)
3813bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003814#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003815 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003816 OPTIONAL(lowerBound, MDSignedField, );
3817 PARSE_MD_FIELDS();
3818#undef VISIT_MD_FIELDS
3819
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003820 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003821 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003822}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003823
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003824/// ParseDIEnumerator:
3825/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3826bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003827#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003828 REQUIRED(name, MDStringField, ); \
3829 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003830 PARSE_MD_FIELDS();
3831#undef VISIT_MD_FIELDS
3832
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003833 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003834 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003835}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003836
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003837/// ParseDIBasicType:
3838/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3839bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003840#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003841 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003842 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003843 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3844 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003845 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003846 PARSE_MD_FIELDS();
3847#undef VISIT_MD_FIELDS
3848
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003849 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003850 align.Val, encoding.Val));
3851 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003852}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003853
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003854/// ParseDIDerivedType:
3855/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003856/// line: 7, scope: !1, baseType: !2, size: 32,
3857/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003858bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003859#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3860 REQUIRED(tag, DwarfTagField, ); \
3861 OPTIONAL(name, MDStringField, ); \
3862 OPTIONAL(file, MDField, ); \
3863 OPTIONAL(line, LineField, ); \
3864 OPTIONAL(scope, MDField, ); \
3865 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003866 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3867 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3868 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003869 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003870 OPTIONAL(extraData, MDField, );
3871 PARSE_MD_FIELDS();
3872#undef VISIT_MD_FIELDS
3873
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003874 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003875 (Context, tag.Val, name.Val, file.Val, line.Val,
3876 scope.Val, baseType.Val, size.Val, align.Val,
3877 offset.Val, flags.Val, extraData.Val));
3878 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003879}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003880
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003881bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003882#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3883 REQUIRED(tag, DwarfTagField, ); \
3884 OPTIONAL(name, MDStringField, ); \
3885 OPTIONAL(file, MDField, ); \
3886 OPTIONAL(line, LineField, ); \
3887 OPTIONAL(scope, MDField, ); \
3888 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003889 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3890 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3891 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003892 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003893 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003894 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003895 OPTIONAL(vtableHolder, MDField, ); \
3896 OPTIONAL(templateParams, MDField, ); \
3897 OPTIONAL(identifier, MDStringField, );
3898 PARSE_MD_FIELDS();
3899#undef VISIT_MD_FIELDS
3900
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003901 // If this has an identifier try to build an ODR type.
3902 if (identifier.Val)
3903 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003904 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3905 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3906 elements.Val, runtimeLang.Val, vtableHolder.Val,
3907 templateParams.Val)) {
3908 Result = CT;
3909 return false;
3910 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003911
3912 // Create a new node, and save it in the context if it belongs in the type
3913 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003914 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003915 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003916 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3917 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3918 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3919 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003920}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003921
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003922bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003923#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003924 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003925 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003926 REQUIRED(types, MDField, );
3927 PARSE_MD_FIELDS();
3928#undef VISIT_MD_FIELDS
3929
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003930 Result = GET_OR_DISTINCT(DISubroutineType,
3931 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003932 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003933}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003934
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003935/// ParseDIFileType:
3936/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3937bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003938#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3939 REQUIRED(filename, MDStringField, ); \
3940 REQUIRED(directory, MDStringField, );
3941 PARSE_MD_FIELDS();
3942#undef VISIT_MD_FIELDS
3943
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003944 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003945 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003946}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003947
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003948/// ParseDICompileUnit:
3949/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003950/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00003951/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00003952/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003953/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003954bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003955 if (!IsDistinct)
3956 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3957
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003958#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3959 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003960 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003961 OPTIONAL(producer, MDStringField, ); \
3962 OPTIONAL(isOptimized, MDBoolField, ); \
3963 OPTIONAL(flags, MDStringField, ); \
3964 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3965 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00003966 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003967 OPTIONAL(enums, MDField, ); \
3968 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003969 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003970 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003971 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00003972 OPTIONAL(dwoId, MDUnsignedField, ); \
3973 OPTIONAL(splitDebugInlining, MDBoolField, = true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003974 PARSE_MD_FIELDS();
3975#undef VISIT_MD_FIELDS
3976
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003977 Result = DICompileUnit::getDistinct(
3978 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3979 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00003980 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
3981 splitDebugInlining.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003982 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003983}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003984
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003985/// ParseDISubprogram:
3986/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003987/// file: !1, line: 7, type: !2, isLocal: false,
3988/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003989/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00003990/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003991/// isOptimized: false, templateParams: !4, declaration: !5,
3992/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003993bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003994 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003995#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3996 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003997 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003998 OPTIONAL(linkageName, MDStringField, ); \
3999 OPTIONAL(file, MDField, ); \
4000 OPTIONAL(line, LineField, ); \
4001 OPTIONAL(type, MDField, ); \
4002 OPTIONAL(isLocal, MDBoolField, ); \
4003 OPTIONAL(isDefinition, MDBoolField, (true)); \
4004 OPTIONAL(scopeLine, LineField, ); \
4005 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004006 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004007 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004008 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004009 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004010 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004011 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004012 OPTIONAL(templateParams, MDField, ); \
4013 OPTIONAL(declaration, MDField, ); \
4014 OPTIONAL(variables, MDField, );
4015 PARSE_MD_FIELDS();
4016#undef VISIT_MD_FIELDS
4017
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004018 if (isDefinition.Val && !IsDistinct)
4019 return Lex.Error(
4020 Loc,
4021 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4022
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004023 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004024 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4025 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4026 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004027 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4028 isOptimized.Val, unit.Val, templateParams.Val,
4029 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004030 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004031}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004032
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004033/// ParseDILexicalBlock:
4034/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4035bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004036#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004037 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004038 OPTIONAL(file, MDField, ); \
4039 OPTIONAL(line, LineField, ); \
4040 OPTIONAL(column, ColumnField, );
4041 PARSE_MD_FIELDS();
4042#undef VISIT_MD_FIELDS
4043
4044 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004045 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004046 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004047}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004048
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004049/// ParseDILexicalBlockFile:
4050/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4051bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004052#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004053 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004054 OPTIONAL(file, MDField, ); \
4055 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4056 PARSE_MD_FIELDS();
4057#undef VISIT_MD_FIELDS
4058
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004059 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004060 (Context, scope.Val, file.Val, discriminator.Val));
4061 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004062}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004063
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004064/// ParseDINamespace:
4065/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4066bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004067#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4068 REQUIRED(scope, MDField, ); \
4069 OPTIONAL(file, MDField, ); \
4070 OPTIONAL(name, MDStringField, ); \
4071 OPTIONAL(line, LineField, );
4072 PARSE_MD_FIELDS();
4073#undef VISIT_MD_FIELDS
4074
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004075 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004076 (Context, scope.Val, file.Val, name.Val, line.Val));
4077 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004078}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004079
Amjad Abouda9bcf162015-12-10 12:56:35 +00004080/// ParseDIMacro:
4081/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4082bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4083#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4084 REQUIRED(type, DwarfMacinfoTypeField, ); \
4085 REQUIRED(line, LineField, ); \
4086 REQUIRED(name, MDStringField, ); \
4087 OPTIONAL(value, MDStringField, );
4088 PARSE_MD_FIELDS();
4089#undef VISIT_MD_FIELDS
4090
4091 Result = GET_OR_DISTINCT(DIMacro,
4092 (Context, type.Val, line.Val, name.Val, value.Val));
4093 return false;
4094}
4095
4096/// ParseDIMacroFile:
4097/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4098bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4099#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4100 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4101 REQUIRED(line, LineField, ); \
4102 REQUIRED(file, MDField, ); \
4103 OPTIONAL(nodes, MDField, );
4104 PARSE_MD_FIELDS();
4105#undef VISIT_MD_FIELDS
4106
4107 Result = GET_OR_DISTINCT(DIMacroFile,
4108 (Context, type.Val, line.Val, file.Val, nodes.Val));
4109 return false;
4110}
4111
4112
Adrian Prantlab1243f2015-06-29 23:03:47 +00004113/// ParseDIModule:
4114/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4115/// includePath: "/usr/include", isysroot: "/")
4116bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4117#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4118 REQUIRED(scope, MDField, ); \
4119 REQUIRED(name, MDStringField, ); \
4120 OPTIONAL(configMacros, MDStringField, ); \
4121 OPTIONAL(includePath, MDStringField, ); \
4122 OPTIONAL(isysroot, MDStringField, );
4123 PARSE_MD_FIELDS();
4124#undef VISIT_MD_FIELDS
4125
4126 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4127 configMacros.Val, includePath.Val, isysroot.Val));
4128 return false;
4129}
4130
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004131/// ParseDITemplateTypeParameter:
4132/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4133bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004134#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004135 OPTIONAL(name, MDStringField, ); \
4136 REQUIRED(type, MDField, );
4137 PARSE_MD_FIELDS();
4138#undef VISIT_MD_FIELDS
4139
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004140 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004141 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004142 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004143}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004144
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004145/// ParseDITemplateValueParameter:
4146/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004147/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004148bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004149#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004150 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004151 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004152 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004153 REQUIRED(value, MDField, );
4154 PARSE_MD_FIELDS();
4155#undef VISIT_MD_FIELDS
4156
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004157 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004158 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004159 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004160}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004161
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004162/// ParseDIGlobalVariable:
4163/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004164/// file: !1, line: 7, type: !2, isLocal: false,
4165/// isDefinition: true, variable: i32* @foo,
4166/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004167bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004168#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004169 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004170 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004171 OPTIONAL(linkageName, MDStringField, ); \
4172 OPTIONAL(file, MDField, ); \
4173 OPTIONAL(line, LineField, ); \
4174 OPTIONAL(type, MDField, ); \
4175 OPTIONAL(isLocal, MDBoolField, ); \
4176 OPTIONAL(isDefinition, MDBoolField, (true)); \
4177 OPTIONAL(variable, MDConstant, ); \
4178 OPTIONAL(declaration, MDField, );
4179 PARSE_MD_FIELDS();
4180#undef VISIT_MD_FIELDS
4181
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004182 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004183 (Context, scope.Val, name.Val, linkageName.Val,
4184 file.Val, line.Val, type.Val, isLocal.Val,
4185 isDefinition.Val, variable.Val, declaration.Val));
4186 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004187}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004188
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004189/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004190/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4191/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4192/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004193/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004194bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004196 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004197 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004198 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004199 OPTIONAL(file, MDField, ); \
4200 OPTIONAL(line, LineField, ); \
4201 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004202 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004203 PARSE_MD_FIELDS();
4204#undef VISIT_MD_FIELDS
4205
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004206 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004207 (Context, scope.Val, name.Val, file.Val, line.Val,
4208 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004209 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004210}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004211
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004212/// ParseDIExpression:
4213/// ::= !DIExpression(0, 7, -1)
4214bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004215 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4216 Lex.Lex();
4217
4218 if (ParseToken(lltok::lparen, "expected '(' here"))
4219 return true;
4220
4221 SmallVector<uint64_t, 8> Elements;
4222 if (Lex.getKind() != lltok::rparen)
4223 do {
4224 if (Lex.getKind() == lltok::DwarfOp) {
4225 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4226 Lex.Lex();
4227 Elements.push_back(Op);
4228 continue;
4229 }
4230 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4231 }
4232
4233 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4234 return TokError("expected unsigned integer");
4235
4236 auto &U = Lex.getAPSIntVal();
4237 if (U.ugt(UINT64_MAX))
4238 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4239 Elements.push_back(U.getZExtValue());
4240 Lex.Lex();
4241 } while (EatIfPresent(lltok::comma));
4242
4243 if (ParseToken(lltok::rparen, "expected ')' here"))
4244 return true;
4245
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004246 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004247 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004248}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004249
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004250/// ParseDIObjCProperty:
4251/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004252/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004253bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004254#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004255 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004256 OPTIONAL(file, MDField, ); \
4257 OPTIONAL(line, LineField, ); \
4258 OPTIONAL(setter, MDStringField, ); \
4259 OPTIONAL(getter, MDStringField, ); \
4260 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4261 OPTIONAL(type, MDField, );
4262 PARSE_MD_FIELDS();
4263#undef VISIT_MD_FIELDS
4264
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004265 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004266 (Context, name.Val, file.Val, line.Val, setter.Val,
4267 getter.Val, attributes.Val, type.Val));
4268 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004269}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004270
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004271/// ParseDIImportedEntity:
4272/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004273/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004274bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004275#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4276 REQUIRED(tag, DwarfTagField, ); \
4277 REQUIRED(scope, MDField, ); \
4278 OPTIONAL(entity, MDField, ); \
4279 OPTIONAL(line, LineField, ); \
4280 OPTIONAL(name, MDStringField, );
4281 PARSE_MD_FIELDS();
4282#undef VISIT_MD_FIELDS
4283
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004284 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004285 entity.Val, line.Val, name.Val));
4286 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004287}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004288
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004289#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004290#undef NOP_FIELD
4291#undef REQUIRE_FIELD
4292#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004293
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004294/// ParseMetadataAsValue
4295/// ::= metadata i32 %local
4296/// ::= metadata i32 @global
4297/// ::= metadata i32 7
4298/// ::= metadata !0
4299/// ::= metadata !{...}
4300/// ::= metadata !"string"
4301bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4302 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004303 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004304 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004305 return true;
4306
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004307 V = MetadataAsValue::get(Context, MD);
4308 return false;
4309}
4310
4311/// ParseValueAsMetadata
4312/// ::= i32 %local
4313/// ::= i32 @global
4314/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004315bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4316 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004317 Type *Ty;
4318 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004319 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004320 return true;
4321 if (Ty->isMetadataTy())
4322 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4323
4324 Value *V;
4325 if (ParseValue(Ty, V, PFS))
4326 return true;
4327
4328 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004329 return false;
4330}
4331
4332/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004333/// ::= i32 %local
4334/// ::= i32 @global
4335/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004336/// ::= !42
4337/// ::= !{...}
4338/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004339/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004340bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004341 if (Lex.getKind() == lltok::MetadataVar) {
4342 MDNode *N;
4343 if (ParseSpecializedMDNode(N))
4344 return true;
4345 MD = N;
4346 return false;
4347 }
4348
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004349 // ValueAsMetadata:
4350 // <type> <value>
4351 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004352 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004353
4354 // '!'.
4355 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4356 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004357
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004358 // MDString:
4359 // ::= '!' STRINGCONSTANT
4360 if (Lex.getKind() == lltok::StringConstant) {
4361 MDString *S;
4362 if (ParseMDString(S))
4363 return true;
4364 MD = S;
4365 return false;
4366 }
4367
Dan Gohman8939ba332010-07-14 18:26:50 +00004368 // MDNode:
4369 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004370 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004371 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004372 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004373 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004374 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004375 return false;
4376}
4377
Victor Hernandez9d75c962010-01-11 22:31:58 +00004378
4379//===----------------------------------------------------------------------===//
4380// Function Parsing.
4381//===----------------------------------------------------------------------===//
4382
Chris Lattner229907c2011-07-18 04:54:35 +00004383bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004384 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004385 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004387
Chris Lattnerac161bf2009-01-02 07:01:27 +00004388 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004389 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004390 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004391 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004392 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004393 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004394 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004395 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004396 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004397 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004398 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004399 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004400 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4401 (ID.UIntVal >> 1) & 1,
4402 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004403 return false;
4404 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004405 case ValID::t_GlobalName:
4406 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004407 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408 case ValID::t_GlobalID:
4409 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004410 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004411 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004412 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004413 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004414 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004415 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004416 return false;
4417 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004418 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004419 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4420 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004421
Dan Gohman518cda42011-12-17 00:04:22 +00004422 // The lexer has no type info, so builds all half, float, and double FP
4423 // constants as double. Fix this here. Long double does not need this.
4424 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004425 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004426 if (Ty->isHalfTy())
4427 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4428 &Ignored);
4429 else if (Ty->isFloatTy())
4430 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4431 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004432 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004433 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004434
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004435 if (V->getType() != Ty)
4436 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004437 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004438
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 return false;
4440 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004441 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004442 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004443 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004444 return false;
4445 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004446 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004447 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004448 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004449 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004450 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004451 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004452 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004453 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004454 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004455 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004456 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004457 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004458 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004460 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004462 case ValID::t_None:
4463 if (!Ty->isTokenTy())
4464 return Error(ID.Loc, "invalid type for none constant");
4465 V = Constant::getNullValue(Ty);
4466 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004467 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004468 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004470
Chris Lattnerac161bf2009-01-02 07:01:27 +00004471 V = ID.ConstantVal;
4472 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004473 case ValID::t_ConstantStruct:
4474 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004475 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004476 if (ST->getNumElements() != ID.UIntVal)
4477 return Error(ID.Loc,
4478 "initializer with struct type has wrong # elements");
4479 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4480 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004481
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004482 // Verify that the elements are compatible with the structtype.
4483 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4484 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4485 return Error(ID.Loc, "element " + Twine(i) +
4486 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004487
David Blaikieadbda4b2015-08-03 20:08:41 +00004488 V = ConstantStruct::get(
4489 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004490 } else
4491 return Error(ID.Loc, "constant expression type mismatch");
4492 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004493 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004494 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004496
Alex Lorenzd2255952015-07-17 22:07:03 +00004497bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4498 C = nullptr;
4499 ValID ID;
4500 auto Loc = Lex.getLoc();
4501 if (ParseValID(ID, /*PFS=*/nullptr))
4502 return true;
4503 switch (ID.Kind) {
4504 case ValID::t_APSInt:
4505 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004506 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004507 case ValID::t_Constant:
4508 case ValID::t_ConstantStruct:
4509 case ValID::t_PackedConstantStruct: {
4510 Value *V;
4511 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4512 return true;
4513 assert(isa<Constant>(V) && "Expected a constant value");
4514 C = cast<Constant>(V);
4515 return false;
4516 }
4517 default:
4518 return Error(Loc, "expected a constant value");
4519 }
4520}
4521
David Majnemer8a1c45d2015-12-12 05:38:55 +00004522bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004523 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004525 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526}
4527
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004528bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004529 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004530 return ParseType(Ty) ||
4531 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004532}
4533
Chris Lattner3ed871f2009-10-27 19:13:16 +00004534bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4535 PerFunctionState &PFS) {
4536 Value *V;
4537 Loc = Lex.getLoc();
4538 if (ParseTypeAndValue(V, PFS)) return true;
4539 if (!isa<BasicBlock>(V))
4540 return Error(Loc, "expected a basic block");
4541 BB = cast<BasicBlock>(V);
4542 return false;
4543}
4544
4545
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546/// FunctionHeader
4547/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004548/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004549/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4551 // Parse the linkage.
4552 LocTy LinkageLoc = Lex.getLoc();
4553 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004554
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004555 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004556 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004557 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004558 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004559 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004560 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004561 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004562 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4563 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004564 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 return true;
4566
4567 // Verify that the linkage is ok.
4568 switch ((GlobalValue::LinkageTypes)Linkage) {
4569 case GlobalValue::ExternalLinkage:
4570 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004571 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 if (isDefine)
4573 return Error(LinkageLoc, "invalid linkage for function definition");
4574 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004575 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004576 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004577 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004578 case GlobalValue::LinkOnceAnyLinkage:
4579 case GlobalValue::LinkOnceODRLinkage:
4580 case GlobalValue::WeakAnyLinkage:
4581 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004582 if (!isDefine)
4583 return Error(LinkageLoc, "invalid linkage for function declaration");
4584 break;
4585 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004586 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004587 return Error(LinkageLoc, "invalid function linkage type");
4588 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004589
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004590 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4591 return Error(LinkageLoc,
4592 "symbol with local linkage must have default visibility");
4593
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004594 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004595 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004596
Chris Lattnerac161bf2009-01-02 07:01:27 +00004597 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004598
4599 std::string FunctionName;
4600 if (Lex.getKind() == lltok::GlobalVar) {
4601 FunctionName = Lex.getStrVal();
4602 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4603 unsigned NameID = Lex.getUIntVal();
4604
4605 if (NameID != NumberedVals.size())
4606 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004607 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004608 } else {
4609 return TokError("expected function name");
4610 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004611
Chris Lattner3822f632009-01-02 08:05:26 +00004612 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004613
Chris Lattner3822f632009-01-02 08:05:26 +00004614 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004616
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004617 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004618 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004619 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004620 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004621 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004624 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004625 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004626 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004627 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004628 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004629 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004630 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004631
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004632 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004633 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004634 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004635 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004636 (EatIfPresent(lltok::kw_section) &&
4637 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004638 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004639 ParseOptionalAlignment(Alignment) ||
4640 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004641 ParseStringConstant(GC)) ||
4642 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004643 ParseGlobalTypeAndValue(Prefix)) ||
4644 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004645 ParseGlobalTypeAndValue(Prologue)) ||
4646 (EatIfPresent(lltok::kw_personality) &&
4647 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004648 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649
Michael Gottesman41748d72013-06-27 00:25:01 +00004650 if (FuncAttrs.contains(Attribute::Builtin))
4651 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004652
Chris Lattnerac161bf2009-01-02 07:01:27 +00004653 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004654 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004655 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004656 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004657 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004658
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659 // Okay, if we got here, the function is syntactically valid. Convert types
4660 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004661 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004662 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004663
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004664 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004665 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4666 AttributeSet::ReturnIndex,
4667 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004670 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004671 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4672 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004673 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4674 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004675 }
4676
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004677 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004678 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4679 AttributeSet::FunctionIndex,
4680 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004681
Bill Wendlinge94d8432012-12-07 23:16:57 +00004682 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004683
Bill Wendling749a43d2012-12-30 13:50:49 +00004684 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004685 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4686
Chris Lattner229907c2011-07-18 04:54:35 +00004687 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004688 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004689 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004690
Craig Topper2617dcc2014-04-15 06:32:26 +00004691 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004692 if (!FunctionName.empty()) {
4693 // If this was a definition of a forward reference, remove the definition
4694 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004695 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 if (FRVI != ForwardRefVals.end()) {
4697 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004698 if (!Fn)
4699 return Error(FRVI->second.second, "invalid forward reference to "
4700 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004701 if (Fn->getType() != PFT)
4702 return Error(FRVI->second.second, "invalid forward reference to "
4703 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004704
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705 ForwardRefVals.erase(FRVI);
4706 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004707 // Reject redefinitions.
4708 return Error(NameLoc, "invalid redefinition of function '" +
4709 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004710 } else if (M->getNamedValue(FunctionName)) {
4711 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004712 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004713
Dan Gohman399d6ae2009-08-29 23:37:49 +00004714 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004715 // If this is a definition of a forward referenced function, make sure the
4716 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004717 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 if (I != ForwardRefValIDs.end()) {
4719 Fn = cast<Function>(I->second.first);
4720 if (Fn->getType() != PFT)
4721 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004722 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 ForwardRefValIDs.erase(I);
4724 }
4725 }
4726
Craig Topper2617dcc2014-04-15 06:32:26 +00004727 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004728 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4729 else // Move the forward-reference to the correct spot in the module.
4730 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4731
4732 if (FunctionName.empty())
4733 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004734
Chris Lattnerac161bf2009-01-02 07:01:27 +00004735 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4736 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004737 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004738 Fn->setCallingConv(CC);
4739 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004740 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 Fn->setAlignment(Alignment);
4742 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004743 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004744 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004745 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004746 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004747 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004748 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004749
Chris Lattnerac161bf2009-01-02 07:01:27 +00004750 // Add all of the arguments we parsed to the function.
4751 Function::arg_iterator ArgIt = Fn->arg_begin();
4752 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4753 // If the argument has a name, insert it into the argument symbol table.
4754 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004755
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 // Set the name, if it conflicted, it will be auto-renamed.
4757 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004758
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004759 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4761 ArgList[i].Name + "'");
4762 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004763
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004764 if (isDefine)
4765 return false;
4766
Robin Morisset039781e2014-08-29 21:53:01 +00004767 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004768 ValID ID;
4769 if (FunctionName.empty()) {
4770 ID.Kind = ValID::t_GlobalID;
4771 ID.UIntVal = NumberedVals.size() - 1;
4772 } else {
4773 ID.Kind = ValID::t_GlobalName;
4774 ID.StrVal = FunctionName;
4775 }
4776 auto Blocks = ForwardRefBlockAddresses.find(ID);
4777 if (Blocks != ForwardRefBlockAddresses.end())
4778 return Error(Blocks->first.Loc,
4779 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004780 return false;
4781}
4782
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004783bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4784 ValID ID;
4785 if (FunctionNumber == -1) {
4786 ID.Kind = ValID::t_GlobalName;
4787 ID.StrVal = F.getName();
4788 } else {
4789 ID.Kind = ValID::t_GlobalID;
4790 ID.UIntVal = FunctionNumber;
4791 }
4792
4793 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4794 if (Blocks == P.ForwardRefBlockAddresses.end())
4795 return false;
4796
4797 for (const auto &I : Blocks->second) {
4798 const ValID &BBID = I.first;
4799 GlobalValue *GV = I.second;
4800
4801 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4802 "Expected local id or name");
4803 BasicBlock *BB;
4804 if (BBID.Kind == ValID::t_LocalName)
4805 BB = GetBB(BBID.StrVal, BBID.Loc);
4806 else
4807 BB = GetBB(BBID.UIntVal, BBID.Loc);
4808 if (!BB)
4809 return P.Error(BBID.Loc, "referenced value is not a basic block");
4810
4811 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4812 GV->eraseFromParent();
4813 }
4814
4815 P.ForwardRefBlockAddresses.erase(Blocks);
4816 return false;
4817}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004818
4819/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004820/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004822 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004823 return TokError("expected '{' in function body");
4824 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004825
Chris Lattner3432c622009-10-28 03:39:23 +00004826 int FunctionNumber = -1;
4827 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004828
Chris Lattner3432c622009-10-28 03:39:23 +00004829 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004830
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004831 // Resolve block addresses and allow basic blocks to be forward-declared
4832 // within this function.
4833 if (PFS.resolveForwardRefBlockAddresses())
4834 return true;
4835 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4836
Chris Lattnerbbddd962010-01-09 19:20:07 +00004837 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004838 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004839 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004840
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004841 while (Lex.getKind() != lltok::rbrace &&
4842 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004843 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004844
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004845 while (Lex.getKind() != lltok::rbrace)
4846 if (ParseUseListOrder(&PFS))
4847 return true;
4848
Chris Lattnerac161bf2009-01-02 07:01:27 +00004849 // Eat the }.
4850 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004851
Chris Lattnerac161bf2009-01-02 07:01:27 +00004852 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004853 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004854}
4855
4856/// ParseBasicBlock
4857/// ::= LabelStr? Instruction*
4858bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4859 // If this basic block starts out with a name, remember it.
4860 std::string Name;
4861 LocTy NameLoc = Lex.getLoc();
4862 if (Lex.getKind() == lltok::LabelStr) {
4863 Name = Lex.getStrVal();
4864 Lex.Lex();
4865 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004866
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004868 if (!BB)
4869 return Error(NameLoc,
4870 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004871
Chris Lattnerac161bf2009-01-02 07:01:27 +00004872 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004873
Chris Lattnerac161bf2009-01-02 07:01:27 +00004874 // Parse the instructions in this block until we get a terminator.
4875 Instruction *Inst;
4876 do {
4877 // This instruction may have three possibilities for a name: a) none
4878 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4879 LocTy NameLoc = Lex.getLoc();
4880 int NameID = -1;
4881 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004882
Chris Lattnerac161bf2009-01-02 07:01:27 +00004883 if (Lex.getKind() == lltok::LocalVarID) {
4884 NameID = Lex.getUIntVal();
4885 Lex.Lex();
4886 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4887 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004888 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004889 NameStr = Lex.getStrVal();
4890 Lex.Lex();
4891 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4892 return true;
4893 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004894
Chris Lattner77b89dc2009-12-30 05:23:43 +00004895 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004896 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004897 case InstError: return true;
4898 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004899 BB->getInstList().push_back(Inst);
4900
Chris Lattner77b89dc2009-12-30 05:23:43 +00004901 // With a normal result, we check to see if the instruction is followed by
4902 // a comma and metadata.
4903 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004904 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004905 return true;
4906 break;
4907 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004908 BB->getInstList().push_back(Inst);
4909
Chris Lattner77b89dc2009-12-30 05:23:43 +00004910 // If the instruction parser ate an extra comma at the end of it, it
4911 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004912 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004913 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004914 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004915 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004916
Chris Lattnerac161bf2009-01-02 07:01:27 +00004917 // Set the name on the instruction.
4918 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4919 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004920
Chris Lattnerac161bf2009-01-02 07:01:27 +00004921 return false;
4922}
4923
4924//===----------------------------------------------------------------------===//
4925// Instruction Parsing.
4926//===----------------------------------------------------------------------===//
4927
4928/// ParseInstruction - Parse one of the many different instructions.
4929///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004930int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4931 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004932 lltok::Kind Token = Lex.getKind();
4933 if (Token == lltok::Eof)
4934 return TokError("found end of file when expecting more instructions");
4935 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004936 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004937 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004938
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939 switch (Token) {
4940 default: return Error(Loc, "expected instruction opcode");
4941 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004942 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4944 case lltok::kw_br: return ParseBr(Inst, PFS);
4945 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004946 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004948 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004949 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4950 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004951 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4952 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004953 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004954 // Binary Operators.
4955 case lltok::kw_add:
4956 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004957 case lltok::kw_mul:
4958 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004959 bool NUW = EatIfPresent(lltok::kw_nuw);
4960 bool NSW = EatIfPresent(lltok::kw_nsw);
4961 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004962
Chris Lattnera676c0f2011-02-07 16:40:21 +00004963 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004964
Chris Lattnera676c0f2011-02-07 16:40:21 +00004965 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4966 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4967 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004968 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004969 case lltok::kw_fadd:
4970 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004971 case lltok::kw_fmul:
4972 case lltok::kw_fdiv:
4973 case lltok::kw_frem: {
4974 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4975 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4976 if (Res != 0)
4977 return Res;
4978 if (FMF.any())
4979 Inst->setFastMathFlags(FMF);
4980 return 0;
4981 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004982
Chris Lattner35315d02011-02-06 21:44:57 +00004983 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004984 case lltok::kw_udiv:
4985 case lltok::kw_lshr:
4986 case lltok::kw_ashr: {
4987 bool Exact = EatIfPresent(lltok::kw_exact);
4988
4989 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4990 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4991 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004992 }
4993
Chris Lattnerac161bf2009-01-02 07:01:27 +00004994 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004995 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004996 case lltok::kw_and:
4997 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004998 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004999 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5000 case lltok::kw_fcmp: {
5001 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5002 int Res = ParseCompare(Inst, PFS, KeywordVal);
5003 if (Res != 0)
5004 return Res;
5005 if (FMF.any())
5006 Inst->setFastMathFlags(FMF);
5007 return 0;
5008 }
5009
Chris Lattnerac161bf2009-01-02 07:01:27 +00005010 // Casts.
5011 case lltok::kw_trunc:
5012 case lltok::kw_zext:
5013 case lltok::kw_sext:
5014 case lltok::kw_fptrunc:
5015 case lltok::kw_fpext:
5016 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005017 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005018 case lltok::kw_uitofp:
5019 case lltok::kw_sitofp:
5020 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005021 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005022 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005023 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 // Other.
5025 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005026 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005027 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5028 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5029 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5030 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005031 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005032 // Call.
5033 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5034 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5035 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005036 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005037 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005038 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005039 case lltok::kw_load: return ParseLoad(Inst, PFS);
5040 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005041 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5042 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005043 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005044 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5045 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5046 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5047 }
5048}
5049
5050/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5051bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005052 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005053 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005054 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005055 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5056 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5057 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5058 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5059 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5060 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5061 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5062 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5063 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5064 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5065 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5066 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5067 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5068 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5069 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5070 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5071 }
5072 } else {
5073 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005074 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5076 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5077 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5078 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5079 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5080 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5081 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5082 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5083 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5084 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5085 }
5086 }
5087 Lex.Lex();
5088 return false;
5089}
5090
5091//===----------------------------------------------------------------------===//
5092// Terminator Instructions.
5093//===----------------------------------------------------------------------===//
5094
5095/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005096/// ::= 'ret' void (',' !dbg, !1)*
5097/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005098bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005099 PerFunctionState &PFS) {
5100 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005101 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005102 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005104 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005105
Chris Lattnerfdd87902009-10-05 05:54:46 +00005106 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005107 if (!ResType->isVoidTy())
5108 return Error(TypeLoc, "value doesn't match function result type '" +
5109 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005110
Owen Anderson55f1c092009-08-13 21:58:54 +00005111 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112 return false;
5113 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005114
Chris Lattnerac161bf2009-01-02 07:01:27 +00005115 Value *RV;
5116 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005118 if (ResType != RV->getType())
5119 return Error(TypeLoc, "value doesn't match function result type '" +
5120 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005121
Owen Anderson55f1c092009-08-13 21:58:54 +00005122 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005123 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005124}
5125
5126
5127/// ParseBr
5128/// ::= 'br' TypeAndValue
5129/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5130bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5131 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005132 Value *Op0;
5133 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005134 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005135
Chris Lattnerac161bf2009-01-02 07:01:27 +00005136 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5137 Inst = BranchInst::Create(BB);
5138 return false;
5139 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005140
Owen Anderson55f1c092009-08-13 21:58:54 +00005141 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005143
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005145 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005146 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005147 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005148 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005149
Chris Lattner3ed871f2009-10-27 19:13:16 +00005150 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 return false;
5152}
5153
5154/// ParseSwitch
5155/// Instruction
5156/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5157/// JumpTable
5158/// ::= (TypeAndValue ',' TypeAndValue)*
5159bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5160 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005161 Value *Cond;
5162 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005163 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5164 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005165 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005166 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5167 return true;
5168
Duncan Sands19d0b472010-02-16 11:11:14 +00005169 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005170 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005171
Chris Lattnerac161bf2009-01-02 07:01:27 +00005172 // Parse the jump table pairs.
5173 SmallPtrSet<Value*, 32> SeenCases;
5174 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5175 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005176 Value *Constant;
5177 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005178
Chris Lattnerac161bf2009-01-02 07:01:27 +00005179 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5180 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005181 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005183
David Blaikie70573dc2014-11-19 07:49:26 +00005184 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005185 return Error(CondLoc, "duplicate case value in switch");
5186 if (!isa<ConstantInt>(Constant))
5187 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005188
Chris Lattner3ed871f2009-10-27 19:13:16 +00005189 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005191
Chris Lattnerac161bf2009-01-02 07:01:27 +00005192 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005193
Chris Lattner3ed871f2009-10-27 19:13:16 +00005194 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005195 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5196 SI->addCase(Table[i].first, Table[i].second);
5197 Inst = SI;
5198 return false;
5199}
5200
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005201/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005202/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005203/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5204bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005205 LocTy AddrLoc;
5206 Value *Address;
5207 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005208 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5209 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005210 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005211
Duncan Sands19d0b472010-02-16 11:11:14 +00005212 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005213 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005214
Chris Lattner3ed871f2009-10-27 19:13:16 +00005215 // Parse the destination list.
5216 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005217
Chris Lattner3ed871f2009-10-27 19:13:16 +00005218 if (Lex.getKind() != lltok::rsquare) {
5219 BasicBlock *DestBB;
5220 if (ParseTypeAndBasicBlock(DestBB, PFS))
5221 return true;
5222 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005223
Chris Lattner3ed871f2009-10-27 19:13:16 +00005224 while (EatIfPresent(lltok::comma)) {
5225 if (ParseTypeAndBasicBlock(DestBB, PFS))
5226 return true;
5227 DestList.push_back(DestBB);
5228 }
5229 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005230
Chris Lattner3ed871f2009-10-27 19:13:16 +00005231 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5232 return true;
5233
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005234 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005235 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5236 IBI->addDestination(DestList[i]);
5237 Inst = IBI;
5238 return false;
5239}
5240
5241
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242/// ParseInvoke
5243/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5244/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5245bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5246 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005247 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005248 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005249 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005250 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005251 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005252 LocTy RetTypeLoc;
5253 ValID CalleeID;
5254 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005255 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256
Chris Lattner3ed871f2009-10-27 19:13:16 +00005257 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005258 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005259 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005260 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005261 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5262 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005263 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005265 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005266 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005267 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005269
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270 // If RetType is a non-function pointer type, then this is the short syntax
5271 // for the call, which means that RetType is just the return type. Infer the
5272 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005273 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5274 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005275 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005276 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005277 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5278 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005279
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280 if (!FunctionType::isValidReturnType(RetType))
5281 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005282
Owen Anderson4056ca92009-07-29 22:17:13 +00005283 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005284 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005285
David Blaikie41ba2b42015-07-27 23:32:19 +00005286 CalleeID.FTy = Ty;
5287
Chris Lattnerac161bf2009-01-02 07:01:27 +00005288 // Look up the callee.
5289 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005290 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5291 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005292
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005293 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005294 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005295 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005296 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5297 AttributeSet::ReturnIndex,
5298 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005299
Chris Lattnerac161bf2009-01-02 07:01:27 +00005300 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005301
Chris Lattnerac161bf2009-01-02 07:01:27 +00005302 // Loop through FunctionType's arguments and ensure they are specified
5303 // correctly. Also, gather any parameter attributes.
5304 FunctionType::param_iterator I = Ty->param_begin();
5305 FunctionType::param_iterator E = Ty->param_end();
5306 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005307 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308 if (I != E) {
5309 ExpectedTy = *I++;
5310 } else if (!Ty->isVarArg()) {
5311 return Error(ArgList[i].Loc, "too many arguments specified");
5312 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005313
Chris Lattnerac161bf2009-01-02 07:01:27 +00005314 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5315 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005316 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005317 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005318 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5319 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005320 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5321 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005322 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005323
Chris Lattnerac161bf2009-01-02 07:01:27 +00005324 if (I != E)
5325 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005326
David Majnemer8d22abd2015-02-23 00:01:32 +00005327 if (FnAttrs.hasAttributes()) {
5328 if (FnAttrs.hasAlignmentAttr())
5329 return Error(CallLoc, "invoke instructions may not have an alignment");
5330
Bill Wendlingf5075a42013-01-27 02:24:02 +00005331 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5332 AttributeSet::FunctionIndex,
5333 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005334 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005335
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005336 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005337 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005338
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005339 InvokeInst *II =
5340 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005341 II->setCallingConv(CC);
5342 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005343 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005344 Inst = II;
5345 return false;
5346}
5347
Bill Wendlingf891bf82011-07-31 06:30:59 +00005348/// ParseResume
5349/// ::= 'resume' TypeAndValue
5350bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5351 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005352 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5353 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005354
Bill Wendlingf891bf82011-07-31 06:30:59 +00005355 ResumeInst *RI = ResumeInst::Create(Exn);
5356 Inst = RI;
5357 return false;
5358}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359
David Majnemer654e1302015-07-31 17:58:14 +00005360bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5361 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005362 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005363 return true;
5364
5365 while (Lex.getKind() != lltok::rsquare) {
5366 // If this isn't the first argument, we need a comma.
5367 if (!Args.empty() &&
5368 ParseToken(lltok::comma, "expected ',' in argument list"))
5369 return true;
5370
5371 // Parse the argument.
5372 LocTy ArgLoc;
5373 Type *ArgTy = nullptr;
5374 if (ParseType(ArgTy, ArgLoc))
5375 return true;
5376
5377 Value *V;
5378 if (ArgTy->isMetadataTy()) {
5379 if (ParseMetadataAsValue(V, PFS))
5380 return true;
5381 } else {
5382 if (ParseValue(ArgTy, V, PFS))
5383 return true;
5384 }
5385 Args.push_back(V);
5386 }
5387
5388 Lex.Lex(); // Lex the ']'.
5389 return false;
5390}
5391
5392/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005393/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005394bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005395 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005396
David Majnemer8a1c45d2015-12-12 05:38:55 +00005397 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5398 return true;
5399
5400 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005401 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005402
5403 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5404 return true;
5405
5406 BasicBlock *UnwindBB = nullptr;
5407 if (Lex.getKind() == lltok::kw_to) {
5408 Lex.Lex();
5409 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5410 return true;
5411 } else {
5412 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5413 return true;
5414 }
5415 }
5416
David Majnemer8a1c45d2015-12-12 05:38:55 +00005417 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005418 return false;
5419}
5420
5421/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005422/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005423bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005424 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005425
David Majnemer8a1c45d2015-12-12 05:38:55 +00005426 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5427 return true;
5428
5429 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005430 return true;
5431
David Majnemer0bc0eef2015-08-15 02:46:08 +00005432 BasicBlock *BB;
5433 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5434 ParseTypeAndBasicBlock(BB, PFS))
5435 return true;
5436
David Majnemer8a1c45d2015-12-12 05:38:55 +00005437 Inst = CatchReturnInst::Create(CatchPad, BB);
5438 return false;
5439}
5440
5441/// ParseCatchSwitch
5442/// ::= 'catchswitch' within Parent
5443bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5444 Value *ParentPad;
5445 LocTy BBLoc;
5446
5447 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5448 return true;
5449
5450 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5451 Lex.getKind() != lltok::LocalVarID)
5452 return TokError("expected scope value for catchswitch");
5453
5454 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5455 return true;
5456
5457 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5458 return true;
5459
5460 SmallVector<BasicBlock *, 32> Table;
5461 do {
5462 BasicBlock *DestBB;
5463 if (ParseTypeAndBasicBlock(DestBB, PFS))
5464 return true;
5465 Table.push_back(DestBB);
5466 } while (EatIfPresent(lltok::comma));
5467
5468 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5469 return true;
5470
5471 if (ParseToken(lltok::kw_unwind,
5472 "expected 'unwind' after catchswitch scope"))
5473 return true;
5474
5475 BasicBlock *UnwindBB = nullptr;
5476 if (EatIfPresent(lltok::kw_to)) {
5477 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5478 return true;
5479 } else {
5480 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5481 return true;
5482 }
5483
5484 auto *CatchSwitch =
5485 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5486 for (BasicBlock *DestBB : Table)
5487 CatchSwitch->addHandler(DestBB);
5488 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005489 return false;
5490}
5491
5492/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005493/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005494bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005495 Value *CatchSwitch = nullptr;
5496
5497 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5498 return true;
5499
5500 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5501 return TokError("expected scope value for catchpad");
5502
5503 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5504 return true;
5505
David Majnemer654e1302015-07-31 17:58:14 +00005506 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005507 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005508 return true;
5509
David Majnemer8a1c45d2015-12-12 05:38:55 +00005510 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005511 return false;
5512}
5513
David Majnemer654e1302015-07-31 17:58:14 +00005514/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005515/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005516bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005517 Value *ParentPad = nullptr;
5518
5519 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5520 return true;
5521
5522 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5523 Lex.getKind() != lltok::LocalVarID)
5524 return TokError("expected scope value for cleanuppad");
5525
5526 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5527 return true;
5528
David Majnemer654e1302015-07-31 17:58:14 +00005529 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005530 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005531 return true;
5532
David Majnemer8a1c45d2015-12-12 05:38:55 +00005533 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005534 return false;
5535}
5536
Chris Lattnerac161bf2009-01-02 07:01:27 +00005537//===----------------------------------------------------------------------===//
5538// Binary Operators.
5539//===----------------------------------------------------------------------===//
5540
5541/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005542/// ::= ArithmeticOps TypeAndValue ',' Value
5543///
5544/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5545/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005546bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005547 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005548 LocTy Loc; Value *LHS, *RHS;
5549 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5550 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5551 ParseValue(LHS->getType(), RHS, PFS))
5552 return true;
5553
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005554 bool Valid;
5555 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005556 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005557 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005558 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5559 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005560 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005561 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5562 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005564
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005565 if (!Valid)
5566 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005567
Chris Lattnerac161bf2009-01-02 07:01:27 +00005568 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5569 return false;
5570}
5571
5572/// ParseLogical
5573/// ::= ArithmeticOps TypeAndValue ',' Value {
5574bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5575 unsigned Opc) {
5576 LocTy Loc; Value *LHS, *RHS;
5577 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5578 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5579 ParseValue(LHS->getType(), RHS, PFS))
5580 return true;
5581
Duncan Sands9dff9be2010-02-15 16:12:20 +00005582 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005583 return Error(Loc,"instruction requires integer or integer vector operands");
5584
5585 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5586 return false;
5587}
5588
5589
5590/// ParseCompare
5591/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5592/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005593bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5594 unsigned Opc) {
5595 // Parse the integer/fp comparison predicate.
5596 LocTy Loc;
5597 unsigned Pred;
5598 Value *LHS, *RHS;
5599 if (ParseCmpPredicate(Pred, Opc) ||
5600 ParseTypeAndValue(LHS, Loc, PFS) ||
5601 ParseToken(lltok::comma, "expected ',' after compare value") ||
5602 ParseValue(LHS->getType(), RHS, PFS))
5603 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005604
Chris Lattnerac161bf2009-01-02 07:01:27 +00005605 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005606 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005607 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005608 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005609 } else {
5610 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005611 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005612 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005613 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005614 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005615 }
5616 return false;
5617}
5618
5619//===----------------------------------------------------------------------===//
5620// Other Instructions.
5621//===----------------------------------------------------------------------===//
5622
5623
5624/// ParseCast
5625/// ::= CastOpc TypeAndValue 'to' Type
5626bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5627 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005628 LocTy Loc;
5629 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005630 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005631 if (ParseTypeAndValue(Op, Loc, PFS) ||
5632 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5633 ParseType(DestTy))
5634 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005635
Chris Lattner89d856e2009-03-01 00:53:13 +00005636 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5637 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005638 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005639 getTypeString(Op->getType()) + "' to '" +
5640 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005641 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005642 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5643 return false;
5644}
5645
5646/// ParseSelect
5647/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5648bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5649 LocTy Loc;
5650 Value *Op0, *Op1, *Op2;
5651 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5652 ParseToken(lltok::comma, "expected ',' after select condition") ||
5653 ParseTypeAndValue(Op1, PFS) ||
5654 ParseToken(lltok::comma, "expected ',' after select value") ||
5655 ParseTypeAndValue(Op2, PFS))
5656 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005657
Chris Lattnerac161bf2009-01-02 07:01:27 +00005658 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5659 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005660
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 Inst = SelectInst::Create(Op0, Op1, Op2);
5662 return false;
5663}
5664
Chris Lattnerb55ab542009-01-05 08:18:44 +00005665/// ParseVA_Arg
5666/// ::= 'va_arg' TypeAndValue ',' Type
5667bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005668 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005669 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005670 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005671 if (ParseTypeAndValue(Op, PFS) ||
5672 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005673 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005675
Chris Lattnerb55ab542009-01-05 08:18:44 +00005676 if (!EltTy->isFirstClassType())
5677 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678
5679 Inst = new VAArgInst(Op, EltTy);
5680 return false;
5681}
5682
5683/// ParseExtractElement
5684/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5685bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5686 LocTy Loc;
5687 Value *Op0, *Op1;
5688 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5689 ParseToken(lltok::comma, "expected ',' after extract value") ||
5690 ParseTypeAndValue(Op1, PFS))
5691 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005692
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5694 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005695
Eric Christopherc9742252009-07-25 02:28:41 +00005696 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697 return false;
5698}
5699
5700/// ParseInsertElement
5701/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5702bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5703 LocTy Loc;
5704 Value *Op0, *Op1, *Op2;
5705 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5706 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5707 ParseTypeAndValue(Op1, PFS) ||
5708 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5709 ParseTypeAndValue(Op2, PFS))
5710 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005711
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005713 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005714
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5716 return false;
5717}
5718
5719/// ParseShuffleVector
5720/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5721bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5722 LocTy Loc;
5723 Value *Op0, *Op1, *Op2;
5724 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5725 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5726 ParseTypeAndValue(Op1, PFS) ||
5727 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5728 ParseTypeAndValue(Op2, PFS))
5729 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005730
Chris Lattnerac161bf2009-01-02 07:01:27 +00005731 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005732 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005733
Chris Lattnerac161bf2009-01-02 07:01:27 +00005734 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5735 return false;
5736}
5737
5738/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005739/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005740int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005741 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005742 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005743
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005744 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5746 ParseValue(Ty, Op0, PFS) ||
5747 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005748 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5750 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005751
Chris Lattnerf4f03422009-12-30 05:27:33 +00005752 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5754 while (1) {
5755 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005756
Chris Lattner3822f632009-01-02 08:05:26 +00005757 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005758 break;
5759
Chris Lattnerf4f03422009-12-30 05:27:33 +00005760 if (Lex.getKind() == lltok::MetadataVar) {
5761 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005762 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005763 }
Devang Patel8f842d32009-10-16 18:45:49 +00005764
Chris Lattner3822f632009-01-02 08:05:26 +00005765 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005766 ParseValue(Ty, Op0, PFS) ||
5767 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005768 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005769 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5770 return true;
5771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005772
Chris Lattnerac161bf2009-01-02 07:01:27 +00005773 if (!Ty->isFirstClassType())
5774 return Error(TypeLoc, "phi node must have first class type");
5775
Jay Foad52131342011-03-30 11:28:46 +00005776 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005777 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5778 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5779 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005780 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005781}
5782
Bill Wendlingfae14752011-08-12 20:24:12 +00005783/// ParseLandingPad
5784/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5785/// Clause
5786/// ::= 'catch' TypeAndValue
5787/// ::= 'filter'
5788/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5789bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005790 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005791
David Majnemer7fddecc2015-06-17 20:52:32 +00005792 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005793 return true;
5794
David Majnemer7fddecc2015-06-17 20:52:32 +00005795 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005796 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5797
5798 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5799 LandingPadInst::ClauseType CT;
5800 if (EatIfPresent(lltok::kw_catch))
5801 CT = LandingPadInst::Catch;
5802 else if (EatIfPresent(lltok::kw_filter))
5803 CT = LandingPadInst::Filter;
5804 else
5805 return TokError("expected 'catch' or 'filter' clause type");
5806
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005807 Value *V;
5808 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005809 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005810 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005811
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005812 // A 'catch' type expects a non-array constant. A filter clause expects an
5813 // array constant.
5814 if (CT == LandingPadInst::Catch) {
5815 if (isa<ArrayType>(V->getType()))
5816 Error(VLoc, "'catch' clause has an invalid type");
5817 } else {
5818 if (!isa<ArrayType>(V->getType()))
5819 Error(VLoc, "'filter' clause has an invalid type");
5820 }
5821
Owen Andersonf8f259d2015-03-09 07:13:42 +00005822 Constant *CV = dyn_cast<Constant>(V);
5823 if (!CV)
5824 return Error(VLoc, "clause argument must be a constant");
5825 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005826 }
5827
Owen Andersonf8f259d2015-03-09 07:13:42 +00005828 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005829 return false;
5830}
5831
Chris Lattnerac161bf2009-01-02 07:01:27 +00005832/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005833/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5834/// OptionalAttrs Type Value ParameterList OptionalAttrs
5835/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5836/// OptionalAttrs Type Value ParameterList OptionalAttrs
5837/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5838/// OptionalAttrs Type Value ParameterList OptionalAttrs
5839/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5840/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005841bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005842 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005843 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005844 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005845 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005846 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005847 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005848 LocTy RetTypeLoc;
5849 ValID CalleeID;
5850 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005851 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005853
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005854 if (TCK != CallInst::TCK_None &&
5855 ParseToken(lltok::kw_call,
5856 "expected 'tail call', 'musttail call', or 'notail call'"))
5857 return true;
5858
5859 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5860
5861 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005862 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005863 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005864 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5865 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005866 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5867 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005868 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005869
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005870 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5871 return Error(CallLoc, "fast-math-flags specified for call without "
5872 "floating-point scalar or vector return type");
5873
Chris Lattnerac161bf2009-01-02 07:01:27 +00005874 // If RetType is a non-function pointer type, then this is the short syntax
5875 // for the call, which means that RetType is just the return type. Infer the
5876 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005877 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5878 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005879 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005880 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005881 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5882 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005883
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884 if (!FunctionType::isValidReturnType(RetType))
5885 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005886
Owen Anderson4056ca92009-07-29 22:17:13 +00005887 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005889
David Blaikie41ba2b42015-07-27 23:32:19 +00005890 CalleeID.FTy = Ty;
5891
Chris Lattnerac161bf2009-01-02 07:01:27 +00005892 // Look up the callee.
5893 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005894 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5895 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005896
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005897 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005898 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005899 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005900 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5901 AttributeSet::ReturnIndex,
5902 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005903
Chris Lattnerac161bf2009-01-02 07:01:27 +00005904 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005905
Chris Lattnerac161bf2009-01-02 07:01:27 +00005906 // Loop through FunctionType's arguments and ensure they are specified
5907 // correctly. Also, gather any parameter attributes.
5908 FunctionType::param_iterator I = Ty->param_begin();
5909 FunctionType::param_iterator E = Ty->param_end();
5910 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005911 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005912 if (I != E) {
5913 ExpectedTy = *I++;
5914 } else if (!Ty->isVarArg()) {
5915 return Error(ArgList[i].Loc, "too many arguments specified");
5916 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005917
Chris Lattnerac161bf2009-01-02 07:01:27 +00005918 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5919 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005920 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005921 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005922 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5923 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005924 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5925 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005926 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005927
Chris Lattnerac161bf2009-01-02 07:01:27 +00005928 if (I != E)
5929 return Error(CallLoc, "not enough parameters specified for call");
5930
David Majnemer8d22abd2015-02-23 00:01:32 +00005931 if (FnAttrs.hasAttributes()) {
5932 if (FnAttrs.hasAlignmentAttr())
5933 return Error(CallLoc, "call instructions may not have an alignment");
5934
Bill Wendlingf5075a42013-01-27 02:24:02 +00005935 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5936 AttributeSet::FunctionIndex,
5937 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005938 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005939
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005940 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005941 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005942
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005943 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005944 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005945 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005946 if (FMF.any())
5947 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005948 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005949 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005950 Inst = CI;
5951 return false;
5952}
5953
5954//===----------------------------------------------------------------------===//
5955// Memory Instructions.
5956//===----------------------------------------------------------------------===//
5957
5958/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00005959/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5960/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005961int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005962 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005963 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005964 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005965 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005966
5967 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005968 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00005969
David Majnemera3b0eb22015-02-16 08:38:03 +00005970 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005971
David Majnemera3b0eb22015-02-16 08:38:03 +00005972 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5973 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005974
Chris Lattnerb2f39502009-12-30 05:44:30 +00005975 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005976 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005977 if (Lex.getKind() == lltok::kw_align) {
5978 if (ParseOptionalAlignment(Alignment)) return true;
5979 } else if (Lex.getKind() == lltok::MetadataVar) {
5980 AteExtraComma = true;
5981 } else {
5982 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5983 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5984 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005985 }
5986 }
5987
Dan Gohman2140a742010-05-28 01:14:11 +00005988 if (Size && !Size->getType()->isIntegerTy())
5989 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005990
Reid Kleckner436c42e2014-01-17 23:58:17 +00005991 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5992 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005993 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00005994 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005995 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005996}
5997
5998/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005999/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006000/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006001/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006002int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006003 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006004 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006005 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006006 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006007 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006008 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006009
6010 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006011 isAtomic = true;
6012 Lex.Lex();
6013 }
6014
Chris Lattnerbc639292011-11-27 06:56:53 +00006015 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006016 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006017 isVolatile = true;
6018 Lex.Lex();
6019 }
6020
David Blaikie15d9a4c2015-04-06 20:59:48 +00006021 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006022 LocTy ExplicitTypeLoc = Lex.getLoc();
6023 if (ParseType(Ty) ||
6024 ParseToken(lltok::comma, "expected comma after load's type") ||
6025 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006026 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006027 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6028 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006029
David Blaikie15d9a4c2015-04-06 20:59:48 +00006030 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006031 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006032 if (isAtomic && !Alignment)
6033 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006034 if (Ordering == AtomicOrdering::Release ||
6035 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006036 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006037
David Blaikiea79ac142015-02-27 21:17:42 +00006038 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6039 return Error(ExplicitTypeLoc,
6040 "explicit pointee type doesn't match operand's pointee type");
6041
David Blaikie15d9a4c2015-04-06 20:59:48 +00006042 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006043 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006044}
6045
6046/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006047
6048/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6049/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006050/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006051int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006052 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006053 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006054 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006055 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006056 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006057 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006058
6059 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006060 isAtomic = true;
6061 Lex.Lex();
6062 }
6063
Chris Lattnerbc639292011-11-27 06:56:53 +00006064 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006065 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006066 isVolatile = true;
6067 Lex.Lex();
6068 }
6069
Chris Lattnerac161bf2009-01-02 07:01:27 +00006070 if (ParseTypeAndValue(Val, Loc, PFS) ||
6071 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006072 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006073 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006074 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006075 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006076
Duncan Sands19d0b472010-02-16 11:11:14 +00006077 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006078 return Error(PtrLoc, "store operand must be a pointer");
6079 if (!Val->getType()->isFirstClassType())
6080 return Error(Loc, "store operand must be a first class value");
6081 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6082 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006083 if (isAtomic && !Alignment)
6084 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006085 if (Ordering == AtomicOrdering::Acquire ||
6086 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006087 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006088
Eli Friedman59b66882011-08-09 23:02:53 +00006089 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006090 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006091}
6092
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006093/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006094/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6095/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006096int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006097 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6098 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006099 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6100 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006101 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006102 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006103 bool isWeak = false;
6104
6105 if (EatIfPresent(lltok::kw_weak))
6106 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006107
6108 if (EatIfPresent(lltok::kw_volatile))
6109 isVolatile = true;
6110
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006111 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6112 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6113 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6114 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6115 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006116 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6117 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006118 return true;
6119
JF Bastien800f87a2016-04-06 21:19:33 +00006120 if (SuccessOrdering == AtomicOrdering::Unordered ||
6121 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006122 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006123 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6124 return TokError("cmpxchg failure argument shall be no stronger than the "
6125 "success argument");
6126 if (FailureOrdering == AtomicOrdering::Release ||
6127 FailureOrdering == AtomicOrdering::AcquireRelease)
6128 return TokError(
6129 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006130 if (!Ptr->getType()->isPointerTy())
6131 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6132 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6133 return Error(CmpLoc, "compare value and pointer type do not match");
6134 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6135 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006136 if (!New->getType()->isFirstClassType())
6137 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006138 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6139 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006140 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006141 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006142 Inst = CXI;
6143 return AteExtraComma ? InstExtraComma : InstNormal;
6144}
6145
6146/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006147/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6148/// 'singlethread'? AtomicOrdering
6149int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006150 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6151 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006152 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006153 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006154 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006155 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006156
6157 if (EatIfPresent(lltok::kw_volatile))
6158 isVolatile = true;
6159
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006160 switch (Lex.getKind()) {
6161 default: return TokError("expected binary operation in atomicrmw");
6162 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6163 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6164 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6165 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6166 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6167 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6168 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6169 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6170 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6171 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6172 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6173 }
6174 Lex.Lex(); // Eat the operation.
6175
6176 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6177 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6178 ParseTypeAndValue(Val, ValLoc, PFS) ||
6179 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6180 return true;
6181
JF Bastien800f87a2016-04-06 21:19:33 +00006182 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006183 return TokError("atomicrmw cannot be unordered");
6184 if (!Ptr->getType()->isPointerTy())
6185 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6186 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6187 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6188 if (!Val->getType()->isIntegerTy())
6189 return Error(ValLoc, "atomicrmw operand must be an integer");
6190 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6191 if (Size < 8 || (Size & (Size - 1)))
6192 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6193 " integer");
6194
6195 AtomicRMWInst *RMWI =
6196 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6197 RMWI->setVolatile(isVolatile);
6198 Inst = RMWI;
6199 return AteExtraComma ? InstExtraComma : InstNormal;
6200}
6201
Eli Friedmanfee02c62011-07-25 23:16:38 +00006202/// ParseFence
6203/// ::= 'fence' 'singlethread'? AtomicOrdering
6204int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006205 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006206 SynchronizationScope Scope = CrossThread;
6207 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6208 return true;
6209
JF Bastien800f87a2016-04-06 21:19:33 +00006210 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006211 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006212 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006213 return TokError("fence cannot be monotonic");
6214
6215 Inst = new FenceInst(Context, Ordering, Scope);
6216 return InstNormal;
6217}
6218
Chris Lattnerac161bf2009-01-02 07:01:27 +00006219/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006220/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006221int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006222 Value *Ptr = nullptr;
6223 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006224 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006225
Dan Gohman16cbbe42009-07-29 15:58:36 +00006226 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006227
David Blaikie79e6c742015-02-27 19:29:02 +00006228 Type *Ty = nullptr;
6229 LocTy ExplicitTypeLoc = Lex.getLoc();
6230 if (ParseType(Ty) ||
6231 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6232 ParseTypeAndValue(Ptr, Loc, PFS))
6233 return true;
6234
Eli Benderskyd9806682013-04-22 17:03:42 +00006235 Type *BaseType = Ptr->getType();
6236 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6237 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006238 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006239
David Blaikie8d757942015-03-09 23:08:44 +00006240 if (Ty != BasePointerType->getElementType())
6241 return Error(ExplicitTypeLoc,
6242 "explicit pointee type doesn't match operand's pointee type");
6243
Chris Lattnerac161bf2009-01-02 07:01:27 +00006244 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006245 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006246 // GEP returns a vector of pointers if at least one of parameters is a vector.
6247 // All vector parameters should have the same vector width.
6248 unsigned GEPWidth = BaseType->isVectorTy() ?
6249 BaseType->getVectorNumElements() : 0;
6250
Chris Lattner3822f632009-01-02 08:05:26 +00006251 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006252 if (Lex.getKind() == lltok::MetadataVar) {
6253 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006254 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006255 }
Chris Lattner3822f632009-01-02 08:05:26 +00006256 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006257 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006258 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006259
Nadav Rotem3924cb02011-12-05 06:29:09 +00006260 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006261 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6262 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006263 return Error(EltLoc,
6264 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006265 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006266 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006267 Indices.push_back(Val);
6268 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006269
Craig Toppere3dcce92015-08-01 22:20:21 +00006270 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006271 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006272 return Error(Loc, "base element of getelementptr must be sized");
6273
David Blaikied33bad32015-04-17 22:32:13 +00006274 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006275 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006276 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006277 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006278 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006279 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006280}
6281
6282/// ParseExtractValue
6283/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006284int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006285 Value *Val; LocTy Loc;
6286 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006287 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006288 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006289 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006290 return true;
6291
Chris Lattner392be582010-02-12 20:49:41 +00006292 if (!Val->getType()->isAggregateType())
6293 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006294
Jay Foad57aa6362011-07-13 10:26:04 +00006295 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006296 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006297 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006298 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006299}
6300
6301/// ParseInsertValue
6302/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006303int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006304 Value *Val0, *Val1; LocTy Loc0, Loc1;
6305 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006306 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006307 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6308 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6309 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006310 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006311 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006312
Chris Lattner392be582010-02-12 20:49:41 +00006313 if (!Val0->getType()->isAggregateType())
6314 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006315
David Majnemer30074532015-02-11 07:43:58 +00006316 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6317 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006318 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006319 if (IndexedType != Val1->getType())
6320 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6321 getTypeString(Val1->getType()) + "' instead of '" +
6322 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006323 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006324 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006325}
Nick Lewycky49f89192009-04-04 07:22:01 +00006326
6327//===----------------------------------------------------------------------===//
6328// Embedded metadata.
6329//===----------------------------------------------------------------------===//
6330
6331/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006332/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006333/// Element
6334/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006335bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006336 if (ParseToken(lltok::lbrace, "expected '{' here"))
6337 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006338
Dan Gohman1e0213a2010-07-13 19:33:27 +00006339 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006340 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006341 return false;
6342
Nick Lewycky49f89192009-04-04 07:22:01 +00006343 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006344 // Null is a special case since it is typeless.
6345 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006346 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006347 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006348 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006349
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006350 Metadata *MD;
6351 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006352 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006353 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006354 } while (EatIfPresent(lltok::comma));
6355
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006356 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006357}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006358
6359//===----------------------------------------------------------------------===//
6360// Use-list order directives.
6361//===----------------------------------------------------------------------===//
6362bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6363 SMLoc Loc) {
6364 if (V->use_empty())
6365 return Error(Loc, "value has no uses");
6366
6367 unsigned NumUses = 0;
6368 SmallDenseMap<const Use *, unsigned, 16> Order;
6369 for (const Use &U : V->uses()) {
6370 if (++NumUses > Indexes.size())
6371 break;
6372 Order[&U] = Indexes[NumUses - 1];
6373 }
6374 if (NumUses < 2)
6375 return Error(Loc, "value only has one use");
6376 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6377 return Error(Loc, "wrong number of indexes, expected " +
6378 Twine(std::distance(V->use_begin(), V->use_end())));
6379
6380 V->sortUseList([&](const Use &L, const Use &R) {
6381 return Order.lookup(&L) < Order.lookup(&R);
6382 });
6383 return false;
6384}
6385
6386/// ParseUseListOrderIndexes
6387/// ::= '{' uint32 (',' uint32)+ '}'
6388bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6389 SMLoc Loc = Lex.getLoc();
6390 if (ParseToken(lltok::lbrace, "expected '{' here"))
6391 return true;
6392 if (Lex.getKind() == lltok::rbrace)
6393 return Lex.Error("expected non-empty list of uselistorder indexes");
6394
6395 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6396 // indexes should be distinct numbers in the range [0, size-1], and should
6397 // not be in order.
6398 unsigned Offset = 0;
6399 unsigned Max = 0;
6400 bool IsOrdered = true;
6401 assert(Indexes.empty() && "Expected empty order vector");
6402 do {
6403 unsigned Index;
6404 if (ParseUInt32(Index))
6405 return true;
6406
6407 // Update consistency checks.
6408 Offset += Index - Indexes.size();
6409 Max = std::max(Max, Index);
6410 IsOrdered &= Index == Indexes.size();
6411
6412 Indexes.push_back(Index);
6413 } while (EatIfPresent(lltok::comma));
6414
6415 if (ParseToken(lltok::rbrace, "expected '}' here"))
6416 return true;
6417
6418 if (Indexes.size() < 2)
6419 return Error(Loc, "expected >= 2 uselistorder indexes");
6420 if (Offset != 0 || Max >= Indexes.size())
6421 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6422 if (IsOrdered)
6423 return Error(Loc, "expected uselistorder indexes to change the order");
6424
6425 return false;
6426}
6427
6428/// ParseUseListOrder
6429/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6430bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6431 SMLoc Loc = Lex.getLoc();
6432 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6433 return true;
6434
6435 Value *V;
6436 SmallVector<unsigned, 16> Indexes;
6437 if (ParseTypeAndValue(V, PFS) ||
6438 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6439 ParseUseListOrderIndexes(Indexes))
6440 return true;
6441
6442 return sortUseListOrder(V, Indexes, Loc);
6443}
6444
6445/// ParseUseListOrderBB
6446/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6447bool LLParser::ParseUseListOrderBB() {
6448 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6449 SMLoc Loc = Lex.getLoc();
6450 Lex.Lex();
6451
6452 ValID Fn, Label;
6453 SmallVector<unsigned, 16> Indexes;
6454 if (ParseValID(Fn) ||
6455 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6456 ParseValID(Label) ||
6457 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6458 ParseUseListOrderIndexes(Indexes))
6459 return true;
6460
6461 // Check the function.
6462 GlobalValue *GV;
6463 if (Fn.Kind == ValID::t_GlobalName)
6464 GV = M->getNamedValue(Fn.StrVal);
6465 else if (Fn.Kind == ValID::t_GlobalID)
6466 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6467 else
6468 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6469 if (!GV)
6470 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6471 auto *F = dyn_cast<Function>(GV);
6472 if (!F)
6473 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6474 if (F->isDeclaration())
6475 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6476
6477 // Check the basic block.
6478 if (Label.Kind == ValID::t_LocalID)
6479 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6480 if (Label.Kind != ValID::t_LocalName)
6481 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6482 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6483 if (!V)
6484 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6485 if (!isa<BasicBlock>(V))
6486 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6487
6488 return sortUseListOrder(V, Indexes, Loc);
6489}