blob: 7269219f955bfeb37810ac2564b15baedf7be6e4 [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"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000017#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000018#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000021#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000030#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000031#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000033#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000034#include "llvm/Support/raw_ostream.h"
35using namespace llvm;
36
Chris Lattner229907c2011-07-18 04:54:35 +000037static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000038 std::string Result;
39 raw_string_ostream Tmp(Result);
40 Tmp << *T;
41 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000042}
43
Chris Lattner3822f632009-01-02 08:05:26 +000044/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000045bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000046 // Prime the lexer.
47 Lex.Lex();
48
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000049 if (Context.discardValueNames())
50 return Error(
51 Lex.getLoc(),
52 "Can't read textual IR with a Context that discards named Values");
53
Chris Lattnerad6f3352009-01-04 20:44:11 +000054 return ParseTopLevelEntities() ||
55 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000056}
57
Alex Lorenz1de2acd2015-08-21 21:32:39 +000058bool LLParser::parseStandaloneConstantValue(Constant *&C,
59 const SlotMapping *Slots) {
60 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000061 Lex.Lex();
62
63 Type *Ty = nullptr;
64 if (ParseType(Ty) || parseConstantValue(Ty, C))
65 return true;
66 if (Lex.getKind() != lltok::Eof)
67 return Error(Lex.getLoc(), "expected end of string");
68 return false;
69}
70
Quentin Colombetdafed5d2016-03-08 00:37:07 +000071bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
72 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000073 restoreParsingState(Slots);
74 Lex.Lex();
75
Quentin Colombetdafed5d2016-03-08 00:37:07 +000076 Read = 0;
77 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000078 Ty = nullptr;
79 if (ParseType(Ty))
80 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000081 SMLoc End = Lex.getLoc();
82 Read = End.getPointer() - Start.getPointer();
83
Quentin Colombet81e72b42016-03-07 22:09:05 +000084 return false;
85}
86
Alex Lorenz1de2acd2015-08-21 21:32:39 +000087void LLParser::restoreParsingState(const SlotMapping *Slots) {
88 if (!Slots)
89 return;
90 NumberedVals = Slots->GlobalValues;
91 NumberedMetadata = Slots->MetadataNodes;
92 for (const auto &I : Slots->NamedTypes)
93 NamedTypes.insert(
94 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
95 for (const auto &I : Slots->Types)
96 NumberedTypes.insert(
97 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
98}
99
Chris Lattnerac161bf2009-01-02 07:01:27 +0000100/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
101/// module.
102bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +0000103 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
104 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
105
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
Chris Lattnerac161bf2009-01-02 07:01:27 +0000208 // Look for intrinsic functions and CallInst that need to be upgraded
209 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000210 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000211
Manman Ren8b4306c2013-12-02 21:29:56 +0000212 UpgradeDebugInfo(*M);
213
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000214 if (!Slots)
215 return false;
216 // Initialize the slot mapping.
217 // Because by this point we've parsed and validated everything, we can "steal"
218 // the mapping from LLParser as it doesn't need it anymore.
219 Slots->GlobalValues = std::move(NumberedVals);
220 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000221 for (const auto &I : NamedTypes)
222 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
223 for (const auto &I : NumberedTypes)
224 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000225
Chris Lattnerac161bf2009-01-02 07:01:27 +0000226 return false;
227}
228
229//===----------------------------------------------------------------------===//
230// Top-Level Entities
231//===----------------------------------------------------------------------===//
232
233bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000234 while (1) {
235 switch (Lex.getKind()) {
236 default: return TokError("expected top-level entity");
237 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000238 case lltok::kw_declare: if (ParseDeclare()) return true; break;
239 case lltok::kw_define: if (ParseDefine()) return true; break;
240 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
241 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000242 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000243 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000244 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000245 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000246 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000247 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000248 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000249 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000250
251 // The Global variable production with no name can have many different
252 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000253 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000254 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000255 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000256 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000257 case lltok::kw_internal: // OptionalLinkage
258 case lltok::kw_weak: // OptionalLinkage
259 case lltok::kw_weak_odr: // OptionalLinkage
260 case lltok::kw_linkonce: // OptionalLinkage
261 case lltok::kw_linkonce_odr: // OptionalLinkage
262 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000263 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000264 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000265 case lltok::kw_external: // OptionalLinkage
266 case lltok::kw_default: // OptionalVisibility
267 case lltok::kw_hidden: // OptionalVisibility
268 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000269 case lltok::kw_dllimport: // OptionalDLLStorageClass
270 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000271 case lltok::kw_thread_local: // OptionalThreadLocal
272 case lltok::kw_addrspace: // OptionalAddrSpace
273 case lltok::kw_constant: // GlobalType
274 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000275 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000276 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000277 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000278 bool HasLinkage;
279 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000281 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000282 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000283 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000284 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000285 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000286 return true;
287 break;
288 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000289
290 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000291 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
292 case lltok::kw_uselistorder_bb:
293 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000294 }
295 }
296}
297
298
299/// toplevelentity
300/// ::= 'module' 'asm' STRINGCONSTANT
301bool LLParser::ParseModuleAsm() {
302 assert(Lex.getKind() == lltok::kw_module);
303 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000304
305 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000306 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
307 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000308
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000309 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000310 return false;
311}
312
313/// toplevelentity
314/// ::= 'target' 'triple' '=' STRINGCONSTANT
315/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
316bool LLParser::ParseTargetDefinition() {
317 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000318 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 switch (Lex.Lex()) {
320 default: return TokError("unknown target property");
321 case lltok::kw_triple:
322 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000323 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
324 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000326 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return false;
328 case lltok::kw_datalayout:
329 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000330 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
331 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000333 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000334 return false;
335 }
336}
337
Bill Wendling706d3d62012-11-28 08:41:48 +0000338/// toplevelentity
339/// ::= 'deplibs' '=' '[' ']'
340/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
341/// FIXME: Remove in 4.0. Currently parse, but ignore.
342bool LLParser::ParseDepLibs() {
343 assert(Lex.getKind() == lltok::kw_deplibs);
344 Lex.Lex();
345 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
346 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
347 return true;
348
349 if (EatIfPresent(lltok::rsquare))
350 return false;
351
352 do {
353 std::string Str;
354 if (ParseStringConstant(Str)) return true;
355 } while (EatIfPresent(lltok::comma));
356
357 return ParseToken(lltok::rsquare, "expected ']' at end of list");
358}
359
Dan Gohman466876b2009-08-12 23:32:33 +0000360/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000361/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000362bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000363 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000364 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000365 Lex.Lex(); // eat LocalVarID;
366
367 if (ParseToken(lltok::equal, "expected '=' after name") ||
368 ParseToken(lltok::kw_type, "expected 'type' after '='"))
369 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370
Craig Topper2617dcc2014-04-15 06:32:26 +0000371 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000372 if (ParseStructDefinition(TypeLoc, "",
373 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000374
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000375 if (!isa<StructType>(Result)) {
376 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
377 if (Entry.first)
378 return Error(TypeLoc, "non-struct types may not be recursive");
379 Entry.first = Result;
380 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000382
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383 return false;
384}
385
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000386
Chris Lattnerac161bf2009-01-02 07:01:27 +0000387/// toplevelentity
388/// ::= LocalVar '=' 'type' type
389bool LLParser::ParseNamedType() {
390 std::string Name = Lex.getStrVal();
391 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000392 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000393
Chris Lattner3822f632009-01-02 08:05:26 +0000394 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000395 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000396 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000397
Craig Topper2617dcc2014-04-15 06:32:26 +0000398 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000399 if (ParseStructDefinition(NameLoc, Name,
400 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000401
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000402 if (!isa<StructType>(Result)) {
403 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
404 if (Entry.first)
405 return Error(NameLoc, "non-struct types may not be recursive");
406 Entry.first = Result;
407 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000408 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000410 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000411}
412
413
414/// toplevelentity
415/// ::= 'declare' FunctionHeader
416bool LLParser::ParseDeclare() {
417 assert(Lex.getKind() == lltok::kw_declare);
418 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000419
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420 Function *F;
421 return ParseFunctionHeader(F, false);
422}
423
424/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000425/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000426bool LLParser::ParseDefine() {
427 assert(Lex.getKind() == lltok::kw_define);
428 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000429
Chris Lattnerac161bf2009-01-02 07:01:27 +0000430 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000431 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000432 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000433 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434}
435
Chris Lattner3822f632009-01-02 08:05:26 +0000436/// ParseGlobalType
437/// ::= 'constant'
438/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000439bool LLParser::ParseGlobalType(bool &IsConstant) {
440 if (Lex.getKind() == lltok::kw_constant)
441 IsConstant = true;
442 else if (Lex.getKind() == lltok::kw_global)
443 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000444 else {
445 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000446 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000447 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448 Lex.Lex();
449 return false;
450}
451
Dan Gohman466876b2009-08-12 23:32:33 +0000452/// ParseUnnamedGlobal:
453/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000454/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
455/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000456/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000457/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
458/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000459bool LLParser::ParseUnnamedGlobal() {
460 unsigned VarID = NumberedVals.size();
461 std::string Name;
462 LocTy NameLoc = Lex.getLoc();
463
464 // Handle the GlobalID form.
465 if (Lex.getKind() == lltok::GlobalID) {
466 if (Lex.getUIntVal() != VarID)
467 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000468 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000469 Lex.Lex(); // eat GlobalID;
470
471 if (ParseToken(lltok::equal, "expected '=' after name"))
472 return true;
473 }
474
475 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000476 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000477 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000478 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000479 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000480 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000481 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000482 ParseOptionalThreadLocal(TLM) ||
483 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000484 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000485
Rafael Espindola464fe022014-07-30 22:51:54 +0000486 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000487 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000488 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000489 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000490 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000491}
492
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493/// ParseNamedGlobal:
494/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000495/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
496/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000497bool LLParser::ParseNamedGlobal() {
498 assert(Lex.getKind() == lltok::GlobalVar);
499 LocTy NameLoc = Lex.getLoc();
500 std::string Name = Lex.getStrVal();
501 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Chris Lattnerac161bf2009-01-02 07:01:27 +0000503 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000504 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000505 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000506 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000507 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
508 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000509 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000510 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000511 ParseOptionalThreadLocal(TLM) ||
512 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000513 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000514
Rafael Espindola464fe022014-07-30 22:51:54 +0000515 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000516 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000517 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000518
519 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000520 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521}
522
David Majnemerdad0a642014-06-27 18:19:56 +0000523bool LLParser::parseComdat() {
524 assert(Lex.getKind() == lltok::ComdatVar);
525 std::string Name = Lex.getStrVal();
526 LocTy NameLoc = Lex.getLoc();
527 Lex.Lex();
528
529 if (ParseToken(lltok::equal, "expected '=' here"))
530 return true;
531
532 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
533 return TokError("expected comdat type");
534
535 Comdat::SelectionKind SK;
536 switch (Lex.getKind()) {
537 default:
538 return TokError("unknown selection kind");
539 case lltok::kw_any:
540 SK = Comdat::Any;
541 break;
542 case lltok::kw_exactmatch:
543 SK = Comdat::ExactMatch;
544 break;
545 case lltok::kw_largest:
546 SK = Comdat::Largest;
547 break;
548 case lltok::kw_noduplicates:
549 SK = Comdat::NoDuplicates;
550 break;
551 case lltok::kw_samesize:
552 SK = Comdat::SameSize;
553 break;
554 }
555 Lex.Lex();
556
557 // See if the comdat was forward referenced, if so, use the comdat.
558 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
559 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
560 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
561 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
562
563 Comdat *C;
564 if (I != ComdatSymTab.end())
565 C = &I->second;
566 else
567 C = M->getOrInsertComdat(Name);
568 C->setSelectionKind(SK);
569
570 return false;
571}
572
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000573// MDString:
574// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000575bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000576 std::string Str;
577 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000578 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000579 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000580 return false;
581}
582
583// MDNode:
584// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000585bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000586 // !{ ..., !42, ... }
587 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000588 if (ParseUInt32(MID))
589 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000590
Chris Lattner8eff0152010-04-01 05:14:45 +0000591 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000592 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000593 Result = NumberedMetadata[MID];
594 return false;
595 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000596
Chris Lattner8eff0152010-04-01 05:14:45 +0000597 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000598 auto &FwdRef = ForwardRefMDNodes[MID];
599 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000600
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000601 Result = FwdRef.first.get();
602 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000604}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000605
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000606/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000607/// !foo = !{ !1, !2 }
608bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000609 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000610 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000611 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000612
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000613 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000614 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000615 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000616 return true;
617
Dan Gohman2637cc12010-07-21 23:38:33 +0000618 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000619 if (Lex.getKind() != lltok::rbrace)
620 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000621 if (ParseToken(lltok::exclaim, "Expected '!' here"))
622 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000623
Craig Topper2617dcc2014-04-15 06:32:26 +0000624 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000625 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000626 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000627 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000628
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000629 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000630}
631
Devang Patel39e64d42009-07-01 19:21:12 +0000632/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000633/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000634bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000635 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000636 Lex.Lex();
637 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000638
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000639 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000640 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000641 ParseToken(lltok::equal, "expected '=' here"))
642 return true;
643
644 // Detect common error, from old metadata syntax.
645 if (Lex.getKind() == lltok::Type)
646 return TokError("unexpected type in metadata definition");
647
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000648 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000649 if (Lex.getKind() == lltok::MetadataVar) {
650 if (ParseSpecializedMDNode(Init, IsDistinct))
651 return true;
652 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
653 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000654 return true;
655
Chris Lattnerfc58af22009-12-30 04:51:58 +0000656 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000657 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000658 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000659 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000660 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000661
Chris Lattnerfc58af22009-12-30 04:51:58 +0000662 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
663 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000664 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000665 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000666 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000667 }
668
Devang Patel39e64d42009-07-01 19:21:12 +0000669 return false;
670}
671
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000672static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
673 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
674 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
675}
676
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000678/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
679/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000680/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000681///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000682/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000683/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000684///
Eric Christopher536f0a92015-05-28 23:07:39 +0000685/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000686///
Rafael Espindola464fe022014-07-30 22:51:54 +0000687bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000688 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000689 GlobalVariable::ThreadLocalMode TLM,
690 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000691 assert(Lex.getKind() == lltok::kw_alias);
692 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000693
Rafael Espindola78527052013-10-06 15:10:43 +0000694 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
695
Rafael Espindolacaa43562013-10-09 16:07:32 +0000696 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000697 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000698
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000699 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000700 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000701 "symbol with local linkage must have default visibility");
702
David Blaikie2f408302015-09-11 03:22:04 +0000703 Type *Ty;
704 LocTy ExplicitTypeLoc = Lex.getLoc();
705 if (ParseType(Ty) ||
706 ParseToken(lltok::comma, "expected comma after alias's type"))
707 return true;
708
Rafael Espindola64c1e182014-06-03 02:41:57 +0000709 Constant *Aliasee;
710 LocTy AliaseeLoc = Lex.getLoc();
711 if (Lex.getKind() != lltok::kw_bitcast &&
712 Lex.getKind() != lltok::kw_getelementptr &&
713 Lex.getKind() != lltok::kw_addrspacecast &&
714 Lex.getKind() != lltok::kw_inttoptr) {
715 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000716 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000717 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000718 // The bitcast dest type is not present, it is implied by the dest type.
719 ValID ID;
720 if (ParseValID(ID))
721 return true;
722 if (ID.Kind != ValID::t_Constant)
723 return Error(AliaseeLoc, "invalid aliasee");
724 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000726
Rafael Espindola64c1e182014-06-03 02:41:57 +0000727 Type *AliaseeType = Aliasee->getType();
728 auto *PTy = dyn_cast<PointerType>(AliaseeType);
729 if (!PTy)
730 return Error(AliaseeLoc, "An alias must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000731 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000732
David Blaikie2f408302015-09-11 03:22:04 +0000733 if (Ty != PTy->getElementType())
734 return Error(
735 ExplicitTypeLoc,
736 "explicit pointee type doesn't match operand's pointee type");
737
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000738 GlobalValue *GVal = nullptr;
739
740 // See if the alias was forward referenced, if so, prepare to replace the
741 // forward reference.
742 if (!Name.empty()) {
743 GVal = M->getNamedValue(Name);
744 if (GVal) {
745 if (!ForwardRefVals.erase(Name))
746 return Error(NameLoc, "redefinition of global '@" + Name + "'");
747 }
748 } else {
749 auto I = ForwardRefValIDs.find(NumberedVals.size());
750 if (I != ForwardRefValIDs.end()) {
751 GVal = I->second.first;
752 ForwardRefValIDs.erase(I);
753 }
754 }
755
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000757 std::unique_ptr<GlobalAlias> GA(
David Blaikie16a2f3e2015-09-14 18:01:59 +0000758 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
759 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000760 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000761 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000762 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000763 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000764
Rafael Espindola54fc2982015-06-17 17:53:31 +0000765 if (Name.empty())
766 NumberedVals.push_back(GA.get());
767
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000768 if (GVal) {
769 // Verify that types agree.
770 if (GVal->getType() != GA->getType())
771 return Error(
772 ExplicitTypeLoc,
773 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
Chris Lattnerac161bf2009-01-02 07:01:27 +0000775 // If they agree, just RAUW the old value with the alias and remove the
776 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000777 GVal->replaceAllUsesWith(GA.get());
778 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Chris Lattnerac161bf2009-01-02 07:01:27 +0000781 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000782 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000783 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000784
Rafael Espindolaaa273822014-05-09 21:49:17 +0000785 // The module owns this now
786 GA.release();
787
Chris Lattnerac161bf2009-01-02 07:01:27 +0000788 return false;
789}
790
791/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000792/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000793/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000794/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000795/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000796/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000797/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000798///
Eric Christopher536f0a92015-05-28 23:07:39 +0000799/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000800/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000801///
802bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
803 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000804 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000805 GlobalVariable::ThreadLocalMode TLM,
806 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000807 if (!isValidVisibilityForLinkage(Visibility, Linkage))
808 return Error(NameLoc,
809 "symbol with local linkage must have default visibility");
810
Chris Lattnerac161bf2009-01-02 07:01:27 +0000811 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000812 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000813 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000814 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
Craig Topper2617dcc2014-04-15 06:32:26 +0000816 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000817 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000818 ParseOptionalToken(lltok::kw_externally_initialized,
819 IsExternallyInitialized,
820 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000821 ParseGlobalType(IsConstant) ||
822 ParseType(Ty, TyLoc))
823 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 // If the linkage is specified and is external, then no initializer is
826 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000827 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000828 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000829 Linkage != GlobalValue::ExternalLinkage)) {
830 if (ParseGlobalValue(Ty, Init))
831 return true;
832 }
833
David Majnemer49b3d9b2015-02-16 08:41:08 +0000834 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000835 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000836
David Majnemer598bd052014-12-09 05:56:09 +0000837 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000838
839 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000840 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000841 GVal = M->getNamedValue(Name);
842 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000843 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000844 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000845 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000847 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000849 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000850 ForwardRefValIDs.erase(I);
851 }
852 }
853
David Majnemer598bd052014-12-09 05:56:09 +0000854 GlobalVariable *GV;
855 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000856 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
857 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000858 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000860 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 return Error(TyLoc,
862 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000863
David Majnemer598bd052014-12-09 05:56:09 +0000864 GV = cast<GlobalVariable>(GVal);
865
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 // Move the forward-reference to the correct spot in the module.
867 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
868 }
869
870 if (Name.empty())
871 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000872
Chris Lattnerac161bf2009-01-02 07:01:27 +0000873 // Set the parsed properties on the global.
874 if (Init)
875 GV->setInitializer(Init);
876 GV->setConstant(IsConstant);
877 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
878 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000879 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000880 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000881 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000882 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000883
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884 // Parse attributes on the global.
885 while (Lex.getKind() == lltok::comma) {
886 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000887
Chris Lattnerac161bf2009-01-02 07:01:27 +0000888 if (Lex.getKind() == lltok::kw_section) {
889 Lex.Lex();
890 GV->setSection(Lex.getStrVal());
891 if (ParseToken(lltok::StringConstant, "expected global section string"))
892 return true;
893 } else if (Lex.getKind() == lltok::kw_align) {
894 unsigned Alignment;
895 if (ParseOptionalAlignment(Alignment)) return true;
896 GV->setAlignment(Alignment);
897 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000898 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000899 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000900 return true;
901 if (C)
902 GV->setComdat(C);
903 else
904 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 }
906 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000907
Chris Lattnerac161bf2009-01-02 07:01:27 +0000908 return false;
909}
910
Bill Wendling63b88192013-02-06 06:52:58 +0000911/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000912/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000913bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000914 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000915 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000916 Lex.Lex();
917
David Majnemerb39e22b2014-12-09 18:33:57 +0000918 if (Lex.getKind() != lltok::AttrGrpID)
919 return TokError("expected attribute group id");
920
Bill Wendling63b88192013-02-06 06:52:58 +0000921 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000922 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000923 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000924 Lex.Lex();
925
926 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000927 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000928 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000929 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000930 ParseToken(lltok::rbrace, "expected end of attribute group"))
931 return true;
932
Bill Wendlingb32b0412013-02-08 06:32:06 +0000933 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000934 return Error(AttrGrpLoc, "attribute group has no attributes");
935
936 return false;
937}
938
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000940/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000941bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
942 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000943 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000944 bool HaveError = false;
945
946 B.clear();
947
Bill Wendling63b88192013-02-06 06:52:58 +0000948 while (true) {
949 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000950 if (Token == lltok::kw_builtin)
951 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000952 switch (Token) {
953 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000954 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000955 return Error(Lex.getLoc(), "unterminated attribute group");
956 case lltok::rbrace:
957 // Finished.
958 return false;
959
Bill Wendlingb32b0412013-02-08 06:32:06 +0000960 case lltok::AttrGrpID: {
961 // Allow a function to reference an attribute group:
962 //
963 // define void @foo() #1 { ... }
964 if (inAttrGrp)
965 HaveError |=
966 Error(Lex.getLoc(),
967 "cannot have an attribute group reference in an attribute group");
968
969 unsigned AttrGrpNum = Lex.getUIntVal();
970 if (inAttrGrp) break;
971
972 // Save the reference to the attribute group. We'll fill it in later.
973 FwdRefAttrGrps.push_back(AttrGrpNum);
974 break;
975 }
Bill Wendling63b88192013-02-06 06:52:58 +0000976 // Target-dependent attributes:
977 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000978 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000979 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000980 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000981 }
982
983 // Target-independent attributes:
984 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000985 // As a hack, we allow function alignment to be initially parsed as an
986 // attribute on a function declaration/definition or added to an attribute
987 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000988 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000989 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000990 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000991 if (ParseToken(lltok::equal, "expected '=' here") ||
992 ParseUInt32(Alignment))
993 return true;
994 } else {
995 if (ParseOptionalAlignment(Alignment))
996 return true;
997 }
Bill Wendling63b88192013-02-06 06:52:58 +0000998 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000999 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001000 }
1001 case lltok::kw_alignstack: {
1002 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001003 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001004 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001005 if (ParseToken(lltok::equal, "expected '=' here") ||
1006 ParseUInt32(Alignment))
1007 return true;
1008 } else {
1009 if (ParseOptionalStackAlignment(Alignment))
1010 return true;
1011 }
Bill Wendling63b88192013-02-06 06:52:58 +00001012 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001013 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001014 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001015 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1016 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1017 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1018 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1019 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001020 case lltok::kw_inaccessiblememonly:
1021 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1022 case lltok::kw_inaccessiblemem_or_argmemonly:
1023 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001024 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1025 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1026 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1027 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1028 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1029 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1030 case lltok::kw_noimplicitfloat:
1031 B.addAttribute(Attribute::NoImplicitFloat); break;
1032 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1033 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1034 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1035 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001036 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001037 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1038 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1039 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1040 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1041 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1042 case lltok::kw_returns_twice:
1043 B.addAttribute(Attribute::ReturnsTwice); break;
1044 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1045 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1046 case lltok::kw_sspstrong:
1047 B.addAttribute(Attribute::StackProtectStrong); break;
1048 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1049 case lltok::kw_sanitize_address:
1050 B.addAttribute(Attribute::SanitizeAddress); break;
1051 case lltok::kw_sanitize_thread:
1052 B.addAttribute(Attribute::SanitizeThread); break;
1053 case lltok::kw_sanitize_memory:
1054 B.addAttribute(Attribute::SanitizeMemory); break;
1055 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001056
1057 // Error handling.
1058 case lltok::kw_inreg:
1059 case lltok::kw_signext:
1060 case lltok::kw_zeroext:
1061 HaveError |=
1062 Error(Lex.getLoc(),
1063 "invalid use of attribute on a function");
1064 break;
1065 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001066 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001067 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001068 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001069 case lltok::kw_nest:
1070 case lltok::kw_noalias:
1071 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001072 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001073 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001074 case lltok::kw_sret:
1075 HaveError |=
1076 Error(Lex.getLoc(),
1077 "invalid use of parameter-only attribute on a function");
1078 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001079 }
1080
1081 Lex.Lex();
1082 }
1083}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084
1085//===----------------------------------------------------------------------===//
1086// GlobalValue Reference/Resolution Routines.
1087//===----------------------------------------------------------------------===//
1088
Karl Schimpf77729782015-09-03 18:06:44 +00001089static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1090 const std::string &Name) {
1091 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1092 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1093 else
1094 return new GlobalVariable(*M, PTy->getElementType(), false,
1095 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1096 nullptr, GlobalVariable::NotThreadLocal,
1097 PTy->getAddressSpace());
1098}
1099
Chris Lattnerac161bf2009-01-02 07:01:27 +00001100/// GetGlobalVal - Get a value with the specified name or ID, creating a
1101/// forward reference record if needed. This can return null if the value
1102/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001103GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001104 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001105 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001106 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001107 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001108 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001109 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001110
Chris Lattnerac161bf2009-01-02 07:01:27 +00001111 // Look this name up in the normal function symbol table.
1112 GlobalValue *Val =
1113 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001114
Chris Lattnerac161bf2009-01-02 07:01:27 +00001115 // If this is a forward reference for the value, see if we already created a
1116 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001117 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001118 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001119 if (I != ForwardRefVals.end())
1120 Val = I->second.first;
1121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001122
Chris Lattnerac161bf2009-01-02 07:01:27 +00001123 // If we have the value in the symbol table or fwd-ref table, return it.
1124 if (Val) {
1125 if (Val->getType() == Ty) return Val;
1126 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001127 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001128 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001129 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001130
Chris Lattnerac161bf2009-01-02 07:01:27 +00001131 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001132 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001133 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1134 return FwdVal;
1135}
1136
Chris Lattner229907c2011-07-18 04:54:35 +00001137GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1138 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001139 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001140 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001141 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001142 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001143
Craig Topper2617dcc2014-04-15 06:32:26 +00001144 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001145
Chris Lattnerac161bf2009-01-02 07:01:27 +00001146 // If this is a forward reference for the value, see if we already created a
1147 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001148 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001149 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001150 if (I != ForwardRefValIDs.end())
1151 Val = I->second.first;
1152 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001153
Chris Lattnerac161bf2009-01-02 07:01:27 +00001154 // If we have the value in the symbol table or fwd-ref table, return it.
1155 if (Val) {
1156 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001157 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001158 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001159 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001161
Chris Lattnerac161bf2009-01-02 07:01:27 +00001162 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001163 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001164 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1165 return FwdVal;
1166}
1167
1168
1169//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001170// Comdat Reference/Resolution Routines.
1171//===----------------------------------------------------------------------===//
1172
1173Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1174 // Look this name up in the comdat symbol table.
1175 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1176 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1177 if (I != ComdatSymTab.end())
1178 return &I->second;
1179
1180 // Otherwise, create a new forward reference for this value and remember it.
1181 Comdat *C = M->getOrInsertComdat(Name);
1182 ForwardRefComdats[Name] = Loc;
1183 return C;
1184}
1185
1186
1187//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001188// Helper Routines.
1189//===----------------------------------------------------------------------===//
1190
1191/// ParseToken - If the current token has the specified kind, eat it and return
1192/// success. Otherwise, emit the specified error and return failure.
1193bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1194 if (Lex.getKind() != T)
1195 return TokError(ErrMsg);
1196 Lex.Lex();
1197 return false;
1198}
1199
Chris Lattner3822f632009-01-02 08:05:26 +00001200/// ParseStringConstant
1201/// ::= StringConstant
1202bool LLParser::ParseStringConstant(std::string &Result) {
1203 if (Lex.getKind() != lltok::StringConstant)
1204 return TokError("expected string constant");
1205 Result = Lex.getStrVal();
1206 Lex.Lex();
1207 return false;
1208}
1209
1210/// ParseUInt32
1211/// ::= uint32
1212bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1214 return TokError("expected integer");
1215 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1216 if (Val64 != unsigned(Val64))
1217 return TokError("expected 32-bit integer (too large)");
1218 Val = Val64;
1219 Lex.Lex();
1220 return false;
1221}
1222
Hal Finkelb0407ba2014-07-18 15:51:28 +00001223/// ParseUInt64
1224/// ::= uint64
1225bool LLParser::ParseUInt64(uint64_t &Val) {
1226 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1227 return TokError("expected integer");
1228 Val = Lex.getAPSIntVal().getLimitedValue();
1229 Lex.Lex();
1230 return false;
1231}
1232
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001233/// ParseTLSModel
1234/// := 'localdynamic'
1235/// := 'initialexec'
1236/// := 'localexec'
1237bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1238 switch (Lex.getKind()) {
1239 default:
1240 return TokError("expected localdynamic, initialexec or localexec");
1241 case lltok::kw_localdynamic:
1242 TLM = GlobalVariable::LocalDynamicTLSModel;
1243 break;
1244 case lltok::kw_initialexec:
1245 TLM = GlobalVariable::InitialExecTLSModel;
1246 break;
1247 case lltok::kw_localexec:
1248 TLM = GlobalVariable::LocalExecTLSModel;
1249 break;
1250 }
1251
1252 Lex.Lex();
1253 return false;
1254}
1255
1256/// ParseOptionalThreadLocal
1257/// := /*empty*/
1258/// := 'thread_local'
1259/// := 'thread_local' '(' tlsmodel ')'
1260bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1261 TLM = GlobalVariable::NotThreadLocal;
1262 if (!EatIfPresent(lltok::kw_thread_local))
1263 return false;
1264
1265 TLM = GlobalVariable::GeneralDynamicTLSModel;
1266 if (Lex.getKind() == lltok::lparen) {
1267 Lex.Lex();
1268 return ParseTLSModel(TLM) ||
1269 ParseToken(lltok::rparen, "expected ')' after thread local model");
1270 }
1271 return false;
1272}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001273
1274/// ParseOptionalAddrSpace
1275/// := /*empty*/
1276/// := 'addrspace' '(' uint32 ')'
1277bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1278 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001279 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001280 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001281 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001282 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001283 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001284}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001285
Artur Pilipenko17376c42015-08-03 14:31:49 +00001286/// ParseStringAttribute
1287/// := StringConstant
1288/// := StringConstant '=' StringConstant
1289bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1290 std::string Attr = Lex.getStrVal();
1291 Lex.Lex();
1292 std::string Val;
1293 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1294 return true;
1295 B.addAttribute(Attr, Val);
1296 return false;
1297}
1298
Bill Wendling34c2eb22012-12-04 23:40:58 +00001299/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1300bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1301 bool HaveError = false;
1302
1303 B.clear();
1304
1305 while (1) {
1306 lltok::Kind Token = Lex.getKind();
1307 switch (Token) {
1308 default: // End of attributes.
1309 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001310 case lltok::StringConstant: {
1311 if (ParseStringAttribute(B))
1312 return true;
1313 continue;
1314 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001315 case lltok::kw_align: {
1316 unsigned Alignment;
1317 if (ParseOptionalAlignment(Alignment))
1318 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001319 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001320 continue;
1321 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001322 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001323 case lltok::kw_dereferenceable: {
1324 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001325 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001326 return true;
1327 B.addDereferenceableAttr(Bytes);
1328 continue;
1329 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001330 case lltok::kw_dereferenceable_or_null: {
1331 uint64_t Bytes;
1332 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1333 return true;
1334 B.addDereferenceableOrNullAttr(Bytes);
1335 continue;
1336 }
Reid Klecknera534a382013-12-19 02:14:12 +00001337 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001338 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1339 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1340 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1341 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001342 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001343 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1344 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001345 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001346 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1347 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1348 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001349
Stephen Lin7577ed52013-04-20 13:16:13 +00001350 case lltok::kw_alignstack:
1351 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001352 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001353 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001354 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001355 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001356 case lltok::kw_minsize:
1357 case lltok::kw_naked:
1358 case lltok::kw_nobuiltin:
1359 case lltok::kw_noduplicate:
1360 case lltok::kw_noimplicitfloat:
1361 case lltok::kw_noinline:
1362 case lltok::kw_nonlazybind:
1363 case lltok::kw_noredzone:
1364 case lltok::kw_noreturn:
1365 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001366 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001367 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001368 case lltok::kw_returns_twice:
1369 case lltok::kw_sanitize_address:
1370 case lltok::kw_sanitize_memory:
1371 case lltok::kw_sanitize_thread:
1372 case lltok::kw_ssp:
1373 case lltok::kw_sspreq:
1374 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001375 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001376 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001377 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1378 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001379 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001380
Bill Wendling34c2eb22012-12-04 23:40:58 +00001381 Lex.Lex();
1382 }
1383}
1384
1385/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1386bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1387 bool HaveError = false;
1388
1389 B.clear();
1390
1391 while (1) {
1392 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001393 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001394 default: // End of attributes.
1395 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001396 case lltok::StringConstant: {
1397 if (ParseStringAttribute(B))
1398 return true;
1399 continue;
1400 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001401 case lltok::kw_dereferenceable: {
1402 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001403 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001404 return true;
1405 B.addDereferenceableAttr(Bytes);
1406 continue;
1407 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001408 case lltok::kw_dereferenceable_or_null: {
1409 uint64_t Bytes;
1410 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1411 return true;
1412 B.addDereferenceableOrNullAttr(Bytes);
1413 continue;
1414 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001415 case lltok::kw_align: {
1416 unsigned Alignment;
1417 if (ParseOptionalAlignment(Alignment))
1418 return true;
1419 B.addAlignmentAttr(Alignment);
1420 continue;
1421 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001422 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1423 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001424 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001425 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1426 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001427
Bill Wendling34c2eb22012-12-04 23:40:58 +00001428 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001429 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001430 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001431 case lltok::kw_nest:
1432 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001433 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001434 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001435 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001436 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001437
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001438 case lltok::kw_alignstack:
1439 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001440 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001441 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001442 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001443 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001444 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001445 case lltok::kw_minsize:
1446 case lltok::kw_naked:
1447 case lltok::kw_nobuiltin:
1448 case lltok::kw_noduplicate:
1449 case lltok::kw_noimplicitfloat:
1450 case lltok::kw_noinline:
1451 case lltok::kw_nonlazybind:
1452 case lltok::kw_noredzone:
1453 case lltok::kw_noreturn:
1454 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001455 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001456 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001457 case lltok::kw_returns_twice:
1458 case lltok::kw_sanitize_address:
1459 case lltok::kw_sanitize_memory:
1460 case lltok::kw_sanitize_thread:
1461 case lltok::kw_ssp:
1462 case lltok::kw_sspreq:
1463 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001464 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001465 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001466 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001467 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001468
1469 case lltok::kw_readnone:
1470 case lltok::kw_readonly:
1471 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001472 }
1473
Chris Lattnerac161bf2009-01-02 07:01:27 +00001474 Lex.Lex();
1475 }
1476}
1477
1478/// ParseOptionalLinkage
1479/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001480/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001481/// ::= 'internal'
1482/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001483/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001484/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001485/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001486/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001487/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001488/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001489/// ::= 'extern_weak'
1490/// ::= 'external'
1491bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1492 HasLinkage = false;
1493 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001494 default: Res=GlobalValue::ExternalLinkage; return false;
1495 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001496 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1497 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1498 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1499 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1500 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001501 case lltok::kw_available_externally:
1502 Res = GlobalValue::AvailableExternallyLinkage;
1503 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001504 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001505 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001506 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1507 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001508 }
1509 Lex.Lex();
1510 HasLinkage = true;
1511 return false;
1512}
1513
1514/// ParseOptionalVisibility
1515/// ::= /*empty*/
1516/// ::= 'default'
1517/// ::= 'hidden'
1518/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001519///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001520bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1521 switch (Lex.getKind()) {
1522 default: Res = GlobalValue::DefaultVisibility; return false;
1523 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1524 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1525 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1526 }
1527 Lex.Lex();
1528 return false;
1529}
1530
Nico Rieck7157bb72014-01-14 15:22:47 +00001531/// ParseOptionalDLLStorageClass
1532/// ::= /*empty*/
1533/// ::= 'dllimport'
1534/// ::= 'dllexport'
1535///
1536bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1537 switch (Lex.getKind()) {
1538 default: Res = GlobalValue::DefaultStorageClass; return false;
1539 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1540 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1541 }
1542 Lex.Lex();
1543 return false;
1544}
1545
Chris Lattnerac161bf2009-01-02 07:01:27 +00001546/// ParseOptionalCallingConv
1547/// ::= /*empty*/
1548/// ::= 'ccc'
1549/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001550/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001551/// ::= 'coldcc'
1552/// ::= 'x86_stdcallcc'
1553/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001554/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001555/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001556/// ::= 'arm_apcscc'
1557/// ::= 'arm_aapcscc'
1558/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001559/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001560/// ::= 'avr_intrcc'
1561/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001562/// ::= 'ptx_kernel'
1563/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001564/// ::= 'spir_func'
1565/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001566/// ::= 'x86_64_sysvcc'
1567/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001568/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001569/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001570/// ::= 'preserve_mostcc'
1571/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001572/// ::= 'ghccc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001573/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001574/// ::= 'hhvmcc'
1575/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001576/// ::= 'cxx_fast_tlscc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001577/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001578///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001579bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001580 switch (Lex.getKind()) {
1581 default: CC = CallingConv::C; return false;
1582 case lltok::kw_ccc: CC = CallingConv::C; break;
1583 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1584 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1585 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1586 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001587 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001588 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001589 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1590 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1591 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001592 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001593 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1594 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001595 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1596 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001597 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1598 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001599 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001600 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1601 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001602 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001603 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001604 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1605 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001606 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001607 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001608 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1609 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001610 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001611 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001612 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001613 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001614 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001615 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001616
Chris Lattnerac161bf2009-01-02 07:01:27 +00001617 Lex.Lex();
1618 return false;
1619}
1620
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001621/// ParseMetadataAttachment
1622/// ::= !dbg !42
1623bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1624 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1625
1626 std::string Name = Lex.getStrVal();
1627 Kind = M->getMDKindID(Name);
1628 Lex.Lex();
1629
1630 return ParseMDNode(MD);
1631}
1632
Chris Lattner5c427632009-12-30 05:31:19 +00001633/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001634/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001635bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001636 do {
1637 if (Lex.getKind() != lltok::MetadataVar)
1638 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001639
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001640 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001641 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001642 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001643 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001644
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001645 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001646 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001647 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001648
Chris Lattner596760d2009-12-29 21:25:40 +00001649 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001650 } while (EatIfPresent(lltok::comma));
1651 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001652}
1653
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001654/// ParseOptionalFunctionMetadata
1655/// ::= (!dbg !57)*
1656bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1657 while (Lex.getKind() == lltok::MetadataVar) {
1658 unsigned MDK;
1659 MDNode *N;
1660 if (ParseMetadataAttachment(MDK, N))
1661 return true;
1662
1663 F.setMetadata(MDK, N);
1664 }
1665 return false;
1666}
1667
Chris Lattnerac161bf2009-01-02 07:01:27 +00001668/// ParseOptionalAlignment
1669/// ::= /* empty */
1670/// ::= 'align' 4
1671bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1672 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001673 if (!EatIfPresent(lltok::kw_align))
1674 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001675 LocTy AlignLoc = Lex.getLoc();
1676 if (ParseUInt32(Alignment)) return true;
1677 if (!isPowerOf2_32(Alignment))
1678 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001679 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001680 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001681 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682}
1683
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001684/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001685/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001686/// ::= AttrKind '(' 4 ')'
1687///
1688/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1689bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1690 uint64_t &Bytes) {
1691 assert((AttrKind == lltok::kw_dereferenceable ||
1692 AttrKind == lltok::kw_dereferenceable_or_null) &&
1693 "contract!");
1694
Hal Finkelb0407ba2014-07-18 15:51:28 +00001695 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001696 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001697 return false;
1698 LocTy ParenLoc = Lex.getLoc();
1699 if (!EatIfPresent(lltok::lparen))
1700 return Error(ParenLoc, "expected '('");
1701 LocTy DerefLoc = Lex.getLoc();
1702 if (ParseUInt64(Bytes)) return true;
1703 ParenLoc = Lex.getLoc();
1704 if (!EatIfPresent(lltok::rparen))
1705 return Error(ParenLoc, "expected ')'");
1706 if (!Bytes)
1707 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1708 return false;
1709}
1710
Chris Lattnerb2f39502009-12-30 05:44:30 +00001711/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001712/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001713/// ::= ',' align 4
1714///
1715/// This returns with AteExtraComma set to true if it ate an excess comma at the
1716/// end.
1717bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1718 bool &AteExtraComma) {
1719 AteExtraComma = false;
1720 while (EatIfPresent(lltok::comma)) {
1721 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001722 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001723 AteExtraComma = true;
1724 return false;
1725 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001726
Chris Lattner95b0ff42010-04-23 00:50:50 +00001727 if (Lex.getKind() != lltok::kw_align)
1728 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001729
Chris Lattner95b0ff42010-04-23 00:50:50 +00001730 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001731 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001732
Devang Patelea8a4b92009-09-17 23:04:48 +00001733 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001734}
1735
Eli Friedmanfee02c62011-07-25 23:16:38 +00001736/// ParseScopeAndOrdering
1737/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1738/// else: ::=
1739///
1740/// This sets Scope and Ordering to the parsed values.
1741bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1742 AtomicOrdering &Ordering) {
1743 if (!isAtomic)
1744 return false;
1745
1746 Scope = CrossThread;
1747 if (EatIfPresent(lltok::kw_singlethread))
1748 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001749
1750 return ParseOrdering(Ordering);
1751}
1752
1753/// ParseOrdering
1754/// ::= AtomicOrdering
1755///
1756/// This sets Ordering to the parsed value.
1757bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001758 switch (Lex.getKind()) {
1759 default: return TokError("Expected ordering on atomic instruction");
1760 case lltok::kw_unordered: Ordering = Unordered; break;
1761 case lltok::kw_monotonic: Ordering = Monotonic; break;
1762 case lltok::kw_acquire: Ordering = Acquire; break;
1763 case lltok::kw_release: Ordering = Release; break;
1764 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1765 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1766 }
1767 Lex.Lex();
1768 return false;
1769}
1770
Charles Davisbe5557e2010-02-12 00:31:15 +00001771/// ParseOptionalStackAlignment
1772/// ::= /* empty */
1773/// ::= 'alignstack' '(' 4 ')'
1774bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1775 Alignment = 0;
1776 if (!EatIfPresent(lltok::kw_alignstack))
1777 return false;
1778 LocTy ParenLoc = Lex.getLoc();
1779 if (!EatIfPresent(lltok::lparen))
1780 return Error(ParenLoc, "expected '('");
1781 LocTy AlignLoc = Lex.getLoc();
1782 if (ParseUInt32(Alignment)) return true;
1783 ParenLoc = Lex.getLoc();
1784 if (!EatIfPresent(lltok::rparen))
1785 return Error(ParenLoc, "expected ')'");
1786 if (!isPowerOf2_32(Alignment))
1787 return Error(AlignLoc, "stack alignment is not a power of two");
1788 return false;
1789}
Devang Patelea8a4b92009-09-17 23:04:48 +00001790
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001791/// ParseIndexList - This parses the index list for an insert/extractvalue
1792/// instruction. This sets AteExtraComma in the case where we eat an extra
1793/// comma at the end of the line and find that it is followed by metadata.
1794/// Clients that don't allow metadata can call the version of this function that
1795/// only takes one argument.
1796///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797/// ParseIndexList
1798/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001799///
1800bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1801 bool &AteExtraComma) {
1802 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001803
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 if (Lex.getKind() != lltok::comma)
1805 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001806
Chris Lattner3822f632009-01-02 08:05:26 +00001807 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001808 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001809 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001810 AteExtraComma = true;
1811 return false;
1812 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001813 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001814 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001815 Indices.push_back(Idx);
1816 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001817
Chris Lattnerac161bf2009-01-02 07:01:27 +00001818 return false;
1819}
1820
1821//===----------------------------------------------------------------------===//
1822// Type Parsing.
1823//===----------------------------------------------------------------------===//
1824
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001825/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001826bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001827 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001828 switch (Lex.getKind()) {
1829 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001830 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001832 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001833 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001834 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001835 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001836 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001837 // Type ::= StructType
1838 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001839 return true;
1840 break;
1841 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001842 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001843 Lex.Lex(); // eat the lsquare.
1844 if (ParseArrayVectorType(Result, false))
1845 return true;
1846 break;
1847 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001848 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001849 Lex.Lex();
1850 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001851 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001852 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 } else if (ParseArrayVectorType(Result, true))
1855 return true;
1856 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001857 case lltok::LocalVar: {
1858 // Type ::= %foo
1859 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001860
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001861 // If the type hasn't been defined yet, create a forward definition and
1862 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001863 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001864 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001865 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001866 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868 Lex.Lex();
1869 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001870 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001871
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001872 case lltok::LocalVarID: {
1873 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001874 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001875
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001876 // If the type hasn't been defined yet, create a forward definition and
1877 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001878 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001879 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001880 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001882 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001883 Lex.Lex();
1884 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001885 }
1886 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001887
1888 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 while (1) {
1890 switch (Lex.getKind()) {
1891 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892 default:
1893 if (!AllowVoid && Result->isVoidTy())
1894 return Error(TypeLoc, "void type only allowed for function results");
1895 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001896
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001897 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001898 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001899 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901 if (Result->isVoidTy())
1902 return TokError("pointers to void are invalid - use i8* instead");
1903 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001904 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001905 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001906 Lex.Lex();
1907 break;
1908
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001909 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001910 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001911 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001912 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001913 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001914 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001915 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001916 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917 unsigned AddrSpace;
1918 if (ParseOptionalAddrSpace(AddrSpace) ||
1919 ParseToken(lltok::star, "expected '*' in address space"))
1920 return true;
1921
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001922 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923 break;
1924 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001925
Chris Lattnerac161bf2009-01-02 07:01:27 +00001926 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1927 case lltok::lparen:
1928 if (ParseFunctionType(Result))
1929 return true;
1930 break;
1931 }
1932 }
1933}
1934
1935/// ParseParameterList
1936/// ::= '(' ')'
1937/// ::= '(' Arg (',' Arg)* ')'
1938/// Arg
1939/// ::= Type OptionalAttributes Value OptionalAttributes
1940bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001941 PerFunctionState &PFS, bool IsMustTailCall,
1942 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001943 if (ParseToken(lltok::lparen, "expected '(' in call"))
1944 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001945
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001946 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001947 while (Lex.getKind() != lltok::rparen) {
1948 // If this isn't the first argument, we need a comma.
1949 if (!ArgList.empty() &&
1950 ParseToken(lltok::comma, "expected ',' in argument list"))
1951 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001952
Reid Kleckner83498642014-08-26 00:33:28 +00001953 // Parse an ellipsis if this is a musttail call in a variadic function.
1954 if (Lex.getKind() == lltok::dotdotdot) {
1955 const char *Msg = "unexpected ellipsis in argument list for ";
1956 if (!IsMustTailCall)
1957 return TokError(Twine(Msg) + "non-musttail call");
1958 if (!InVarArgsFunc)
1959 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1960 Lex.Lex(); // Lex the '...', it is purely for readability.
1961 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1962 }
1963
Chris Lattnerac161bf2009-01-02 07:01:27 +00001964 // Parse the argument.
1965 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001966 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001967 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001968 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001969 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001971
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001972 if (ArgTy->isMetadataTy()) {
1973 if (ParseMetadataAsValue(V, PFS))
1974 return true;
1975 } else {
1976 // Otherwise, handle normal operands.
1977 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1978 return true;
1979 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001980 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1981 AttrIndex++,
1982 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 }
1984
Reid Kleckner83498642014-08-26 00:33:28 +00001985 if (IsMustTailCall && InVarArgsFunc)
1986 return TokError("expected '...' at end of argument list for musttail call "
1987 "in varargs function");
1988
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 Lex.Lex(); // Lex the ')'.
1990 return false;
1991}
1992
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001993/// ParseOptionalOperandBundles
1994/// ::= /*empty*/
1995/// ::= '[' OperandBundle [, OperandBundle ]* ']'
1996///
1997/// OperandBundle
1998/// ::= bundle-tag '(' ')'
1999/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2000///
2001/// bundle-tag ::= String Constant
2002bool LLParser::ParseOptionalOperandBundles(
2003 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2004 LocTy BeginLoc = Lex.getLoc();
2005 if (!EatIfPresent(lltok::lsquare))
2006 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002007
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002008 while (Lex.getKind() != lltok::rsquare) {
2009 // If this isn't the first operand bundle, we need a comma.
2010 if (!BundleList.empty() &&
2011 ParseToken(lltok::comma, "expected ',' in input list"))
2012 return true;
2013
2014 std::string Tag;
2015 if (ParseStringConstant(Tag))
2016 return true;
2017
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002018 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2019 return true;
2020
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002021 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002022 while (Lex.getKind() != lltok::rparen) {
2023 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002024 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002025 ParseToken(lltok::comma, "expected ',' in input list"))
2026 return true;
2027
2028 Type *Ty = nullptr;
2029 Value *Input = nullptr;
2030 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2031 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002032 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002033 }
2034
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002035 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2036
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002037 Lex.Lex(); // Lex the ')'.
2038 }
2039
2040 if (BundleList.empty())
2041 return Error(BeginLoc, "operand bundle set must not be empty");
2042
2043 Lex.Lex(); // Lex the ']'.
2044 return false;
2045}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046
Chris Lattner2ed06b42009-01-05 18:34:07 +00002047/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002048/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002049/// ::= '(' ArgTypeListI ')'
2050/// ArgTypeListI
2051/// ::= /*empty*/
2052/// ::= '...'
2053/// ::= ArgTypeList ',' '...'
2054/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002055///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2057 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 isVarArg = false;
2059 assert(Lex.getKind() == lltok::lparen);
2060 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002061
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 if (Lex.getKind() == lltok::rparen) {
2063 // empty
2064 } else if (Lex.getKind() == lltok::dotdotdot) {
2065 isVarArg = true;
2066 Lex.Lex();
2067 } else {
2068 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002069 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002070 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002072
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002073 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002074 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075
Chris Lattnerfdd87902009-10-05 05:54:46 +00002076 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002077 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002078
Chris Lattnerdef19492011-06-17 06:36:20 +00002079 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080 Name = Lex.getStrVal();
2081 Lex.Lex();
2082 }
Chris Lattner3822f632009-01-02 08:05:26 +00002083
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002084 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002085 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002086
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002087 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002088 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2089 AttrIndex++, Attrs),
2090 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002091
Chris Lattner3822f632009-01-02 08:05:26 +00002092 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002094 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 break;
2097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 // Otherwise must be an argument type.
2100 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002101 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002102
Chris Lattnerfdd87902009-10-05 05:54:46 +00002103 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002104 return Error(TypeLoc, "argument can not have void type");
2105
Chris Lattnerdef19492011-06-17 06:36:20 +00002106 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107 Name = Lex.getStrVal();
2108 Lex.Lex();
2109 } else {
2110 Name = "";
2111 }
Chris Lattner3822f632009-01-02 08:05:26 +00002112
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002114 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002115
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002116 ArgList.emplace_back(
2117 TypeLoc, ArgTy,
2118 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2119 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 }
2121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Chris Lattner3822f632009-01-02 08:05:26 +00002123 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002125
Chris Lattnerac161bf2009-01-02 07:01:27 +00002126/// ParseFunctionType
2127/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002128bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 assert(Lex.getKind() == lltok::lparen);
2130
Chris Lattnerce473c72009-01-05 08:04:33 +00002131 if (!FunctionType::isValidReturnType(Result))
2132 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002133
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002134 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002136 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002138
Chris Lattnerac161bf2009-01-02 07:01:27 +00002139 // Reject names on the arguments lists.
2140 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2141 if (!ArgList[i].Name.empty())
2142 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002143 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002144 return Error(ArgList[i].Loc,
2145 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002147
Jay Foadb804a2b2011-07-12 14:06:48 +00002148 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002150 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002151
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002152 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002153 return false;
2154}
2155
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002156/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2157/// other structs.
2158bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2159 SmallVector<Type*, 8> Elts;
2160 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002161
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002162 Result = StructType::get(Context, Elts, Packed);
2163 return false;
2164}
2165
2166/// ParseStructDefinition - Parse a struct in a 'type' definition.
2167bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2168 std::pair<Type*, LocTy> &Entry,
2169 Type *&ResultTy) {
2170 // If the type was already defined, diagnose the redefinition.
2171 if (Entry.first && !Entry.second.isValid())
2172 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002174 // If we have opaque, just return without filling in the definition for the
2175 // struct. This counts as a definition as far as the .ll file goes.
2176 if (EatIfPresent(lltok::kw_opaque)) {
2177 // This type is being defined, so clear the location to indicate this.
2178 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002179
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002180 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002181 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002182 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002183 ResultTy = Entry.first;
2184 return false;
2185 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002186
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002187 // If the type starts with '<', then it is either a packed struct or a vector.
2188 bool isPacked = EatIfPresent(lltok::less);
2189
2190 // If we don't have a struct, then we have a random type alias, which we
2191 // accept for compatibility with old files. These types are not allowed to be
2192 // forward referenced and not allowed to be recursive.
2193 if (Lex.getKind() != lltok::lbrace) {
2194 if (Entry.first)
2195 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002196
Craig Topper2617dcc2014-04-15 06:32:26 +00002197 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002198 if (isPacked)
2199 return ParseArrayVectorType(ResultTy, true);
2200 return ParseType(ResultTy);
2201 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002202
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002203 // This type is being defined, so clear the location to indicate this.
2204 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002205
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002206 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002207 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002208 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002209
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002210 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002211
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002212 SmallVector<Type*, 8> Body;
2213 if (ParseStructBody(Body) ||
2214 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2215 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002217 STy->setBody(Body, isPacked);
2218 ResultTy = STy;
2219 return false;
2220}
2221
2222
Chris Lattnerac161bf2009-01-02 07:01:27 +00002223/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002224/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002226/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002227/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002228/// ::= '<' '{' Type (',' Type)* '}' '>'
2229bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002230 assert(Lex.getKind() == lltok::lbrace);
2231 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002232
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002233 // Handle the empty struct.
2234 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002236
Chris Lattnerf880ca22009-03-09 04:49:14 +00002237 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002238 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002239 if (ParseType(Ty)) return true;
2240 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002241
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002242 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002243 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Chris Lattner3822f632009-01-02 08:05:26 +00002245 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002246 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002247 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002249 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002250 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002251
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002253 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002255 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256}
2257
2258/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2259/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002260/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002261/// ::= '[' APSINTVAL 'x' Types ']'
2262/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002263bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2265 Lex.getAPSIntVal().getBitWidth() > 64)
2266 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002267
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 LocTy SizeLoc = Lex.getLoc();
2269 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002270 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002271
Chris Lattner3822f632009-01-02 08:05:26 +00002272 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2273 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274
2275 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002276 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002277 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002278
Chris Lattner3822f632009-01-02 08:05:26 +00002279 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2280 "expected end of sequential type"))
2281 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002282
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002284 if (Size == 0)
2285 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 if ((unsigned)Size != Size)
2287 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002288 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002289 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002290 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002292 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002294 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 }
2296 return false;
2297}
2298
2299//===----------------------------------------------------------------------===//
2300// Function Semantic Analysis.
2301//===----------------------------------------------------------------------===//
2302
Chris Lattner3432c622009-10-28 03:39:23 +00002303LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2304 int functionNumber)
2305 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306
2307 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002308 for (Argument &A : F.args())
2309 if (!A.hasName())
2310 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311}
2312
2313LLParser::PerFunctionState::~PerFunctionState() {
2314 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
David Blaikie9ebdc692015-09-21 21:07:50 +00002316 for (const auto &P : ForwardRefVals) {
2317 if (isa<BasicBlock>(P.second.first))
2318 continue;
2319 P.second.first->replaceAllUsesWith(
2320 UndefValue::get(P.second.first->getType()));
2321 delete P.second.first;
2322 }
2323
2324 for (const auto &P : ForwardRefValIDs) {
2325 if (isa<BasicBlock>(P.second.first))
2326 continue;
2327 P.second.first->replaceAllUsesWith(
2328 UndefValue::get(P.second.first->getType()));
2329 delete P.second.first;
2330 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331}
2332
Chris Lattner3432c622009-10-28 03:39:23 +00002333bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002334 if (!ForwardRefVals.empty())
2335 return P.Error(ForwardRefVals.begin()->second.second,
2336 "use of undefined value '%" + ForwardRefVals.begin()->first +
2337 "'");
2338 if (!ForwardRefValIDs.empty())
2339 return P.Error(ForwardRefValIDs.begin()->second.second,
2340 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002341 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 return false;
2343}
2344
2345
2346/// GetVal - Get a value with the specified name or ID, creating a
2347/// forward reference record if needed. This can return null if the value
2348/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002349Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002350 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351 // Look this name up in the normal function symbol table.
2352 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002353
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 // If this is a forward reference for the value, see if we already created a
2355 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002356 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002357 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002358 if (I != ForwardRefVals.end())
2359 Val = I->second.first;
2360 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002361
Chris Lattnerac161bf2009-01-02 07:01:27 +00002362 // If we have the value in the symbol table or fwd-ref table, return it.
2363 if (Val) {
2364 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002365 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 P.Error(Loc, "'%" + Name + "' is not a basic block");
2367 else
2368 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002369 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002370 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002372
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002374 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002376 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002378
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379 // Otherwise, create a new forward reference for this value and remember it.
2380 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002381 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002382 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002383 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002384 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002385 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2388 return FwdVal;
2389}
2390
David Majnemer8a1c45d2015-12-12 05:38:55 +00002391Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002393 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 // If this is a forward reference for the value, see if we already created a
2396 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002397 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002398 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 if (I != ForwardRefValIDs.end())
2400 Val = I->second.first;
2401 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002402
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 // If we have the value in the symbol table or fwd-ref table, return it.
2404 if (Val) {
2405 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002406 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002407 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002409 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002410 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002411 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002413
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002414 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002416 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 // Otherwise, create a new forward reference for this value and remember it.
2420 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002421 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002422 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002423 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002424 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002425 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002426
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2428 return FwdVal;
2429}
2430
2431/// SetInstName - After an instruction is parsed and inserted into its
2432/// basic block, this installs its name.
2433bool LLParser::PerFunctionState::SetInstName(int NameID,
2434 const std::string &NameStr,
2435 LocTy NameLoc, Instruction *Inst) {
2436 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002437 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 if (NameID != -1 || !NameStr.empty())
2439 return P.Error(NameLoc, "instructions returning void cannot have a name");
2440 return false;
2441 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 // If this was a numbered instruction, verify that the instruction is the
2444 // expected value and resolve any forward references.
2445 if (NameStr.empty()) {
2446 // If neither a name nor an ID was specified, just use the next ID.
2447 if (NameID == -1)
2448 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002449
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 if (unsigned(NameID) != NumberedVals.size())
2451 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002452 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453
David Blaikie9ebdc692015-09-21 21:07:50 +00002454 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002456 Value *Sentinel = FI->second.first;
2457 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002458 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002459 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002460
2461 Sentinel->replaceAllUsesWith(Inst);
2462 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002463 ForwardRefValIDs.erase(FI);
2464 }
2465
2466 NumberedVals.push_back(Inst);
2467 return false;
2468 }
2469
2470 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002471 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002473 Value *Sentinel = FI->second.first;
2474 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002475 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002476 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002477
2478 Sentinel->replaceAllUsesWith(Inst);
2479 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480 ForwardRefVals.erase(FI);
2481 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 // Set the name on the instruction.
2484 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002485
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002486 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 NameStr + "'");
2489 return false;
2490}
2491
2492/// GetBB - Get a basic block with the specified name or ID, creating a
2493/// forward reference record if needed.
2494BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2495 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002496 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2497 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498}
2499
2500BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002501 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2502 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503}
2504
2505/// DefineBB - Define the specified basic block, which is either named or
2506/// unnamed. If there is an error, this returns null otherwise it returns
2507/// the block being defined.
2508BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2509 LocTy Loc) {
2510 BasicBlock *BB;
2511 if (Name.empty())
2512 BB = GetBB(NumberedVals.size(), Loc);
2513 else
2514 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002515 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002516
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517 // Move the block to the end of the function. Forward ref'd blocks are
2518 // inserted wherever they happen to be referenced.
2519 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002520
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 // Remove the block from forward ref sets.
2522 if (Name.empty()) {
2523 ForwardRefValIDs.erase(NumberedVals.size());
2524 NumberedVals.push_back(BB);
2525 } else {
2526 // BB forward references are already in the function symbol table.
2527 ForwardRefVals.erase(Name);
2528 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002529
Chris Lattnerac161bf2009-01-02 07:01:27 +00002530 return BB;
2531}
2532
2533//===----------------------------------------------------------------------===//
2534// Constants.
2535//===----------------------------------------------------------------------===//
2536
2537/// ParseValID - Parse an abstract value that doesn't necessarily have a
2538/// type implied. For example, if we parse "4" we don't know what integer type
2539/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002540/// sanity. PFS is used to convert function-local operands of metadata (since
2541/// metadata operands are not just parsed here but also converted to values).
2542/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002543bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 ID.Loc = Lex.getLoc();
2545 switch (Lex.getKind()) {
2546 default: return TokError("expected value token");
2547 case lltok::GlobalID: // @42
2548 ID.UIntVal = Lex.getUIntVal();
2549 ID.Kind = ValID::t_GlobalID;
2550 break;
2551 case lltok::GlobalVar: // @foo
2552 ID.StrVal = Lex.getStrVal();
2553 ID.Kind = ValID::t_GlobalName;
2554 break;
2555 case lltok::LocalVarID: // %42
2556 ID.UIntVal = Lex.getUIntVal();
2557 ID.Kind = ValID::t_LocalID;
2558 break;
2559 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 ID.StrVal = Lex.getStrVal();
2561 ID.Kind = ValID::t_LocalName;
2562 break;
2563 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002564 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 ID.Kind = ValID::t_APSInt;
2566 break;
2567 case lltok::APFloat:
2568 ID.APFloatVal = Lex.getAPFloatVal();
2569 ID.Kind = ValID::t_APFloat;
2570 break;
2571 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002572 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002573 ID.Kind = ValID::t_Constant;
2574 break;
2575 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002576 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 ID.Kind = ValID::t_Constant;
2578 break;
2579 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2580 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2581 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002582 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002583
Chris Lattnerac161bf2009-01-02 07:01:27 +00002584 case lltok::lbrace: {
2585 // ValID ::= '{' ConstVector '}'
2586 Lex.Lex();
2587 SmallVector<Constant*, 16> Elts;
2588 if (ParseGlobalValueVector(Elts) ||
2589 ParseToken(lltok::rbrace, "expected end of struct constant"))
2590 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002591
David Blaikieadbda4b2015-08-03 20:08:41 +00002592 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002593 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002594 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2595 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002596 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 return false;
2598 }
2599 case lltok::less: {
2600 // ValID ::= '<' ConstVector '>' --> Vector.
2601 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2602 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002603 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002604
Chris Lattnerac161bf2009-01-02 07:01:27 +00002605 SmallVector<Constant*, 16> Elts;
2606 LocTy FirstEltLoc = Lex.getLoc();
2607 if (ParseGlobalValueVector(Elts) ||
2608 (isPackedStruct &&
2609 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2610 ParseToken(lltok::greater, "expected end of constant"))
2611 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002612
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002614 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2615 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2616 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002617 ID.UIntVal = Elts.size();
2618 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 return false;
2620 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002621
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 if (Elts.empty())
2623 return Error(ID.Loc, "constant vector must not be empty");
2624
Duncan Sands9dff9be2010-02-15 16:12:20 +00002625 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002626 !Elts[0]->getType()->isFloatingPointTy() &&
2627 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002628 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002629 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002630
Chris Lattnerac161bf2009-01-02 07:01:27 +00002631 // Verify that all the vector elements have the same type.
2632 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2633 if (Elts[i]->getType() != Elts[0]->getType())
2634 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002635 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002636 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002637
Chris Lattner69229312011-02-15 00:14:00 +00002638 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 ID.Kind = ValID::t_Constant;
2640 return false;
2641 }
2642 case lltok::lsquare: { // Array Constant
2643 Lex.Lex();
2644 SmallVector<Constant*, 16> Elts;
2645 LocTy FirstEltLoc = Lex.getLoc();
2646 if (ParseGlobalValueVector(Elts) ||
2647 ParseToken(lltok::rsquare, "expected end of array constant"))
2648 return true;
2649
2650 // Handle empty element.
2651 if (Elts.empty()) {
2652 // Use undef instead of an array because it's inconvenient to determine
2653 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002654 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 return false;
2656 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002659 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002660 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002661
Owen Anderson4056ca92009-07-29 22:17:13 +00002662 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663
Chris Lattnerac161bf2009-01-02 07:01:27 +00002664 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002665 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 if (Elts[i]->getType() != Elts[0]->getType())
2667 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002668 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002669 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002671
Jay Foad83be3612011-06-22 09:24:39 +00002672 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002673 ID.Kind = ValID::t_Constant;
2674 return false;
2675 }
2676 case lltok::kw_c: // c "foo"
2677 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002678 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2679 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2681 ID.Kind = ValID::t_Constant;
2682 return false;
2683
2684 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002685 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2686 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002687 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 Lex.Lex();
2689 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002690 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002691 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002692 ParseStringConstant(ID.StrVal) ||
2693 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 ParseToken(lltok::StringConstant, "expected constraint string"))
2695 return true;
2696 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002697 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002698 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 ID.Kind = ValID::t_InlineAsm;
2700 return false;
2701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002702
Chris Lattner3432c622009-10-28 03:39:23 +00002703 case lltok::kw_blockaddress: {
2704 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2705 Lex.Lex();
2706
2707 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002708
Chris Lattner3432c622009-10-28 03:39:23 +00002709 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2710 ParseValID(Fn) ||
2711 ParseToken(lltok::comma, "expected comma in block address expression")||
2712 ParseValID(Label) ||
2713 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2714 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002715
Chris Lattner3432c622009-10-28 03:39:23 +00002716 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2717 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002718 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002719 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002720
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002721 // Try to find the function (but skip it if it's forward-referenced).
2722 GlobalValue *GV = nullptr;
2723 if (Fn.Kind == ValID::t_GlobalID) {
2724 if (Fn.UIntVal < NumberedVals.size())
2725 GV = NumberedVals[Fn.UIntVal];
2726 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2727 GV = M->getNamedValue(Fn.StrVal);
2728 }
2729 Function *F = nullptr;
2730 if (GV) {
2731 // Confirm that it's actually a function with a definition.
2732 if (!isa<Function>(GV))
2733 return Error(Fn.Loc, "expected function name in blockaddress");
2734 F = cast<Function>(GV);
2735 if (F->isDeclaration())
2736 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2737 }
2738
2739 if (!F) {
2740 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002741 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002742 ForwardRefBlockAddresses.insert(std::make_pair(
2743 std::move(Fn),
2744 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002745 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2746 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002747 if (!FwdRef)
2748 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2749 GlobalValue::InternalLinkage, nullptr, "");
2750 ID.ConstantVal = FwdRef;
2751 ID.Kind = ValID::t_Constant;
2752 return false;
2753 }
2754
2755 // We found the function; now find the basic block. Don't use PFS, since we
2756 // might be inside a constant expression.
2757 BasicBlock *BB;
2758 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2759 if (Label.Kind == ValID::t_LocalID)
2760 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2761 else
2762 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2763 if (!BB)
2764 return Error(Label.Loc, "referenced value is not a basic block");
2765 } else {
2766 if (Label.Kind == ValID::t_LocalID)
2767 return Error(Label.Loc, "cannot take address of numeric label after "
2768 "the function is defined");
2769 BB = dyn_cast_or_null<BasicBlock>(
2770 F->getValueSymbolTable().lookup(Label.StrVal));
2771 if (!BB)
2772 return Error(Label.Loc, "referenced value is not a basic block");
2773 }
2774
2775 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002776 ID.Kind = ValID::t_Constant;
2777 return false;
2778 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002779
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 case lltok::kw_trunc:
2781 case lltok::kw_zext:
2782 case lltok::kw_sext:
2783 case lltok::kw_fptrunc:
2784 case lltok::kw_fpext:
2785 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002786 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 case lltok::kw_uitofp:
2788 case lltok::kw_sitofp:
2789 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002794 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002795 Constant *SrcVal;
2796 Lex.Lex();
2797 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2798 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002799 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 ParseType(DestTy) ||
2801 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2802 return true;
2803 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2804 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002805 getTypeString(SrcVal->getType()) + "' to '" +
2806 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002808 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 ID.Kind = ValID::t_Constant;
2810 return false;
2811 }
2812 case lltok::kw_extractvalue: {
2813 Lex.Lex();
2814 Constant *Val;
2815 SmallVector<unsigned, 4> Indices;
2816 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2817 ParseGlobalTypeAndValue(Val) ||
2818 ParseIndexList(Indices) ||
2819 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2820 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002821
Chris Lattner392be582010-02-12 20:49:41 +00002822 if (!Val->getType()->isAggregateType())
2823 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002824 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002826 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 ID.Kind = ValID::t_Constant;
2828 return false;
2829 }
2830 case lltok::kw_insertvalue: {
2831 Lex.Lex();
2832 Constant *Val0, *Val1;
2833 SmallVector<unsigned, 4> Indices;
2834 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2835 ParseGlobalTypeAndValue(Val0) ||
2836 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2837 ParseGlobalTypeAndValue(Val1) ||
2838 ParseIndexList(Indices) ||
2839 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2840 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002841 if (!Val0->getType()->isAggregateType())
2842 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002843 Type *IndexedType =
2844 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2845 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002846 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002847 if (IndexedType != Val1->getType())
2848 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2849 getTypeString(Val1->getType()) +
2850 "' instead of '" + getTypeString(IndexedType) +
2851 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002852 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 ID.Kind = ValID::t_Constant;
2854 return false;
2855 }
2856 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002857 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002858 unsigned PredVal, Opc = Lex.getUIntVal();
2859 Constant *Val0, *Val1;
2860 Lex.Lex();
2861 if (ParseCmpPredicate(PredVal, Opc) ||
2862 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2863 ParseGlobalTypeAndValue(Val0) ||
2864 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2865 ParseGlobalTypeAndValue(Val1) ||
2866 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2867 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 if (Val0->getType() != Val1->getType())
2870 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002871
Chris Lattnerac161bf2009-01-02 07:01:27 +00002872 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002873
Chris Lattnerac161bf2009-01-02 07:01:27 +00002874 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002875 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002877 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002878 } else {
2879 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002880 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002881 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002882 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002883 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002884 }
2885 ID.Kind = ValID::t_Constant;
2886 return false;
2887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002888
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 // Binary Operators.
2890 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002891 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002892 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002893 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002895 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002896 case lltok::kw_udiv:
2897 case lltok::kw_sdiv:
2898 case lltok::kw_fdiv:
2899 case lltok::kw_urem:
2900 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002901 case lltok::kw_frem:
2902 case lltok::kw_shl:
2903 case lltok::kw_lshr:
2904 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002905 bool NUW = false;
2906 bool NSW = false;
2907 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002908 unsigned Opc = Lex.getUIntVal();
2909 Constant *Val0, *Val1;
2910 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002911 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002912 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2913 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002914 if (EatIfPresent(lltok::kw_nuw))
2915 NUW = true;
2916 if (EatIfPresent(lltok::kw_nsw)) {
2917 NSW = true;
2918 if (EatIfPresent(lltok::kw_nuw))
2919 NUW = true;
2920 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002921 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2922 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002923 if (EatIfPresent(lltok::kw_exact))
2924 Exact = true;
2925 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002926 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2927 ParseGlobalTypeAndValue(Val0) ||
2928 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2929 ParseGlobalTypeAndValue(Val1) ||
2930 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2931 return true;
2932 if (Val0->getType() != Val1->getType())
2933 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002934 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002935 if (NUW)
2936 return Error(ModifierLoc, "nuw only applies to integer operations");
2937 if (NSW)
2938 return Error(ModifierLoc, "nsw only applies to integer operations");
2939 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002940 // Check that the type is valid for the operator.
2941 switch (Opc) {
2942 case Instruction::Add:
2943 case Instruction::Sub:
2944 case Instruction::Mul:
2945 case Instruction::UDiv:
2946 case Instruction::SDiv:
2947 case Instruction::URem:
2948 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002949 case Instruction::Shl:
2950 case Instruction::AShr:
2951 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002952 if (!Val0->getType()->isIntOrIntVectorTy())
2953 return Error(ID.Loc, "constexpr requires integer operands");
2954 break;
2955 case Instruction::FAdd:
2956 case Instruction::FSub:
2957 case Instruction::FMul:
2958 case Instruction::FDiv:
2959 case Instruction::FRem:
2960 if (!Val0->getType()->isFPOrFPVectorTy())
2961 return Error(ID.Loc, "constexpr requires fp operands");
2962 break;
2963 default: llvm_unreachable("Unknown binary operator!");
2964 }
Dan Gohman1b849082009-09-07 23:54:19 +00002965 unsigned Flags = 0;
2966 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2967 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002968 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002969 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002970 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002971 ID.Kind = ValID::t_Constant;
2972 return false;
2973 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002974
Chris Lattnerac161bf2009-01-02 07:01:27 +00002975 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002976 case lltok::kw_and:
2977 case lltok::kw_or:
2978 case lltok::kw_xor: {
2979 unsigned Opc = Lex.getUIntVal();
2980 Constant *Val0, *Val1;
2981 Lex.Lex();
2982 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2983 ParseGlobalTypeAndValue(Val0) ||
2984 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2985 ParseGlobalTypeAndValue(Val1) ||
2986 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2987 return true;
2988 if (Val0->getType() != Val1->getType())
2989 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002990 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002991 return Error(ID.Loc,
2992 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002993 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 ID.Kind = ValID::t_Constant;
2995 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002996 }
2997
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 case lltok::kw_getelementptr:
2999 case lltok::kw_shufflevector:
3000 case lltok::kw_insertelement:
3001 case lltok::kw_extractelement:
3002 case lltok::kw_select: {
3003 unsigned Opc = Lex.getUIntVal();
3004 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003005 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003006 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003008
Dan Gohman1639c392009-07-27 21:53:46 +00003009 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003010 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003011
3012 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3013 return true;
3014
3015 LocTy ExplicitTypeLoc = Lex.getLoc();
3016 if (Opc == Instruction::GetElementPtr) {
3017 if (ParseType(Ty) ||
3018 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3019 return true;
3020 }
3021
3022 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3024 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003025
Chris Lattnerac161bf2009-01-02 07:01:27 +00003026 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003027 if (Elts.size() == 0 ||
3028 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003029 return Error(ID.Loc, "base of getelementptr must be a pointer");
3030
3031 Type *BaseType = Elts[0]->getType();
3032 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003033 if (Ty != BasePointerType->getElementType())
3034 return Error(
3035 ExplicitTypeLoc,
3036 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003037
Jay Foaded8db7d2011-07-21 14:31:17 +00003038 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003039 for (Constant *Val : Indices) {
3040 Type *ValTy = Val->getType();
3041 if (!ValTy->getScalarType()->isIntegerTy())
3042 return Error(ID.Loc, "getelementptr index must be an integer");
3043 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3044 return Error(ID.Loc, "getelementptr index type missmatch");
3045 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003046 unsigned ValNumEl = ValTy->getVectorNumElements();
3047 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003048 if (ValNumEl != PtrNumEl)
3049 return Error(
3050 ID.Loc,
3051 "getelementptr vector index has a wrong number of elements");
3052 }
3053 }
3054
Craig Toppere3dcce92015-08-01 22:20:21 +00003055 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003056 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003057 return Error(ID.Loc, "base element of getelementptr must be sized");
3058
David Blaikie4a2e73b2015-04-02 18:55:32 +00003059 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003060 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003061 ID.ConstantVal =
3062 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 } else if (Opc == Instruction::Select) {
3064 if (Elts.size() != 3)
3065 return Error(ID.Loc, "expected three operands to select");
3066 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3067 Elts[2]))
3068 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003069 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003070 } else if (Opc == Instruction::ShuffleVector) {
3071 if (Elts.size() != 3)
3072 return Error(ID.Loc, "expected three operands to shufflevector");
3073 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3074 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003075 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003076 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 } else if (Opc == Instruction::ExtractElement) {
3078 if (Elts.size() != 2)
3079 return Error(ID.Loc, "expected two operands to extractelement");
3080 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3081 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003082 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 } else {
3084 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3085 if (Elts.size() != 3)
3086 return Error(ID.Loc, "expected three operands to insertelement");
3087 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3088 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003089 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003090 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003091 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003092
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 ID.Kind = ValID::t_Constant;
3094 return false;
3095 }
3096 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003097
Chris Lattnerac161bf2009-01-02 07:01:27 +00003098 Lex.Lex();
3099 return false;
3100}
3101
3102/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003103bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003104 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003105 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003106 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003107 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003108 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003109 if (V && !(C = dyn_cast<Constant>(V)))
3110 return Error(ID.Loc, "global values must be constants");
3111 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112}
3113
Victor Hernandez9d75c962010-01-11 22:31:58 +00003114bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003115 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003116 return ParseType(Ty) ||
3117 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003118}
3119
Rafael Espindola83a362c2015-01-06 22:55:16 +00003120bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003121 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003122
3123 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003124 if (!EatIfPresent(lltok::kw_comdat))
3125 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003126
3127 if (EatIfPresent(lltok::lparen)) {
3128 if (Lex.getKind() != lltok::ComdatVar)
3129 return TokError("expected comdat variable");
3130 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3131 Lex.Lex();
3132 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3133 return true;
3134 } else {
3135 if (GlobalName.empty())
3136 return TokError("comdat cannot be unnamed");
3137 C = getComdat(GlobalName, KwLoc);
3138 }
3139
David Majnemerdad0a642014-06-27 18:19:56 +00003140 return false;
3141}
3142
Victor Hernandez9d75c962010-01-11 22:31:58 +00003143/// ParseGlobalValueVector
3144/// ::= /*empty*/
3145/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003146bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003147 // Empty list.
3148 if (Lex.getKind() == lltok::rbrace ||
3149 Lex.getKind() == lltok::rsquare ||
3150 Lex.getKind() == lltok::greater ||
3151 Lex.getKind() == lltok::rparen)
3152 return false;
3153
3154 Constant *C;
3155 if (ParseGlobalTypeAndValue(C)) return true;
3156 Elts.push_back(C);
3157
3158 while (EatIfPresent(lltok::comma)) {
3159 if (ParseGlobalTypeAndValue(C)) return true;
3160 Elts.push_back(C);
3161 }
3162
3163 return false;
3164}
3165
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003166bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003167 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003168 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003169 return true;
3170
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003171 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003172 return false;
3173}
3174
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003175/// MDNode:
3176/// ::= !{ ... }
3177/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003178/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003179bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003180 if (Lex.getKind() == lltok::MetadataVar)
3181 return ParseSpecializedMDNode(N);
3182
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003183 return ParseToken(lltok::exclaim, "expected '!' here") ||
3184 ParseMDNodeTail(N);
3185}
3186
3187bool LLParser::ParseMDNodeTail(MDNode *&N) {
3188 // !{ ... }
3189 if (Lex.getKind() == lltok::lbrace)
3190 return ParseMDTuple(N);
3191
3192 // !42
3193 return ParseMDNodeID(N);
3194}
3195
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003196namespace {
3197
3198/// Structure to represent an optional metadata field.
3199template <class FieldTy> struct MDFieldImpl {
3200 typedef MDFieldImpl ImplTy;
3201 FieldTy Val;
3202 bool Seen;
3203
3204 void assign(FieldTy Val) {
3205 Seen = true;
3206 this->Val = std::move(Val);
3207 }
3208
3209 explicit MDFieldImpl(FieldTy Default)
3210 : Val(std::move(Default)), Seen(false) {}
3211};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003212
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003213struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3214 uint64_t Max;
3215
3216 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3217 : ImplTy(Default), Max(Max) {}
3218};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003219struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003220 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003221};
3222struct ColumnField : public MDUnsignedField {
3223 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3224};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003225struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003226 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003227 DwarfTagField(dwarf::Tag DefaultTag)
3228 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003229};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003230struct DwarfMacinfoTypeField : public MDUnsignedField {
3231 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3232 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3233 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3234};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003235struct DwarfAttEncodingField : public MDUnsignedField {
3236 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3237};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003238struct DwarfVirtualityField : public MDUnsignedField {
3239 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3240};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003241struct DwarfLangField : public MDUnsignedField {
3242 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3243};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003244
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003245struct DIFlagField : public MDUnsignedField {
3246 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3247};
3248
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003249struct MDSignedField : public MDFieldImpl<int64_t> {
3250 int64_t Min;
3251 int64_t Max;
3252
3253 MDSignedField(int64_t Default = 0)
3254 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3255 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3256 : ImplTy(Default), Min(Min), Max(Max) {}
3257};
3258
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003259struct MDBoolField : public MDFieldImpl<bool> {
3260 MDBoolField(bool Default = false) : ImplTy(Default) {}
3261};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003262struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003263 bool AllowNull;
3264
3265 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003266};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003267struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3268 MDConstant() : ImplTy(nullptr) {}
3269};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003270struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003271 bool AllowEmpty;
3272 MDStringField(bool AllowEmpty = true)
3273 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003274};
3275struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3276 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3277};
3278
3279} // end namespace
3280
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003281namespace llvm {
3282
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003283template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003284bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003285 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003286 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3287 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003288
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003289 auto &U = Lex.getAPSIntVal();
3290 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003291 return TokError("value for '" + Name + "' too large, limit is " +
3292 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003293 Result.assign(U.getZExtValue());
3294 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003295 Lex.Lex();
3296 return false;
3297}
3298
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003299template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003300bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3301 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3302}
3303template <>
3304bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3305 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3306}
3307
3308template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003309bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3310 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003311 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003312
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003313 if (Lex.getKind() != lltok::DwarfTag)
3314 return TokError("expected DWARF tag");
3315
3316 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3317 if (Tag == dwarf::DW_TAG_invalid)
3318 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003319 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003320
3321 Result.assign(Tag);
3322 Lex.Lex();
3323 return false;
3324}
3325
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003326template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003327bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003328 DwarfMacinfoTypeField &Result) {
3329 if (Lex.getKind() == lltok::APSInt)
3330 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3331
3332 if (Lex.getKind() != lltok::DwarfMacinfo)
3333 return TokError("expected DWARF macinfo type");
3334
3335 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3336 if (Macinfo == dwarf::DW_MACINFO_invalid)
3337 return TokError(
3338 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3339 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3340
3341 Result.assign(Macinfo);
3342 Lex.Lex();
3343 return false;
3344}
3345
3346template <>
3347bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003348 DwarfVirtualityField &Result) {
3349 if (Lex.getKind() == lltok::APSInt)
3350 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3351
3352 if (Lex.getKind() != lltok::DwarfVirtuality)
3353 return TokError("expected DWARF virtuality code");
3354
3355 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3356 if (!Virtuality)
3357 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3358 Lex.getStrVal() + "'");
3359 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3360 Result.assign(Virtuality);
3361 Lex.Lex();
3362 return false;
3363}
3364
3365template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003366bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3367 if (Lex.getKind() == lltok::APSInt)
3368 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3369
3370 if (Lex.getKind() != lltok::DwarfLang)
3371 return TokError("expected DWARF language");
3372
3373 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3374 if (!Lang)
3375 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3376 "'");
3377 assert(Lang <= Result.Max && "Expected valid DWARF language");
3378 Result.assign(Lang);
3379 Lex.Lex();
3380 return false;
3381}
3382
3383template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003384bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003385 DwarfAttEncodingField &Result) {
3386 if (Lex.getKind() == lltok::APSInt)
3387 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3388
3389 if (Lex.getKind() != lltok::DwarfAttEncoding)
3390 return TokError("expected DWARF type attribute encoding");
3391
3392 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3393 if (!Encoding)
3394 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3395 Lex.getStrVal() + "'");
3396 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3397 Result.assign(Encoding);
3398 Lex.Lex();
3399 return false;
3400}
3401
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003402/// DIFlagField
3403/// ::= uint32
3404/// ::= DIFlagVector
3405/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3406template <>
3407bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3408 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3409
3410 // Parser for a single flag.
3411 auto parseFlag = [&](unsigned &Val) {
3412 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3413 return ParseUInt32(Val);
3414
3415 if (Lex.getKind() != lltok::DIFlag)
3416 return TokError("expected debug info flag");
3417
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003418 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003419 if (!Val)
3420 return TokError(Twine("invalid debug info flag flag '") +
3421 Lex.getStrVal() + "'");
3422 Lex.Lex();
3423 return false;
3424 };
3425
3426 // Parse the flags and combine them together.
3427 unsigned Combined = 0;
3428 do {
3429 unsigned Val;
3430 if (parseFlag(Val))
3431 return true;
3432 Combined |= Val;
3433 } while (EatIfPresent(lltok::bar));
3434
3435 Result.assign(Combined);
3436 return false;
3437}
3438
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003439template <>
3440bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003441 MDSignedField &Result) {
3442 if (Lex.getKind() != lltok::APSInt)
3443 return TokError("expected signed integer");
3444
3445 auto &S = Lex.getAPSIntVal();
3446 if (S < Result.Min)
3447 return TokError("value for '" + Name + "' too small, limit is " +
3448 Twine(Result.Min));
3449 if (S > Result.Max)
3450 return TokError("value for '" + Name + "' too large, limit is " +
3451 Twine(Result.Max));
3452 Result.assign(S.getExtValue());
3453 assert(Result.Val >= Result.Min && "Expected value in range");
3454 assert(Result.Val <= Result.Max && "Expected value in range");
3455 Lex.Lex();
3456 return false;
3457}
3458
3459template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003460bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3461 switch (Lex.getKind()) {
3462 default:
3463 return TokError("expected 'true' or 'false'");
3464 case lltok::kw_true:
3465 Result.assign(true);
3466 break;
3467 case lltok::kw_false:
3468 Result.assign(false);
3469 break;
3470 }
3471 Lex.Lex();
3472 return false;
3473}
3474
3475template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003476bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003477 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003478 if (!Result.AllowNull)
3479 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003480 Lex.Lex();
3481 Result.assign(nullptr);
3482 return false;
3483 }
3484
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003485 Metadata *MD;
3486 if (ParseMetadata(MD, nullptr))
3487 return true;
3488
3489 Result.assign(MD);
3490 return false;
3491}
3492
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003493template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003494bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3495 Metadata *MD;
3496 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3497 return true;
3498
3499 Result.assign(cast<ConstantAsMetadata>(MD));
3500 return false;
3501}
3502
3503template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003504bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003505 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003506 std::string S;
3507 if (ParseStringConstant(S))
3508 return true;
3509
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003510 if (!Result.AllowEmpty && S.empty())
3511 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3512
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003513 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003514 return false;
3515}
3516
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003517template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003518bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3519 SmallVector<Metadata *, 4> MDs;
3520 if (ParseMDNodeVector(MDs))
3521 return true;
3522
3523 Result.assign(std::move(MDs));
3524 return false;
3525}
3526
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003527} // end namespace llvm
3528
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003529template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003530bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003531 do {
3532 if (Lex.getKind() != lltok::LabelStr)
3533 return TokError("expected field label here");
3534
3535 if (parseField())
3536 return true;
3537 } while (EatIfPresent(lltok::comma));
3538
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003539 return false;
3540}
3541
3542template <class ParserTy>
3543bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3544 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3545 Lex.Lex();
3546
3547 if (ParseToken(lltok::lparen, "expected '(' here"))
3548 return true;
3549 if (Lex.getKind() != lltok::rparen)
3550 if (ParseMDFieldsImplBody(parseField))
3551 return true;
3552
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003553 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003554 return ParseToken(lltok::rparen, "expected ')' here");
3555}
3556
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003557template <class FieldTy>
3558bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3559 if (Result.Seen)
3560 return TokError("field '" + Name + "' cannot be specified more than once");
3561
3562 LocTy Loc = Lex.getLoc();
3563 Lex.Lex();
3564 return ParseMDField(Loc, Name, Result);
3565}
3566
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003567bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3568 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003569
3570#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003571 if (Lex.getStrVal() == #CLASS) \
3572 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003573#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003574
3575 return TokError("expected metadata type");
3576}
3577
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003578#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3579#define NOP_FIELD(NAME, TYPE, INIT)
3580#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3581 if (!NAME.Seen) \
3582 return Error(ClosingLoc, "missing required field '" #NAME "'");
3583#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003584 if (Lex.getStrVal() == #NAME) \
3585 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003586#define PARSE_MD_FIELDS() \
3587 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3588 do { \
3589 LocTy ClosingLoc; \
3590 if (ParseMDFieldsImpl([&]() -> bool { \
3591 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3592 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3593 }, ClosingLoc)) \
3594 return true; \
3595 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3596 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003597#define GET_OR_DISTINCT(CLASS, ARGS) \
3598 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003599
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003600/// ParseDILocationFields:
3601/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3602bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003603#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003604 OPTIONAL(line, LineField, ); \
3605 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003606 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003607 OPTIONAL(inlinedAt, MDField, );
3608 PARSE_MD_FIELDS();
3609#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003610
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003611 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003612 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003613 return false;
3614}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003615
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003616/// ParseGenericDINode:
3617/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3618bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003619#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003620 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003621 OPTIONAL(header, MDStringField, ); \
3622 OPTIONAL(operands, MDFieldList, );
3623 PARSE_MD_FIELDS();
3624#undef VISIT_MD_FIELDS
3625
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003626 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003627 (Context, tag.Val, header.Val, operands.Val));
3628 return false;
3629}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003630
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003631/// ParseDISubrange:
3632/// ::= !DISubrange(count: 30, lowerBound: 2)
3633bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003634#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003635 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003636 OPTIONAL(lowerBound, MDSignedField, );
3637 PARSE_MD_FIELDS();
3638#undef VISIT_MD_FIELDS
3639
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003640 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003641 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003642}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003643
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003644/// ParseDIEnumerator:
3645/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3646bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003647#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003648 REQUIRED(name, MDStringField, ); \
3649 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003650 PARSE_MD_FIELDS();
3651#undef VISIT_MD_FIELDS
3652
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003653 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003654 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003655}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003656
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003657/// ParseDIBasicType:
3658/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3659bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003660#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003661 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003662 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003663 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3664 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003665 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003666 PARSE_MD_FIELDS();
3667#undef VISIT_MD_FIELDS
3668
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003669 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003670 align.Val, encoding.Val));
3671 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003672}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003673
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003674/// ParseDIDerivedType:
3675/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003676/// line: 7, scope: !1, baseType: !2, size: 32,
3677/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003678bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003679#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3680 REQUIRED(tag, DwarfTagField, ); \
3681 OPTIONAL(name, MDStringField, ); \
3682 OPTIONAL(file, MDField, ); \
3683 OPTIONAL(line, LineField, ); \
3684 OPTIONAL(scope, MDField, ); \
3685 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003686 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3687 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3688 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003689 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003690 OPTIONAL(extraData, MDField, );
3691 PARSE_MD_FIELDS();
3692#undef VISIT_MD_FIELDS
3693
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003694 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003695 (Context, tag.Val, name.Val, file.Val, line.Val,
3696 scope.Val, baseType.Val, size.Val, align.Val,
3697 offset.Val, flags.Val, extraData.Val));
3698 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003699}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003700
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003701bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003702#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3703 REQUIRED(tag, DwarfTagField, ); \
3704 OPTIONAL(name, MDStringField, ); \
3705 OPTIONAL(file, MDField, ); \
3706 OPTIONAL(line, LineField, ); \
3707 OPTIONAL(scope, MDField, ); \
3708 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003709 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3710 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3711 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003712 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003713 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003714 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003715 OPTIONAL(vtableHolder, MDField, ); \
3716 OPTIONAL(templateParams, MDField, ); \
3717 OPTIONAL(identifier, MDStringField, );
3718 PARSE_MD_FIELDS();
3719#undef VISIT_MD_FIELDS
3720
3721 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003722 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003723 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3724 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3725 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3726 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003727}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003728
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003729bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003730#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003731 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003732 REQUIRED(types, MDField, );
3733 PARSE_MD_FIELDS();
3734#undef VISIT_MD_FIELDS
3735
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003736 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003737 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003738}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003739
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003740/// ParseDIFileType:
3741/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3742bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003743#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3744 REQUIRED(filename, MDStringField, ); \
3745 REQUIRED(directory, MDStringField, );
3746 PARSE_MD_FIELDS();
3747#undef VISIT_MD_FIELDS
3748
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003749 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003750 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003751}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003752
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003753/// ParseDICompileUnit:
3754/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003755/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3756/// splitDebugFilename: "abc.debug", emissionKind: 1,
3757/// enums: !1, retainedTypes: !2, subprograms: !3,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003758/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003759bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003760 if (!IsDistinct)
3761 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3762
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003763#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3764 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003765 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003766 OPTIONAL(producer, MDStringField, ); \
3767 OPTIONAL(isOptimized, MDBoolField, ); \
3768 OPTIONAL(flags, MDStringField, ); \
3769 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3770 OPTIONAL(splitDebugFilename, MDStringField, ); \
3771 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3772 OPTIONAL(enums, MDField, ); \
3773 OPTIONAL(retainedTypes, MDField, ); \
3774 OPTIONAL(subprograms, MDField, ); \
3775 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003776 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003777 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003778 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003779 PARSE_MD_FIELDS();
3780#undef VISIT_MD_FIELDS
3781
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003782 Result = DICompileUnit::getDistinct(
3783 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3784 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003785 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, macros.Val,
3786 dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003787 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003788}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003789
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003790/// ParseDISubprogram:
3791/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003792/// file: !1, line: 7, type: !2, isLocal: false,
3793/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003794/// virtuality: DW_VIRTUALTIY_pure_virtual,
3795/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003796/// isOptimized: false, templateParams: !4, declaration: !5,
3797/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003798bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003799 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003800#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3801 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003802 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003803 OPTIONAL(linkageName, MDStringField, ); \
3804 OPTIONAL(file, MDField, ); \
3805 OPTIONAL(line, LineField, ); \
3806 OPTIONAL(type, MDField, ); \
3807 OPTIONAL(isLocal, MDBoolField, ); \
3808 OPTIONAL(isDefinition, MDBoolField, (true)); \
3809 OPTIONAL(scopeLine, LineField, ); \
3810 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003811 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003812 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003813 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003814 OPTIONAL(isOptimized, MDBoolField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003815 OPTIONAL(templateParams, MDField, ); \
3816 OPTIONAL(declaration, MDField, ); \
3817 OPTIONAL(variables, MDField, );
3818 PARSE_MD_FIELDS();
3819#undef VISIT_MD_FIELDS
3820
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003821 if (isDefinition.Val && !IsDistinct)
3822 return Lex.Error(
3823 Loc,
3824 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3825
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003826 Result = GET_OR_DISTINCT(
Peter Collingbourned4bff302015-11-05 22:03:56 +00003827 DISubprogram,
3828 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
3829 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
3830 containingType.Val, virtuality.Val, virtualIndex.Val, flags.Val,
3831 isOptimized.Val, templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003832 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003833}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003834
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003835/// ParseDILexicalBlock:
3836/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3837bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003838#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003839 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003840 OPTIONAL(file, MDField, ); \
3841 OPTIONAL(line, LineField, ); \
3842 OPTIONAL(column, ColumnField, );
3843 PARSE_MD_FIELDS();
3844#undef VISIT_MD_FIELDS
3845
3846 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003847 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003848 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003849}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003850
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003851/// ParseDILexicalBlockFile:
3852/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3853bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003854#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003855 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003856 OPTIONAL(file, MDField, ); \
3857 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3858 PARSE_MD_FIELDS();
3859#undef VISIT_MD_FIELDS
3860
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003861 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003862 (Context, scope.Val, file.Val, discriminator.Val));
3863 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003864}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003865
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003866/// ParseDINamespace:
3867/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3868bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003869#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3870 REQUIRED(scope, MDField, ); \
3871 OPTIONAL(file, MDField, ); \
3872 OPTIONAL(name, MDStringField, ); \
3873 OPTIONAL(line, LineField, );
3874 PARSE_MD_FIELDS();
3875#undef VISIT_MD_FIELDS
3876
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003877 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003878 (Context, scope.Val, file.Val, name.Val, line.Val));
3879 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003880}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003881
Amjad Abouda9bcf162015-12-10 12:56:35 +00003882/// ParseDIMacro:
3883/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3884bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3885#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3886 REQUIRED(type, DwarfMacinfoTypeField, ); \
3887 REQUIRED(line, LineField, ); \
3888 REQUIRED(name, MDStringField, ); \
3889 OPTIONAL(value, MDStringField, );
3890 PARSE_MD_FIELDS();
3891#undef VISIT_MD_FIELDS
3892
3893 Result = GET_OR_DISTINCT(DIMacro,
3894 (Context, type.Val, line.Val, name.Val, value.Val));
3895 return false;
3896}
3897
3898/// ParseDIMacroFile:
3899/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
3900bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
3901#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3902 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
3903 REQUIRED(line, LineField, ); \
3904 REQUIRED(file, MDField, ); \
3905 OPTIONAL(nodes, MDField, );
3906 PARSE_MD_FIELDS();
3907#undef VISIT_MD_FIELDS
3908
3909 Result = GET_OR_DISTINCT(DIMacroFile,
3910 (Context, type.Val, line.Val, file.Val, nodes.Val));
3911 return false;
3912}
3913
3914
Adrian Prantlab1243f2015-06-29 23:03:47 +00003915/// ParseDIModule:
3916/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3917/// includePath: "/usr/include", isysroot: "/")
3918bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3919#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3920 REQUIRED(scope, MDField, ); \
3921 REQUIRED(name, MDStringField, ); \
3922 OPTIONAL(configMacros, MDStringField, ); \
3923 OPTIONAL(includePath, MDStringField, ); \
3924 OPTIONAL(isysroot, MDStringField, );
3925 PARSE_MD_FIELDS();
3926#undef VISIT_MD_FIELDS
3927
3928 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3929 configMacros.Val, includePath.Val, isysroot.Val));
3930 return false;
3931}
3932
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003933/// ParseDITemplateTypeParameter:
3934/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3935bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003937 OPTIONAL(name, MDStringField, ); \
3938 REQUIRED(type, MDField, );
3939 PARSE_MD_FIELDS();
3940#undef VISIT_MD_FIELDS
3941
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003942 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003943 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003944 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003945}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003946
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003947/// ParseDITemplateValueParameter:
3948/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003949/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003950bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003951#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003952 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003953 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003954 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003955 REQUIRED(value, MDField, );
3956 PARSE_MD_FIELDS();
3957#undef VISIT_MD_FIELDS
3958
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003959 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003960 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003961 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003962}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003963
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003964/// ParseDIGlobalVariable:
3965/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003966/// file: !1, line: 7, type: !2, isLocal: false,
3967/// isDefinition: true, variable: i32* @foo,
3968/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003969bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003970#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003971 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003972 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003973 OPTIONAL(linkageName, MDStringField, ); \
3974 OPTIONAL(file, MDField, ); \
3975 OPTIONAL(line, LineField, ); \
3976 OPTIONAL(type, MDField, ); \
3977 OPTIONAL(isLocal, MDBoolField, ); \
3978 OPTIONAL(isDefinition, MDBoolField, (true)); \
3979 OPTIONAL(variable, MDConstant, ); \
3980 OPTIONAL(declaration, MDField, );
3981 PARSE_MD_FIELDS();
3982#undef VISIT_MD_FIELDS
3983
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003984 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003985 (Context, scope.Val, name.Val, linkageName.Val,
3986 file.Val, line.Val, type.Val, isLocal.Val,
3987 isDefinition.Val, variable.Val, declaration.Val));
3988 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003989}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003990
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003991/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003992/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3993/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3994/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003995/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003996bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003997#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003998 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003999 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004000 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004001 OPTIONAL(file, MDField, ); \
4002 OPTIONAL(line, LineField, ); \
4003 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004004 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004005 PARSE_MD_FIELDS();
4006#undef VISIT_MD_FIELDS
4007
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004008 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004009 (Context, scope.Val, name.Val, file.Val, line.Val,
4010 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004011 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004012}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004013
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004014/// ParseDIExpression:
4015/// ::= !DIExpression(0, 7, -1)
4016bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004017 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4018 Lex.Lex();
4019
4020 if (ParseToken(lltok::lparen, "expected '(' here"))
4021 return true;
4022
4023 SmallVector<uint64_t, 8> Elements;
4024 if (Lex.getKind() != lltok::rparen)
4025 do {
4026 if (Lex.getKind() == lltok::DwarfOp) {
4027 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4028 Lex.Lex();
4029 Elements.push_back(Op);
4030 continue;
4031 }
4032 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4033 }
4034
4035 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4036 return TokError("expected unsigned integer");
4037
4038 auto &U = Lex.getAPSIntVal();
4039 if (U.ugt(UINT64_MAX))
4040 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4041 Elements.push_back(U.getZExtValue());
4042 Lex.Lex();
4043 } while (EatIfPresent(lltok::comma));
4044
4045 if (ParseToken(lltok::rparen, "expected ')' here"))
4046 return true;
4047
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004048 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004049 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004050}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004051
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004052/// ParseDIObjCProperty:
4053/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004054/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004055bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004056#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004057 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004058 OPTIONAL(file, MDField, ); \
4059 OPTIONAL(line, LineField, ); \
4060 OPTIONAL(setter, MDStringField, ); \
4061 OPTIONAL(getter, MDStringField, ); \
4062 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4063 OPTIONAL(type, MDField, );
4064 PARSE_MD_FIELDS();
4065#undef VISIT_MD_FIELDS
4066
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004067 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004068 (Context, name.Val, file.Val, line.Val, setter.Val,
4069 getter.Val, attributes.Val, type.Val));
4070 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004071}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004072
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004073/// ParseDIImportedEntity:
4074/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004075/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004076bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004077#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4078 REQUIRED(tag, DwarfTagField, ); \
4079 REQUIRED(scope, MDField, ); \
4080 OPTIONAL(entity, MDField, ); \
4081 OPTIONAL(line, LineField, ); \
4082 OPTIONAL(name, MDStringField, );
4083 PARSE_MD_FIELDS();
4084#undef VISIT_MD_FIELDS
4085
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004086 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004087 entity.Val, line.Val, name.Val));
4088 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004089}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004090
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004091#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004092#undef NOP_FIELD
4093#undef REQUIRE_FIELD
4094#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004095
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004096/// ParseMetadataAsValue
4097/// ::= metadata i32 %local
4098/// ::= metadata i32 @global
4099/// ::= metadata i32 7
4100/// ::= metadata !0
4101/// ::= metadata !{...}
4102/// ::= metadata !"string"
4103bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4104 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004105 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004106 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004107 return true;
4108
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004109 V = MetadataAsValue::get(Context, MD);
4110 return false;
4111}
4112
4113/// ParseValueAsMetadata
4114/// ::= i32 %local
4115/// ::= i32 @global
4116/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004117bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4118 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004119 Type *Ty;
4120 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004121 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004122 return true;
4123 if (Ty->isMetadataTy())
4124 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4125
4126 Value *V;
4127 if (ParseValue(Ty, V, PFS))
4128 return true;
4129
4130 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004131 return false;
4132}
4133
4134/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004135/// ::= i32 %local
4136/// ::= i32 @global
4137/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004138/// ::= !42
4139/// ::= !{...}
4140/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004141/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004142bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004143 if (Lex.getKind() == lltok::MetadataVar) {
4144 MDNode *N;
4145 if (ParseSpecializedMDNode(N))
4146 return true;
4147 MD = N;
4148 return false;
4149 }
4150
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004151 // ValueAsMetadata:
4152 // <type> <value>
4153 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004154 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004155
4156 // '!'.
4157 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4158 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004159
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004160 // MDString:
4161 // ::= '!' STRINGCONSTANT
4162 if (Lex.getKind() == lltok::StringConstant) {
4163 MDString *S;
4164 if (ParseMDString(S))
4165 return true;
4166 MD = S;
4167 return false;
4168 }
4169
Dan Gohman8939ba332010-07-14 18:26:50 +00004170 // MDNode:
4171 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004172 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004173 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004174 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004175 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004176 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004177 return false;
4178}
4179
Victor Hernandez9d75c962010-01-11 22:31:58 +00004180
4181//===----------------------------------------------------------------------===//
4182// Function Parsing.
4183//===----------------------------------------------------------------------===//
4184
Chris Lattner229907c2011-07-18 04:54:35 +00004185bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004186 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004187 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004188 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004189
Chris Lattnerac161bf2009-01-02 07:01:27 +00004190 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004191 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004192 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004193 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004194 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004195 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004196 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004197 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004198 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004199 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004200 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004201 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004202 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4203 (ID.UIntVal >> 1) & 1,
4204 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004205 return false;
4206 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004207 case ValID::t_GlobalName:
4208 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004209 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 case ValID::t_GlobalID:
4211 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004212 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004213 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004214 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004215 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004216 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004217 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004218 return false;
4219 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004220 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004221 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4222 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004223
Dan Gohman518cda42011-12-17 00:04:22 +00004224 // The lexer has no type info, so builds all half, float, and double FP
4225 // constants as double. Fix this here. Long double does not need this.
4226 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004227 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004228 if (Ty->isHalfTy())
4229 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4230 &Ignored);
4231 else if (Ty->isFloatTy())
4232 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4233 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004234 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004235 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004236
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004237 if (V->getType() != Ty)
4238 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004239 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004240
Chris Lattnerac161bf2009-01-02 07:01:27 +00004241 return false;
4242 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004243 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004244 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004245 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004246 return false;
4247 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004248 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004249 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004250 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004251 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004252 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004253 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004254 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004255 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004256 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004257 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004258 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004259 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004260 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004261 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004262 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004263 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004264 case ValID::t_None:
4265 if (!Ty->isTokenTy())
4266 return Error(ID.Loc, "invalid type for none constant");
4267 V = Constant::getNullValue(Ty);
4268 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004269 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004270 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004271 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004272
Chris Lattnerac161bf2009-01-02 07:01:27 +00004273 V = ID.ConstantVal;
4274 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004275 case ValID::t_ConstantStruct:
4276 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004277 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004278 if (ST->getNumElements() != ID.UIntVal)
4279 return Error(ID.Loc,
4280 "initializer with struct type has wrong # elements");
4281 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4282 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004283
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004284 // Verify that the elements are compatible with the structtype.
4285 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4286 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4287 return Error(ID.Loc, "element " + Twine(i) +
4288 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004289
David Blaikieadbda4b2015-08-03 20:08:41 +00004290 V = ConstantStruct::get(
4291 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004292 } else
4293 return Error(ID.Loc, "constant expression type mismatch");
4294 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004295 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004296 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004297}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004298
Alex Lorenzd2255952015-07-17 22:07:03 +00004299bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4300 C = nullptr;
4301 ValID ID;
4302 auto Loc = Lex.getLoc();
4303 if (ParseValID(ID, /*PFS=*/nullptr))
4304 return true;
4305 switch (ID.Kind) {
4306 case ValID::t_APSInt:
4307 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004308 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004309 case ValID::t_Constant:
4310 case ValID::t_ConstantStruct:
4311 case ValID::t_PackedConstantStruct: {
4312 Value *V;
4313 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4314 return true;
4315 assert(isa<Constant>(V) && "Expected a constant value");
4316 C = cast<Constant>(V);
4317 return false;
4318 }
4319 default:
4320 return Error(Loc, "expected a constant value");
4321 }
4322}
4323
David Majnemer8a1c45d2015-12-12 05:38:55 +00004324bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004325 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004326 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004327 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328}
4329
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004330bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004331 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004332 return ParseType(Ty) ||
4333 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004334}
4335
Chris Lattner3ed871f2009-10-27 19:13:16 +00004336bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4337 PerFunctionState &PFS) {
4338 Value *V;
4339 Loc = Lex.getLoc();
4340 if (ParseTypeAndValue(V, PFS)) return true;
4341 if (!isa<BasicBlock>(V))
4342 return Error(Loc, "expected a basic block");
4343 BB = cast<BasicBlock>(V);
4344 return false;
4345}
4346
4347
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348/// FunctionHeader
4349/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004350/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004351/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004352bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4353 // Parse the linkage.
4354 LocTy LinkageLoc = Lex.getLoc();
4355 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004356
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004357 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004358 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004359 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004360 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004361 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004362 LocTy RetTypeLoc = Lex.getLoc();
4363 if (ParseOptionalLinkage(Linkage) ||
4364 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004365 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004366 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004367 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004368 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004369 return true;
4370
4371 // Verify that the linkage is ok.
4372 switch ((GlobalValue::LinkageTypes)Linkage) {
4373 case GlobalValue::ExternalLinkage:
4374 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004375 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004376 if (isDefine)
4377 return Error(LinkageLoc, "invalid linkage for function definition");
4378 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004379 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004380 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004381 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004382 case GlobalValue::LinkOnceAnyLinkage:
4383 case GlobalValue::LinkOnceODRLinkage:
4384 case GlobalValue::WeakAnyLinkage:
4385 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386 if (!isDefine)
4387 return Error(LinkageLoc, "invalid linkage for function declaration");
4388 break;
4389 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004390 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004391 return Error(LinkageLoc, "invalid function linkage type");
4392 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004393
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004394 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4395 return Error(LinkageLoc,
4396 "symbol with local linkage must have default visibility");
4397
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004398 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004399 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004400
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004402
4403 std::string FunctionName;
4404 if (Lex.getKind() == lltok::GlobalVar) {
4405 FunctionName = Lex.getStrVal();
4406 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4407 unsigned NameID = Lex.getUIntVal();
4408
4409 if (NameID != NumberedVals.size())
4410 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004411 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004412 } else {
4413 return TokError("expected function name");
4414 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004415
Chris Lattner3822f632009-01-02 08:05:26 +00004416 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004417
Chris Lattner3822f632009-01-02 08:05:26 +00004418 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004419 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004421 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004422 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004423 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004424 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004425 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004426 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004427 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004428 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004429 bool UnnamedAddr;
4430 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004431 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004432 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004433 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004434 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004436 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004437 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4438 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004439 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004440 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004441 (EatIfPresent(lltok::kw_section) &&
4442 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004443 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004444 ParseOptionalAlignment(Alignment) ||
4445 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004446 ParseStringConstant(GC)) ||
4447 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004448 ParseGlobalTypeAndValue(Prefix)) ||
4449 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004450 ParseGlobalTypeAndValue(Prologue)) ||
4451 (EatIfPresent(lltok::kw_personality) &&
4452 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004453 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004454
Michael Gottesman41748d72013-06-27 00:25:01 +00004455 if (FuncAttrs.contains(Attribute::Builtin))
4456 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004457
Chris Lattnerac161bf2009-01-02 07:01:27 +00004458 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004459 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004460 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004461 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004462 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004463
Chris Lattnerac161bf2009-01-02 07:01:27 +00004464 // Okay, if we got here, the function is syntactically valid. Convert types
4465 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004466 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004467 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004468
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004469 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004470 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4471 AttributeSet::ReturnIndex,
4472 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004473
Chris Lattnerac161bf2009-01-02 07:01:27 +00004474 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004475 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004476 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4477 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004478 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4479 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004480 }
4481
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004482 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004483 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4484 AttributeSet::FunctionIndex,
4485 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004486
Bill Wendlinge94d8432012-12-07 23:16:57 +00004487 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004488
Bill Wendling749a43d2012-12-30 13:50:49 +00004489 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004490 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4491
Chris Lattner229907c2011-07-18 04:54:35 +00004492 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004493 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004494 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495
Craig Topper2617dcc2014-04-15 06:32:26 +00004496 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004497 if (!FunctionName.empty()) {
4498 // If this was a definition of a forward reference, remove the definition
4499 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004500 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004501 if (FRVI != ForwardRefVals.end()) {
4502 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004503 if (!Fn)
4504 return Error(FRVI->second.second, "invalid forward reference to "
4505 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004506 if (Fn->getType() != PFT)
4507 return Error(FRVI->second.second, "invalid forward reference to "
4508 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004509
Chris Lattnerac161bf2009-01-02 07:01:27 +00004510 ForwardRefVals.erase(FRVI);
4511 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004512 // Reject redefinitions.
4513 return Error(NameLoc, "invalid redefinition of function '" +
4514 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004515 } else if (M->getNamedValue(FunctionName)) {
4516 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004517 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004518
Dan Gohman399d6ae2009-08-29 23:37:49 +00004519 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 // If this is a definition of a forward referenced function, make sure the
4521 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004522 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 if (I != ForwardRefValIDs.end()) {
4524 Fn = cast<Function>(I->second.first);
4525 if (Fn->getType() != PFT)
4526 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004527 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004528 ForwardRefValIDs.erase(I);
4529 }
4530 }
4531
Craig Topper2617dcc2014-04-15 06:32:26 +00004532 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4534 else // Move the forward-reference to the correct spot in the module.
4535 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4536
4537 if (FunctionName.empty())
4538 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004539
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4541 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004542 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004543 Fn->setCallingConv(CC);
4544 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004545 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546 Fn->setAlignment(Alignment);
4547 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004548 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004549 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004551 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004552 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004553 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004554
Chris Lattnerac161bf2009-01-02 07:01:27 +00004555 // Add all of the arguments we parsed to the function.
4556 Function::arg_iterator ArgIt = Fn->arg_begin();
4557 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4558 // If the argument has a name, insert it into the argument symbol table.
4559 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004560
Chris Lattnerac161bf2009-01-02 07:01:27 +00004561 // Set the name, if it conflicted, it will be auto-renamed.
4562 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004563
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004564 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4566 ArgList[i].Name + "'");
4567 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004568
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004569 if (isDefine)
4570 return false;
4571
Robin Morisset039781e2014-08-29 21:53:01 +00004572 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004573 ValID ID;
4574 if (FunctionName.empty()) {
4575 ID.Kind = ValID::t_GlobalID;
4576 ID.UIntVal = NumberedVals.size() - 1;
4577 } else {
4578 ID.Kind = ValID::t_GlobalName;
4579 ID.StrVal = FunctionName;
4580 }
4581 auto Blocks = ForwardRefBlockAddresses.find(ID);
4582 if (Blocks != ForwardRefBlockAddresses.end())
4583 return Error(Blocks->first.Loc,
4584 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585 return false;
4586}
4587
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004588bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4589 ValID ID;
4590 if (FunctionNumber == -1) {
4591 ID.Kind = ValID::t_GlobalName;
4592 ID.StrVal = F.getName();
4593 } else {
4594 ID.Kind = ValID::t_GlobalID;
4595 ID.UIntVal = FunctionNumber;
4596 }
4597
4598 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4599 if (Blocks == P.ForwardRefBlockAddresses.end())
4600 return false;
4601
4602 for (const auto &I : Blocks->second) {
4603 const ValID &BBID = I.first;
4604 GlobalValue *GV = I.second;
4605
4606 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4607 "Expected local id or name");
4608 BasicBlock *BB;
4609 if (BBID.Kind == ValID::t_LocalName)
4610 BB = GetBB(BBID.StrVal, BBID.Loc);
4611 else
4612 BB = GetBB(BBID.UIntVal, BBID.Loc);
4613 if (!BB)
4614 return P.Error(BBID.Loc, "referenced value is not a basic block");
4615
4616 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4617 GV->eraseFromParent();
4618 }
4619
4620 P.ForwardRefBlockAddresses.erase(Blocks);
4621 return false;
4622}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623
4624/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004625/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004626bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004627 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628 return TokError("expected '{' in function body");
4629 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004630
Chris Lattner3432c622009-10-28 03:39:23 +00004631 int FunctionNumber = -1;
4632 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004633
Chris Lattner3432c622009-10-28 03:39:23 +00004634 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004635
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004636 // Resolve block addresses and allow basic blocks to be forward-declared
4637 // within this function.
4638 if (PFS.resolveForwardRefBlockAddresses())
4639 return true;
4640 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4641
Chris Lattnerbbddd962010-01-09 19:20:07 +00004642 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004643 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004644 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004645
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004646 while (Lex.getKind() != lltok::rbrace &&
4647 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004649
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004650 while (Lex.getKind() != lltok::rbrace)
4651 if (ParseUseListOrder(&PFS))
4652 return true;
4653
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 // Eat the }.
4655 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004656
Chris Lattnerac161bf2009-01-02 07:01:27 +00004657 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004658 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659}
4660
4661/// ParseBasicBlock
4662/// ::= LabelStr? Instruction*
4663bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4664 // If this basic block starts out with a name, remember it.
4665 std::string Name;
4666 LocTy NameLoc = Lex.getLoc();
4667 if (Lex.getKind() == lltok::LabelStr) {
4668 Name = Lex.getStrVal();
4669 Lex.Lex();
4670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004671
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004673 if (!BB)
4674 return Error(NameLoc,
4675 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004676
Chris Lattnerac161bf2009-01-02 07:01:27 +00004677 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004678
Chris Lattnerac161bf2009-01-02 07:01:27 +00004679 // Parse the instructions in this block until we get a terminator.
4680 Instruction *Inst;
4681 do {
4682 // This instruction may have three possibilities for a name: a) none
4683 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4684 LocTy NameLoc = Lex.getLoc();
4685 int NameID = -1;
4686 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004687
Chris Lattnerac161bf2009-01-02 07:01:27 +00004688 if (Lex.getKind() == lltok::LocalVarID) {
4689 NameID = Lex.getUIntVal();
4690 Lex.Lex();
4691 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4692 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004693 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004694 NameStr = Lex.getStrVal();
4695 Lex.Lex();
4696 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4697 return true;
4698 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004699
Chris Lattner77b89dc2009-12-30 05:23:43 +00004700 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004701 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004702 case InstError: return true;
4703 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004704 BB->getInstList().push_back(Inst);
4705
Chris Lattner77b89dc2009-12-30 05:23:43 +00004706 // With a normal result, we check to see if the instruction is followed by
4707 // a comma and metadata.
4708 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004709 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004710 return true;
4711 break;
4712 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004713 BB->getInstList().push_back(Inst);
4714
Chris Lattner77b89dc2009-12-30 05:23:43 +00004715 // If the instruction parser ate an extra comma at the end of it, it
4716 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004717 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004718 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004719 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004720 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004721
Chris Lattnerac161bf2009-01-02 07:01:27 +00004722 // Set the name on the instruction.
4723 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4724 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004725
Chris Lattnerac161bf2009-01-02 07:01:27 +00004726 return false;
4727}
4728
4729//===----------------------------------------------------------------------===//
4730// Instruction Parsing.
4731//===----------------------------------------------------------------------===//
4732
4733/// ParseInstruction - Parse one of the many different instructions.
4734///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004735int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4736 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 lltok::Kind Token = Lex.getKind();
4738 if (Token == lltok::Eof)
4739 return TokError("found end of file when expecting more instructions");
4740 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004741 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004742 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004743
Chris Lattnerac161bf2009-01-02 07:01:27 +00004744 switch (Token) {
4745 default: return Error(Loc, "expected instruction opcode");
4746 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004747 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004748 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4749 case lltok::kw_br: return ParseBr(Inst, PFS);
4750 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004751 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004753 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004754 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4755 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004756 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4757 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004758 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 // Binary Operators.
4760 case lltok::kw_add:
4761 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004762 case lltok::kw_mul:
4763 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004764 bool NUW = EatIfPresent(lltok::kw_nuw);
4765 bool NSW = EatIfPresent(lltok::kw_nsw);
4766 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004767
Chris Lattnera676c0f2011-02-07 16:40:21 +00004768 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004769
Chris Lattnera676c0f2011-02-07 16:40:21 +00004770 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4771 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4772 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004773 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004774 case lltok::kw_fadd:
4775 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004776 case lltok::kw_fmul:
4777 case lltok::kw_fdiv:
4778 case lltok::kw_frem: {
4779 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4780 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4781 if (Res != 0)
4782 return Res;
4783 if (FMF.any())
4784 Inst->setFastMathFlags(FMF);
4785 return 0;
4786 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004787
Chris Lattner35315d02011-02-06 21:44:57 +00004788 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004789 case lltok::kw_udiv:
4790 case lltok::kw_lshr:
4791 case lltok::kw_ashr: {
4792 bool Exact = EatIfPresent(lltok::kw_exact);
4793
4794 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4795 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4796 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004797 }
4798
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004800 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004801 case lltok::kw_and:
4802 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004803 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004804 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4805 case lltok::kw_fcmp: {
4806 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4807 int Res = ParseCompare(Inst, PFS, KeywordVal);
4808 if (Res != 0)
4809 return Res;
4810 if (FMF.any())
4811 Inst->setFastMathFlags(FMF);
4812 return 0;
4813 }
4814
Chris Lattnerac161bf2009-01-02 07:01:27 +00004815 // Casts.
4816 case lltok::kw_trunc:
4817 case lltok::kw_zext:
4818 case lltok::kw_sext:
4819 case lltok::kw_fptrunc:
4820 case lltok::kw_fpext:
4821 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004822 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004823 case lltok::kw_uitofp:
4824 case lltok::kw_sitofp:
4825 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004828 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004829 // Other.
4830 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004831 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4833 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4834 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4835 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004836 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004837 // Call.
4838 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4839 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4840 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004841 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004843 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004844 case lltok::kw_load: return ParseLoad(Inst, PFS);
4845 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004846 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4847 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004848 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004849 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4850 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4851 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4852 }
4853}
4854
4855/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4856bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004857 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004858 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004859 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4861 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4862 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4863 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4864 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4865 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4866 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4867 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4868 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4869 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4870 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4871 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4872 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4873 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4874 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4875 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4876 }
4877 } else {
4878 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004879 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004880 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4881 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4882 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4883 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4884 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4885 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4886 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4887 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4888 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4889 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4890 }
4891 }
4892 Lex.Lex();
4893 return false;
4894}
4895
4896//===----------------------------------------------------------------------===//
4897// Terminator Instructions.
4898//===----------------------------------------------------------------------===//
4899
4900/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004901/// ::= 'ret' void (',' !dbg, !1)*
4902/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004903bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004904 PerFunctionState &PFS) {
4905 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004906 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004907 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004908
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004909 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004910
Chris Lattnerfdd87902009-10-05 05:54:46 +00004911 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004912 if (!ResType->isVoidTy())
4913 return Error(TypeLoc, "value doesn't match function result type '" +
4914 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004915
Owen Anderson55f1c092009-08-13 21:58:54 +00004916 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004917 return false;
4918 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004919
Chris Lattnerac161bf2009-01-02 07:01:27 +00004920 Value *RV;
4921 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004923 if (ResType != RV->getType())
4924 return Error(TypeLoc, "value doesn't match function result type '" +
4925 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004926
Owen Anderson55f1c092009-08-13 21:58:54 +00004927 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004928 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004929}
4930
4931
4932/// ParseBr
4933/// ::= 'br' TypeAndValue
4934/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4935bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4936 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004937 Value *Op0;
4938 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4942 Inst = BranchInst::Create(BB);
4943 return false;
4944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004945
Owen Anderson55f1c092009-08-13 21:58:54 +00004946 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004948
Chris Lattnerac161bf2009-01-02 07:01:27 +00004949 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004950 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004951 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004952 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004953 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004954
Chris Lattner3ed871f2009-10-27 19:13:16 +00004955 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 return false;
4957}
4958
4959/// ParseSwitch
4960/// Instruction
4961/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4962/// JumpTable
4963/// ::= (TypeAndValue ',' TypeAndValue)*
4964bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4965 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004966 Value *Cond;
4967 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004968 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4969 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004970 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004971 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4972 return true;
4973
Duncan Sands19d0b472010-02-16 11:11:14 +00004974 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004976
Chris Lattnerac161bf2009-01-02 07:01:27 +00004977 // Parse the jump table pairs.
4978 SmallPtrSet<Value*, 32> SeenCases;
4979 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4980 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004981 Value *Constant;
4982 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004983
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4985 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004986 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004987 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004988
David Blaikie70573dc2014-11-19 07:49:26 +00004989 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 return Error(CondLoc, "duplicate case value in switch");
4991 if (!isa<ConstantInt>(Constant))
4992 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004993
Chris Lattner3ed871f2009-10-27 19:13:16 +00004994 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004996
Chris Lattnerac161bf2009-01-02 07:01:27 +00004997 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004998
Chris Lattner3ed871f2009-10-27 19:13:16 +00004999 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005000 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5001 SI->addCase(Table[i].first, Table[i].second);
5002 Inst = SI;
5003 return false;
5004}
5005
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005006/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005007/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005008/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5009bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005010 LocTy AddrLoc;
5011 Value *Address;
5012 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005013 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5014 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005015 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005016
Duncan Sands19d0b472010-02-16 11:11:14 +00005017 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005018 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005019
Chris Lattner3ed871f2009-10-27 19:13:16 +00005020 // Parse the destination list.
5021 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005022
Chris Lattner3ed871f2009-10-27 19:13:16 +00005023 if (Lex.getKind() != lltok::rsquare) {
5024 BasicBlock *DestBB;
5025 if (ParseTypeAndBasicBlock(DestBB, PFS))
5026 return true;
5027 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005028
Chris Lattner3ed871f2009-10-27 19:13:16 +00005029 while (EatIfPresent(lltok::comma)) {
5030 if (ParseTypeAndBasicBlock(DestBB, PFS))
5031 return true;
5032 DestList.push_back(DestBB);
5033 }
5034 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005035
Chris Lattner3ed871f2009-10-27 19:13:16 +00005036 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5037 return true;
5038
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005039 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005040 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5041 IBI->addDestination(DestList[i]);
5042 Inst = IBI;
5043 return false;
5044}
5045
5046
Chris Lattnerac161bf2009-01-02 07:01:27 +00005047/// ParseInvoke
5048/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5049/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5050bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5051 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005052 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005053 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005054 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005055 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005056 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 LocTy RetTypeLoc;
5058 ValID CalleeID;
5059 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005060 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061
Chris Lattner3ed871f2009-10-27 19:13:16 +00005062 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005063 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005064 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005065 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005066 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5067 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005068 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005069 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005070 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005071 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005072 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005073 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005074
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 // If RetType is a non-function pointer type, then this is the short syntax
5076 // for the call, which means that RetType is just the return type. Infer the
5077 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005078 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5079 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005081 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5083 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005084
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085 if (!FunctionType::isValidReturnType(RetType))
5086 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005087
Owen Anderson4056ca92009-07-29 22:17:13 +00005088 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005090
David Blaikie41ba2b42015-07-27 23:32:19 +00005091 CalleeID.FTy = Ty;
5092
Chris Lattnerac161bf2009-01-02 07:01:27 +00005093 // Look up the callee.
5094 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005095 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5096 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005097
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005098 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005099 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005100 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005101 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5102 AttributeSet::ReturnIndex,
5103 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005104
Chris Lattnerac161bf2009-01-02 07:01:27 +00005105 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005106
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107 // Loop through FunctionType's arguments and ensure they are specified
5108 // correctly. Also, gather any parameter attributes.
5109 FunctionType::param_iterator I = Ty->param_begin();
5110 FunctionType::param_iterator E = Ty->param_end();
5111 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005112 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 if (I != E) {
5114 ExpectedTy = *I++;
5115 } else if (!Ty->isVarArg()) {
5116 return Error(ArgList[i].Loc, "too many arguments specified");
5117 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005118
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5120 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005121 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005122 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005123 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5124 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005125 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5126 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005128
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 if (I != E)
5130 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
David Majnemer8d22abd2015-02-23 00:01:32 +00005132 if (FnAttrs.hasAttributes()) {
5133 if (FnAttrs.hasAlignmentAttr())
5134 return Error(CallLoc, "invoke instructions may not have an alignment");
5135
Bill Wendlingf5075a42013-01-27 02:24:02 +00005136 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5137 AttributeSet::FunctionIndex,
5138 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005139 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005140
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005141 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005142 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005143
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005144 InvokeInst *II =
5145 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005146 II->setCallingConv(CC);
5147 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005148 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149 Inst = II;
5150 return false;
5151}
5152
Bill Wendlingf891bf82011-07-31 06:30:59 +00005153/// ParseResume
5154/// ::= 'resume' TypeAndValue
5155bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5156 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005157 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5158 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005159
Bill Wendlingf891bf82011-07-31 06:30:59 +00005160 ResumeInst *RI = ResumeInst::Create(Exn);
5161 Inst = RI;
5162 return false;
5163}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005164
David Majnemer654e1302015-07-31 17:58:14 +00005165bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5166 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005167 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005168 return true;
5169
5170 while (Lex.getKind() != lltok::rsquare) {
5171 // If this isn't the first argument, we need a comma.
5172 if (!Args.empty() &&
5173 ParseToken(lltok::comma, "expected ',' in argument list"))
5174 return true;
5175
5176 // Parse the argument.
5177 LocTy ArgLoc;
5178 Type *ArgTy = nullptr;
5179 if (ParseType(ArgTy, ArgLoc))
5180 return true;
5181
5182 Value *V;
5183 if (ArgTy->isMetadataTy()) {
5184 if (ParseMetadataAsValue(V, PFS))
5185 return true;
5186 } else {
5187 if (ParseValue(ArgTy, V, PFS))
5188 return true;
5189 }
5190 Args.push_back(V);
5191 }
5192
5193 Lex.Lex(); // Lex the ']'.
5194 return false;
5195}
5196
5197/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005198/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005199bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005200 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005201
David Majnemer8a1c45d2015-12-12 05:38:55 +00005202 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5203 return true;
5204
5205 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005206 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005207
5208 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5209 return true;
5210
5211 BasicBlock *UnwindBB = nullptr;
5212 if (Lex.getKind() == lltok::kw_to) {
5213 Lex.Lex();
5214 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5215 return true;
5216 } else {
5217 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5218 return true;
5219 }
5220 }
5221
David Majnemer8a1c45d2015-12-12 05:38:55 +00005222 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005223 return false;
5224}
5225
5226/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005227/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005228bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005229 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005230
David Majnemer8a1c45d2015-12-12 05:38:55 +00005231 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5232 return true;
5233
5234 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005235 return true;
5236
David Majnemer0bc0eef2015-08-15 02:46:08 +00005237 BasicBlock *BB;
5238 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5239 ParseTypeAndBasicBlock(BB, PFS))
5240 return true;
5241
David Majnemer8a1c45d2015-12-12 05:38:55 +00005242 Inst = CatchReturnInst::Create(CatchPad, BB);
5243 return false;
5244}
5245
5246/// ParseCatchSwitch
5247/// ::= 'catchswitch' within Parent
5248bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5249 Value *ParentPad;
5250 LocTy BBLoc;
5251
5252 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5253 return true;
5254
5255 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5256 Lex.getKind() != lltok::LocalVarID)
5257 return TokError("expected scope value for catchswitch");
5258
5259 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5260 return true;
5261
5262 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5263 return true;
5264
5265 SmallVector<BasicBlock *, 32> Table;
5266 do {
5267 BasicBlock *DestBB;
5268 if (ParseTypeAndBasicBlock(DestBB, PFS))
5269 return true;
5270 Table.push_back(DestBB);
5271 } while (EatIfPresent(lltok::comma));
5272
5273 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5274 return true;
5275
5276 if (ParseToken(lltok::kw_unwind,
5277 "expected 'unwind' after catchswitch scope"))
5278 return true;
5279
5280 BasicBlock *UnwindBB = nullptr;
5281 if (EatIfPresent(lltok::kw_to)) {
5282 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5283 return true;
5284 } else {
5285 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5286 return true;
5287 }
5288
5289 auto *CatchSwitch =
5290 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5291 for (BasicBlock *DestBB : Table)
5292 CatchSwitch->addHandler(DestBB);
5293 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005294 return false;
5295}
5296
5297/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005298/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005299bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005300 Value *CatchSwitch = nullptr;
5301
5302 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5303 return true;
5304
5305 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5306 return TokError("expected scope value for catchpad");
5307
5308 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5309 return true;
5310
David Majnemer654e1302015-07-31 17:58:14 +00005311 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005312 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005313 return true;
5314
David Majnemer8a1c45d2015-12-12 05:38:55 +00005315 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005316 return false;
5317}
5318
David Majnemer654e1302015-07-31 17:58:14 +00005319/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005320/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005321bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005322 Value *ParentPad = nullptr;
5323
5324 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5325 return true;
5326
5327 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5328 Lex.getKind() != lltok::LocalVarID)
5329 return TokError("expected scope value for cleanuppad");
5330
5331 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5332 return true;
5333
David Majnemer654e1302015-07-31 17:58:14 +00005334 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005335 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005336 return true;
5337
David Majnemer8a1c45d2015-12-12 05:38:55 +00005338 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005339 return false;
5340}
5341
Chris Lattnerac161bf2009-01-02 07:01:27 +00005342//===----------------------------------------------------------------------===//
5343// Binary Operators.
5344//===----------------------------------------------------------------------===//
5345
5346/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005347/// ::= ArithmeticOps TypeAndValue ',' Value
5348///
5349/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5350/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005351bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005352 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 LocTy Loc; Value *LHS, *RHS;
5354 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5355 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5356 ParseValue(LHS->getType(), RHS, PFS))
5357 return true;
5358
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005359 bool Valid;
5360 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005361 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005362 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005363 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5364 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005365 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005366 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5367 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005368 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005369
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005370 if (!Valid)
5371 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005372
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5374 return false;
5375}
5376
5377/// ParseLogical
5378/// ::= ArithmeticOps TypeAndValue ',' Value {
5379bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5380 unsigned Opc) {
5381 LocTy Loc; Value *LHS, *RHS;
5382 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5383 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5384 ParseValue(LHS->getType(), RHS, PFS))
5385 return true;
5386
Duncan Sands9dff9be2010-02-15 16:12:20 +00005387 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005388 return Error(Loc,"instruction requires integer or integer vector operands");
5389
5390 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5391 return false;
5392}
5393
5394
5395/// ParseCompare
5396/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5397/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005398bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5399 unsigned Opc) {
5400 // Parse the integer/fp comparison predicate.
5401 LocTy Loc;
5402 unsigned Pred;
5403 Value *LHS, *RHS;
5404 if (ParseCmpPredicate(Pred, Opc) ||
5405 ParseTypeAndValue(LHS, Loc, PFS) ||
5406 ParseToken(lltok::comma, "expected ',' after compare value") ||
5407 ParseValue(LHS->getType(), RHS, PFS))
5408 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005409
Chris Lattnerac161bf2009-01-02 07:01:27 +00005410 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005411 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005412 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005413 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005414 } else {
5415 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005416 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005417 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005418 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005419 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420 }
5421 return false;
5422}
5423
5424//===----------------------------------------------------------------------===//
5425// Other Instructions.
5426//===----------------------------------------------------------------------===//
5427
5428
5429/// ParseCast
5430/// ::= CastOpc TypeAndValue 'to' Type
5431bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5432 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005433 LocTy Loc;
5434 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005435 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005436 if (ParseTypeAndValue(Op, Loc, PFS) ||
5437 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5438 ParseType(DestTy))
5439 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005440
Chris Lattner89d856e2009-03-01 00:53:13 +00005441 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5442 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005443 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005444 getTypeString(Op->getType()) + "' to '" +
5445 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005446 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005447 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5448 return false;
5449}
5450
5451/// ParseSelect
5452/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5453bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5454 LocTy Loc;
5455 Value *Op0, *Op1, *Op2;
5456 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5457 ParseToken(lltok::comma, "expected ',' after select condition") ||
5458 ParseTypeAndValue(Op1, PFS) ||
5459 ParseToken(lltok::comma, "expected ',' after select value") ||
5460 ParseTypeAndValue(Op2, PFS))
5461 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005462
Chris Lattnerac161bf2009-01-02 07:01:27 +00005463 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5464 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005465
Chris Lattnerac161bf2009-01-02 07:01:27 +00005466 Inst = SelectInst::Create(Op0, Op1, Op2);
5467 return false;
5468}
5469
Chris Lattnerb55ab542009-01-05 08:18:44 +00005470/// ParseVA_Arg
5471/// ::= 'va_arg' TypeAndValue ',' Type
5472bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005473 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005474 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005475 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005476 if (ParseTypeAndValue(Op, PFS) ||
5477 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005478 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005479 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005480
Chris Lattnerb55ab542009-01-05 08:18:44 +00005481 if (!EltTy->isFirstClassType())
5482 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005483
5484 Inst = new VAArgInst(Op, EltTy);
5485 return false;
5486}
5487
5488/// ParseExtractElement
5489/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5490bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5491 LocTy Loc;
5492 Value *Op0, *Op1;
5493 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5494 ParseToken(lltok::comma, "expected ',' after extract value") ||
5495 ParseTypeAndValue(Op1, PFS))
5496 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005497
Chris Lattnerac161bf2009-01-02 07:01:27 +00005498 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5499 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005500
Eric Christopherc9742252009-07-25 02:28:41 +00005501 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005502 return false;
5503}
5504
5505/// ParseInsertElement
5506/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5507bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5508 LocTy Loc;
5509 Value *Op0, *Op1, *Op2;
5510 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5511 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5512 ParseTypeAndValue(Op1, PFS) ||
5513 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5514 ParseTypeAndValue(Op2, PFS))
5515 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005516
Chris Lattnerac161bf2009-01-02 07:01:27 +00005517 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005518 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005519
Chris Lattnerac161bf2009-01-02 07:01:27 +00005520 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5521 return false;
5522}
5523
5524/// ParseShuffleVector
5525/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5526bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5527 LocTy Loc;
5528 Value *Op0, *Op1, *Op2;
5529 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5530 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5531 ParseTypeAndValue(Op1, PFS) ||
5532 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5533 ParseTypeAndValue(Op2, PFS))
5534 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
Chris Lattnerac161bf2009-01-02 07:01:27 +00005536 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005537 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005538
Chris Lattnerac161bf2009-01-02 07:01:27 +00005539 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5540 return false;
5541}
5542
5543/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005544/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005545int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005546 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005547 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005548
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005549 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005550 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5551 ParseValue(Ty, Op0, PFS) ||
5552 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005553 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005554 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5555 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005556
Chris Lattnerf4f03422009-12-30 05:27:33 +00005557 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5559 while (1) {
5560 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005561
Chris Lattner3822f632009-01-02 08:05:26 +00005562 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005563 break;
5564
Chris Lattnerf4f03422009-12-30 05:27:33 +00005565 if (Lex.getKind() == lltok::MetadataVar) {
5566 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005567 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005568 }
Devang Patel8f842d32009-10-16 18:45:49 +00005569
Chris Lattner3822f632009-01-02 08:05:26 +00005570 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005571 ParseValue(Ty, Op0, PFS) ||
5572 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005573 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005574 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5575 return true;
5576 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005577
Chris Lattnerac161bf2009-01-02 07:01:27 +00005578 if (!Ty->isFirstClassType())
5579 return Error(TypeLoc, "phi node must have first class type");
5580
Jay Foad52131342011-03-30 11:28:46 +00005581 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5583 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5584 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005585 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005586}
5587
Bill Wendlingfae14752011-08-12 20:24:12 +00005588/// ParseLandingPad
5589/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5590/// Clause
5591/// ::= 'catch' TypeAndValue
5592/// ::= 'filter'
5593/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5594bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005595 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005596
David Majnemer7fddecc2015-06-17 20:52:32 +00005597 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005598 return true;
5599
David Majnemer7fddecc2015-06-17 20:52:32 +00005600 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005601 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5602
5603 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5604 LandingPadInst::ClauseType CT;
5605 if (EatIfPresent(lltok::kw_catch))
5606 CT = LandingPadInst::Catch;
5607 else if (EatIfPresent(lltok::kw_filter))
5608 CT = LandingPadInst::Filter;
5609 else
5610 return TokError("expected 'catch' or 'filter' clause type");
5611
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005612 Value *V;
5613 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005614 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005615 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005616
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005617 // A 'catch' type expects a non-array constant. A filter clause expects an
5618 // array constant.
5619 if (CT == LandingPadInst::Catch) {
5620 if (isa<ArrayType>(V->getType()))
5621 Error(VLoc, "'catch' clause has an invalid type");
5622 } else {
5623 if (!isa<ArrayType>(V->getType()))
5624 Error(VLoc, "'filter' clause has an invalid type");
5625 }
5626
Owen Andersonf8f259d2015-03-09 07:13:42 +00005627 Constant *CV = dyn_cast<Constant>(V);
5628 if (!CV)
5629 return Error(VLoc, "clause argument must be a constant");
5630 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005631 }
5632
Owen Andersonf8f259d2015-03-09 07:13:42 +00005633 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005634 return false;
5635}
5636
Chris Lattnerac161bf2009-01-02 07:01:27 +00005637/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005638/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5639/// OptionalAttrs Type Value ParameterList OptionalAttrs
5640/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5641/// OptionalAttrs Type Value ParameterList OptionalAttrs
5642/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5643/// OptionalAttrs Type Value ParameterList OptionalAttrs
5644/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5645/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005646bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005647 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005648 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005649 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005650 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005651 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005652 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005653 LocTy RetTypeLoc;
5654 ValID CalleeID;
5655 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005656 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005658
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005659 if (TCK != CallInst::TCK_None &&
5660 ParseToken(lltok::kw_call,
5661 "expected 'tail call', 'musttail call', or 'notail call'"))
5662 return true;
5663
5664 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5665
5666 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005667 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005668 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005669 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5670 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005671 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5672 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005673 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005674
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005675 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5676 return Error(CallLoc, "fast-math-flags specified for call without "
5677 "floating-point scalar or vector return type");
5678
Chris Lattnerac161bf2009-01-02 07:01:27 +00005679 // If RetType is a non-function pointer type, then this is the short syntax
5680 // for the call, which means that RetType is just the return type. Infer the
5681 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005682 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5683 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005685 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005686 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5687 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005688
Chris Lattnerac161bf2009-01-02 07:01:27 +00005689 if (!FunctionType::isValidReturnType(RetType))
5690 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005691
Owen Anderson4056ca92009-07-29 22:17:13 +00005692 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005694
David Blaikie41ba2b42015-07-27 23:32:19 +00005695 CalleeID.FTy = Ty;
5696
Chris Lattnerac161bf2009-01-02 07:01:27 +00005697 // Look up the callee.
5698 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005699 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5700 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005701
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005702 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005703 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005704 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005705 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5706 AttributeSet::ReturnIndex,
5707 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005708
Chris Lattnerac161bf2009-01-02 07:01:27 +00005709 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005710
Chris Lattnerac161bf2009-01-02 07:01:27 +00005711 // Loop through FunctionType's arguments and ensure they are specified
5712 // correctly. Also, gather any parameter attributes.
5713 FunctionType::param_iterator I = Ty->param_begin();
5714 FunctionType::param_iterator E = Ty->param_end();
5715 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005716 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 if (I != E) {
5718 ExpectedTy = *I++;
5719 } else if (!Ty->isVarArg()) {
5720 return Error(ArgList[i].Loc, "too many arguments specified");
5721 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005722
Chris Lattnerac161bf2009-01-02 07:01:27 +00005723 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5724 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005725 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005726 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005727 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5728 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005729 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5730 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005731 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005732
Chris Lattnerac161bf2009-01-02 07:01:27 +00005733 if (I != E)
5734 return Error(CallLoc, "not enough parameters specified for call");
5735
David Majnemer8d22abd2015-02-23 00:01:32 +00005736 if (FnAttrs.hasAttributes()) {
5737 if (FnAttrs.hasAlignmentAttr())
5738 return Error(CallLoc, "call instructions may not have an alignment");
5739
Bill Wendlingf5075a42013-01-27 02:24:02 +00005740 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5741 AttributeSet::FunctionIndex,
5742 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005743 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005744
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005745 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005746 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005747
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005748 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005749 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005750 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005751 if (FMF.any())
5752 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005754 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005755 Inst = CI;
5756 return false;
5757}
5758
5759//===----------------------------------------------------------------------===//
5760// Memory Instructions.
5761//===----------------------------------------------------------------------===//
5762
5763/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005764/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005765int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005766 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005767 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005769 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005770
5771 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5772
David Majnemera3b0eb22015-02-16 08:38:03 +00005773 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005774
David Majnemera3b0eb22015-02-16 08:38:03 +00005775 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5776 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005777
Chris Lattnerb2f39502009-12-30 05:44:30 +00005778 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005779 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005780 if (Lex.getKind() == lltok::kw_align) {
5781 if (ParseOptionalAlignment(Alignment)) return true;
5782 } else if (Lex.getKind() == lltok::MetadataVar) {
5783 AteExtraComma = true;
5784 } else {
5785 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5786 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5787 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788 }
5789 }
5790
Dan Gohman2140a742010-05-28 01:14:11 +00005791 if (Size && !Size->getType()->isIntegerTy())
5792 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005793
Reid Kleckner436c42e2014-01-17 23:58:17 +00005794 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5795 AI->setUsedWithInAlloca(IsInAlloca);
5796 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005797 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005798}
5799
5800/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005801/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005802/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005803/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005804int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005805 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005806 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005807 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005808 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005809 AtomicOrdering Ordering = NotAtomic;
5810 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005811
5812 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005813 isAtomic = true;
5814 Lex.Lex();
5815 }
5816
Chris Lattnerbc639292011-11-27 06:56:53 +00005817 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005818 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005819 isVolatile = true;
5820 Lex.Lex();
5821 }
5822
David Blaikie15d9a4c2015-04-06 20:59:48 +00005823 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005824 LocTy ExplicitTypeLoc = Lex.getLoc();
5825 if (ParseType(Ty) ||
5826 ParseToken(lltok::comma, "expected comma after load's type") ||
5827 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005828 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005829 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5830 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005831
David Blaikie15d9a4c2015-04-06 20:59:48 +00005832 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005834 if (isAtomic && !Alignment)
5835 return Error(Loc, "atomic load must have explicit non-zero alignment");
5836 if (Ordering == Release || Ordering == AcquireRelease)
5837 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005838
David Blaikiea79ac142015-02-27 21:17:42 +00005839 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5840 return Error(ExplicitTypeLoc,
5841 "explicit pointee type doesn't match operand's pointee type");
5842
David Blaikie15d9a4c2015-04-06 20:59:48 +00005843 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005844 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005845}
5846
5847/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005848
5849/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5850/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005851/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005852int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005853 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005854 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005855 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005856 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005857 AtomicOrdering Ordering = NotAtomic;
5858 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005859
5860 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005861 isAtomic = true;
5862 Lex.Lex();
5863 }
5864
Chris Lattnerbc639292011-11-27 06:56:53 +00005865 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005866 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005867 isVolatile = true;
5868 Lex.Lex();
5869 }
5870
Chris Lattnerac161bf2009-01-02 07:01:27 +00005871 if (ParseTypeAndValue(Val, Loc, PFS) ||
5872 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005873 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005874 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005875 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005876 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005877
Duncan Sands19d0b472010-02-16 11:11:14 +00005878 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005879 return Error(PtrLoc, "store operand must be a pointer");
5880 if (!Val->getType()->isFirstClassType())
5881 return Error(Loc, "store operand must be a first class value");
5882 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5883 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005884 if (isAtomic && !Alignment)
5885 return Error(Loc, "atomic store must have explicit non-zero alignment");
5886 if (Ordering == Acquire || Ordering == AcquireRelease)
5887 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005888
Eli Friedman59b66882011-08-09 23:02:53 +00005889 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005890 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005891}
5892
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005893/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005894/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5895/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005896int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005897 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5898 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005899 AtomicOrdering SuccessOrdering = NotAtomic;
5900 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005901 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005902 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005903 bool isWeak = false;
5904
5905 if (EatIfPresent(lltok::kw_weak))
5906 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005907
5908 if (EatIfPresent(lltok::kw_volatile))
5909 isVolatile = true;
5910
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005911 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5912 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5913 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5914 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5915 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005916 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5917 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005918 return true;
5919
Tim Northovere94a5182014-03-11 10:48:52 +00005920 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005921 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005922 if (SuccessOrdering < FailureOrdering)
5923 return TokError("cmpxchg must be at least as ordered on success as failure");
5924 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5925 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005926 if (!Ptr->getType()->isPointerTy())
5927 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5928 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5929 return Error(CmpLoc, "compare value and pointer type do not match");
5930 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5931 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00005932 if (!New->getType()->isFirstClassType())
5933 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00005934 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5935 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005936 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005937 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005938 Inst = CXI;
5939 return AteExtraComma ? InstExtraComma : InstNormal;
5940}
5941
5942/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005943/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5944/// 'singlethread'? AtomicOrdering
5945int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005946 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5947 bool AteExtraComma = false;
5948 AtomicOrdering Ordering = NotAtomic;
5949 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005950 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005951 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005952
5953 if (EatIfPresent(lltok::kw_volatile))
5954 isVolatile = true;
5955
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005956 switch (Lex.getKind()) {
5957 default: return TokError("expected binary operation in atomicrmw");
5958 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5959 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5960 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5961 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5962 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5963 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5964 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5965 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5966 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5967 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5968 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5969 }
5970 Lex.Lex(); // Eat the operation.
5971
5972 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5973 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5974 ParseTypeAndValue(Val, ValLoc, PFS) ||
5975 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5976 return true;
5977
5978 if (Ordering == Unordered)
5979 return TokError("atomicrmw cannot be unordered");
5980 if (!Ptr->getType()->isPointerTy())
5981 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5982 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5983 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5984 if (!Val->getType()->isIntegerTy())
5985 return Error(ValLoc, "atomicrmw operand must be an integer");
5986 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5987 if (Size < 8 || (Size & (Size - 1)))
5988 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5989 " integer");
5990
5991 AtomicRMWInst *RMWI =
5992 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5993 RMWI->setVolatile(isVolatile);
5994 Inst = RMWI;
5995 return AteExtraComma ? InstExtraComma : InstNormal;
5996}
5997
Eli Friedmanfee02c62011-07-25 23:16:38 +00005998/// ParseFence
5999/// ::= 'fence' 'singlethread'? AtomicOrdering
6000int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6001 AtomicOrdering Ordering = NotAtomic;
6002 SynchronizationScope Scope = CrossThread;
6003 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6004 return true;
6005
6006 if (Ordering == Unordered)
6007 return TokError("fence cannot be unordered");
6008 if (Ordering == Monotonic)
6009 return TokError("fence cannot be monotonic");
6010
6011 Inst = new FenceInst(Context, Ordering, Scope);
6012 return InstNormal;
6013}
6014
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006016/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006017int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006018 Value *Ptr = nullptr;
6019 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006020 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006021
Dan Gohman16cbbe42009-07-29 15:58:36 +00006022 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006023
David Blaikie79e6c742015-02-27 19:29:02 +00006024 Type *Ty = nullptr;
6025 LocTy ExplicitTypeLoc = Lex.getLoc();
6026 if (ParseType(Ty) ||
6027 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6028 ParseTypeAndValue(Ptr, Loc, PFS))
6029 return true;
6030
Eli Benderskyd9806682013-04-22 17:03:42 +00006031 Type *BaseType = Ptr->getType();
6032 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6033 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006034 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006035
David Blaikie8d757942015-03-09 23:08:44 +00006036 if (Ty != BasePointerType->getElementType())
6037 return Error(ExplicitTypeLoc,
6038 "explicit pointee type doesn't match operand's pointee type");
6039
Chris Lattnerac161bf2009-01-02 07:01:27 +00006040 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006041 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006042 // GEP returns a vector of pointers if at least one of parameters is a vector.
6043 // All vector parameters should have the same vector width.
6044 unsigned GEPWidth = BaseType->isVectorTy() ?
6045 BaseType->getVectorNumElements() : 0;
6046
Chris Lattner3822f632009-01-02 08:05:26 +00006047 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006048 if (Lex.getKind() == lltok::MetadataVar) {
6049 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006050 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006051 }
Chris Lattner3822f632009-01-02 08:05:26 +00006052 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006053 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006054 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006055
Nadav Rotem3924cb02011-12-05 06:29:09 +00006056 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006057 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6058 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006059 return Error(EltLoc,
6060 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006061 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006062 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006063 Indices.push_back(Val);
6064 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006065
Craig Toppere3dcce92015-08-01 22:20:21 +00006066 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006067 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006068 return Error(Loc, "base element of getelementptr must be sized");
6069
David Blaikied33bad32015-04-17 22:32:13 +00006070 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006071 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006072 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006073 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006074 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006075 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006076}
6077
6078/// ParseExtractValue
6079/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006080int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006081 Value *Val; LocTy Loc;
6082 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006083 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006084 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006085 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006086 return true;
6087
Chris Lattner392be582010-02-12 20:49:41 +00006088 if (!Val->getType()->isAggregateType())
6089 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006090
Jay Foad57aa6362011-07-13 10:26:04 +00006091 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006092 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006093 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006094 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006095}
6096
6097/// ParseInsertValue
6098/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006099int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006100 Value *Val0, *Val1; LocTy Loc0, Loc1;
6101 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006102 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006103 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6104 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6105 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006106 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006107 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006108
Chris Lattner392be582010-02-12 20:49:41 +00006109 if (!Val0->getType()->isAggregateType())
6110 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006111
David Majnemer30074532015-02-11 07:43:58 +00006112 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6113 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006114 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006115 if (IndexedType != Val1->getType())
6116 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6117 getTypeString(Val1->getType()) + "' instead of '" +
6118 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006119 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006120 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006121}
Nick Lewycky49f89192009-04-04 07:22:01 +00006122
6123//===----------------------------------------------------------------------===//
6124// Embedded metadata.
6125//===----------------------------------------------------------------------===//
6126
6127/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006128/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006129/// Element
6130/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006131bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006132 if (ParseToken(lltok::lbrace, "expected '{' here"))
6133 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006134
Dan Gohman1e0213a2010-07-13 19:33:27 +00006135 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006136 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006137 return false;
6138
Nick Lewycky49f89192009-04-04 07:22:01 +00006139 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006140 // Null is a special case since it is typeless.
6141 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006142 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006143 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006144 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006145
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006146 Metadata *MD;
6147 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006148 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006149 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006150 } while (EatIfPresent(lltok::comma));
6151
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006152 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006153}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006154
6155//===----------------------------------------------------------------------===//
6156// Use-list order directives.
6157//===----------------------------------------------------------------------===//
6158bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6159 SMLoc Loc) {
6160 if (V->use_empty())
6161 return Error(Loc, "value has no uses");
6162
6163 unsigned NumUses = 0;
6164 SmallDenseMap<const Use *, unsigned, 16> Order;
6165 for (const Use &U : V->uses()) {
6166 if (++NumUses > Indexes.size())
6167 break;
6168 Order[&U] = Indexes[NumUses - 1];
6169 }
6170 if (NumUses < 2)
6171 return Error(Loc, "value only has one use");
6172 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6173 return Error(Loc, "wrong number of indexes, expected " +
6174 Twine(std::distance(V->use_begin(), V->use_end())));
6175
6176 V->sortUseList([&](const Use &L, const Use &R) {
6177 return Order.lookup(&L) < Order.lookup(&R);
6178 });
6179 return false;
6180}
6181
6182/// ParseUseListOrderIndexes
6183/// ::= '{' uint32 (',' uint32)+ '}'
6184bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6185 SMLoc Loc = Lex.getLoc();
6186 if (ParseToken(lltok::lbrace, "expected '{' here"))
6187 return true;
6188 if (Lex.getKind() == lltok::rbrace)
6189 return Lex.Error("expected non-empty list of uselistorder indexes");
6190
6191 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6192 // indexes should be distinct numbers in the range [0, size-1], and should
6193 // not be in order.
6194 unsigned Offset = 0;
6195 unsigned Max = 0;
6196 bool IsOrdered = true;
6197 assert(Indexes.empty() && "Expected empty order vector");
6198 do {
6199 unsigned Index;
6200 if (ParseUInt32(Index))
6201 return true;
6202
6203 // Update consistency checks.
6204 Offset += Index - Indexes.size();
6205 Max = std::max(Max, Index);
6206 IsOrdered &= Index == Indexes.size();
6207
6208 Indexes.push_back(Index);
6209 } while (EatIfPresent(lltok::comma));
6210
6211 if (ParseToken(lltok::rbrace, "expected '}' here"))
6212 return true;
6213
6214 if (Indexes.size() < 2)
6215 return Error(Loc, "expected >= 2 uselistorder indexes");
6216 if (Offset != 0 || Max >= Indexes.size())
6217 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6218 if (IsOrdered)
6219 return Error(Loc, "expected uselistorder indexes to change the order");
6220
6221 return false;
6222}
6223
6224/// ParseUseListOrder
6225/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6226bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6227 SMLoc Loc = Lex.getLoc();
6228 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6229 return true;
6230
6231 Value *V;
6232 SmallVector<unsigned, 16> Indexes;
6233 if (ParseTypeAndValue(V, PFS) ||
6234 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6235 ParseUseListOrderIndexes(Indexes))
6236 return true;
6237
6238 return sortUseListOrder(V, Indexes, Loc);
6239}
6240
6241/// ParseUseListOrderBB
6242/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6243bool LLParser::ParseUseListOrderBB() {
6244 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6245 SMLoc Loc = Lex.getLoc();
6246 Lex.Lex();
6247
6248 ValID Fn, Label;
6249 SmallVector<unsigned, 16> Indexes;
6250 if (ParseValID(Fn) ||
6251 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6252 ParseValID(Label) ||
6253 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6254 ParseUseListOrderIndexes(Indexes))
6255 return true;
6256
6257 // Check the function.
6258 GlobalValue *GV;
6259 if (Fn.Kind == ValID::t_GlobalName)
6260 GV = M->getNamedValue(Fn.StrVal);
6261 else if (Fn.Kind == ValID::t_GlobalID)
6262 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6263 else
6264 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6265 if (!GV)
6266 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6267 auto *F = dyn_cast<Function>(GV);
6268 if (!F)
6269 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6270 if (F->isDeclaration())
6271 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6272
6273 // Check the basic block.
6274 if (Label.Kind == ValID::t_LocalID)
6275 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6276 if (Label.Kind != ValID::t_LocalName)
6277 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6278 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6279 if (!V)
6280 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6281 if (!isa<BasicBlock>(V))
6282 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6283
6284 return sortUseListOrder(V, Indexes, Loc);
6285}