blob: 717eb0e00f4f414eccf1cf93adddb59399719cfa [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000127 AttrBuilder B;
128
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000131
132 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000133 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136
137 FnAttrs.merge(B);
138
139 // If the alignment was parsed as an attribute, move to the alignment
140 // field.
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
144 }
145
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000150 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000153 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000158 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000161 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000164 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
167 Attrs.merge(B);
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000169 } else {
170 llvm_unreachable("invalid object with forward attribute group reference");
171 }
172 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000173
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000179
David Majnemer19b51052015-02-11 07:43:56 +0000180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
195
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
199 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000204 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Devang Pateld2541152009-07-08 19:23:54 +0000206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
215 }
Devang Pateld2541152009-07-08 19:23:54 +0000216
Mehdi Aminie4709272016-09-14 22:29:59 +0000217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000224
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000228
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
237 }
238 }
239
Manman Ren8b4306c2013-12-02 21:29:56 +0000240 UpgradeDebugInfo(*M);
241
Manman Renb5d7ff42016-05-25 23:14:48 +0000242 UpgradeModuleFlags(*M);
243
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000244 if (!Slots)
245 return false;
246 // Initialize the slot mapping.
247 // Because by this point we've parsed and validated everything, we can "steal"
248 // the mapping from LLParser as it doesn't need it anymore.
249 Slots->GlobalValues = std::move(NumberedVals);
250 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000251 for (const auto &I : NamedTypes)
252 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
253 for (const auto &I : NumberedTypes)
254 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000255
Chris Lattnerac161bf2009-01-02 07:01:27 +0000256 return false;
257}
258
259//===----------------------------------------------------------------------===//
260// Top-Level Entities
261//===----------------------------------------------------------------------===//
262
263bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000264 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000265 switch (Lex.getKind()) {
266 default: return TokError("expected top-level entity");
267 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 case lltok::kw_declare: if (ParseDeclare()) return true; break;
269 case lltok::kw_define: if (ParseDefine()) return true; break;
270 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
271 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000272 case lltok::kw_source_filename:
273 if (ParseSourceFileName())
274 return true;
275 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000276 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000277 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000278 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000279 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000281 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000282 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000283 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000284 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000285 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
286 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000287 if (ParseUseListOrderBB())
288 return true;
289 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 }
291 }
292}
293
Chris Lattnerac161bf2009-01-02 07:01:27 +0000294/// toplevelentity
295/// ::= 'module' 'asm' STRINGCONSTANT
296bool LLParser::ParseModuleAsm() {
297 assert(Lex.getKind() == lltok::kw_module);
298 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000299
300 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000301 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
302 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000303
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000304 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305 return false;
306}
307
308/// toplevelentity
309/// ::= 'target' 'triple' '=' STRINGCONSTANT
310/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
311bool LLParser::ParseTargetDefinition() {
312 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000313 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 switch (Lex.Lex()) {
315 default: return TokError("unknown target property");
316 case lltok::kw_triple:
317 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000318 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
319 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000321 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return false;
323 case lltok::kw_datalayout:
324 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000325 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
326 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000328 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return false;
330 }
331}
332
Bill Wendling706d3d62012-11-28 08:41:48 +0000333/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000334/// ::= 'source_filename' '=' STRINGCONSTANT
335bool LLParser::ParseSourceFileName() {
336 assert(Lex.getKind() == lltok::kw_source_filename);
337 std::string Str;
338 Lex.Lex();
339 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
340 ParseStringConstant(Str))
341 return true;
342 M->setSourceFileName(Str);
343 return false;
344}
345
346/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000347/// ::= 'deplibs' '=' '[' ']'
348/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
349/// FIXME: Remove in 4.0. Currently parse, but ignore.
350bool LLParser::ParseDepLibs() {
351 assert(Lex.getKind() == lltok::kw_deplibs);
352 Lex.Lex();
353 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
354 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
355 return true;
356
357 if (EatIfPresent(lltok::rsquare))
358 return false;
359
360 do {
361 std::string Str;
362 if (ParseStringConstant(Str)) return true;
363 } while (EatIfPresent(lltok::comma));
364
365 return ParseToken(lltok::rsquare, "expected ']' at end of list");
366}
367
Dan Gohman466876b2009-08-12 23:32:33 +0000368/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000369/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000371 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000372 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000373 Lex.Lex(); // eat LocalVarID;
374
375 if (ParseToken(lltok::equal, "expected '=' after name") ||
376 ParseToken(lltok::kw_type, "expected 'type' after '='"))
377 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378
Craig Topper2617dcc2014-04-15 06:32:26 +0000379 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000380 if (ParseStructDefinition(TypeLoc, "",
381 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000382
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383 if (!isa<StructType>(Result)) {
384 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
385 if (Entry.first)
386 return Error(TypeLoc, "non-struct types may not be recursive");
387 Entry.first = Result;
388 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000390
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391 return false;
392}
393
394/// toplevelentity
395/// ::= LocalVar '=' 'type' type
396bool LLParser::ParseNamedType() {
397 std::string Name = Lex.getStrVal();
398 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000399 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000400
Chris Lattner3822f632009-01-02 08:05:26 +0000401 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000402 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000403 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000404
Craig Topper2617dcc2014-04-15 06:32:26 +0000405 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000406 if (ParseStructDefinition(NameLoc, Name,
407 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 if (!isa<StructType>(Result)) {
410 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
411 if (Entry.first)
412 return Error(NameLoc, "non-struct types may not be recursive");
413 Entry.first = Result;
414 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000415 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000417 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000418}
419
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420/// toplevelentity
421/// ::= 'declare' FunctionHeader
422bool LLParser::ParseDeclare() {
423 assert(Lex.getKind() == lltok::kw_declare);
424 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000425
Peter Collingbourne21521892016-06-21 23:42:48 +0000426 std::vector<std::pair<unsigned, MDNode *>> MDs;
427 while (Lex.getKind() == lltok::MetadataVar) {
428 unsigned MDK;
429 MDNode *N;
430 if (ParseMetadataAttachment(MDK, N))
431 return true;
432 MDs.push_back({MDK, N});
433 }
434
Chris Lattnerac161bf2009-01-02 07:01:27 +0000435 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000436 if (ParseFunctionHeader(F, false))
437 return true;
438 for (auto &MD : MDs)
439 F->addMetadata(MD.first, *MD.second);
440 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441}
442
443/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000444/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445bool LLParser::ParseDefine() {
446 assert(Lex.getKind() == lltok::kw_define);
447 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000448
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000450 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000451 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000452 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000453}
454
Chris Lattner3822f632009-01-02 08:05:26 +0000455/// ParseGlobalType
456/// ::= 'constant'
457/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458bool LLParser::ParseGlobalType(bool &IsConstant) {
459 if (Lex.getKind() == lltok::kw_constant)
460 IsConstant = true;
461 else if (Lex.getKind() == lltok::kw_global)
462 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000463 else {
464 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000466 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 Lex.Lex();
468 return false;
469}
470
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000471bool LLParser::ParseOptionalUnnamedAddr(
472 GlobalVariable::UnnamedAddr &UnnamedAddr) {
473 if (EatIfPresent(lltok::kw_unnamed_addr))
474 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
475 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
476 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
477 else
478 UnnamedAddr = GlobalValue::UnnamedAddr::None;
479 return false;
480}
481
Dan Gohman466876b2009-08-12 23:32:33 +0000482/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000483/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000484/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000486/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000487/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
488/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000489bool LLParser::ParseUnnamedGlobal() {
490 unsigned VarID = NumberedVals.size();
491 std::string Name;
492 LocTy NameLoc = Lex.getLoc();
493
494 // Handle the GlobalID form.
495 if (Lex.getKind() == lltok::GlobalID) {
496 if (Lex.getUIntVal() != VarID)
497 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000498 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000499 Lex.Lex(); // eat GlobalID;
500
501 if (ParseToken(lltok::equal, "expected '=' after name"))
502 return true;
503 }
504
505 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000506 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000507 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000508 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000509 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000510 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000511 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000512
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000513 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000514 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000515 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000516
517 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
518 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000519}
520
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000522/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000523/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
524/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000525bool LLParser::ParseNamedGlobal() {
526 assert(Lex.getKind() == lltok::GlobalVar);
527 LocTy NameLoc = Lex.getLoc();
528 std::string Name = Lex.getStrVal();
529 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000530
Chris Lattnerac161bf2009-01-02 07:01:27 +0000531 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000532 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000533 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000534 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000535 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000536 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000537 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000538 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000539
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000540 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000541 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000542 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000543
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000544 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
545 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000546}
547
David Majnemerdad0a642014-06-27 18:19:56 +0000548bool LLParser::parseComdat() {
549 assert(Lex.getKind() == lltok::ComdatVar);
550 std::string Name = Lex.getStrVal();
551 LocTy NameLoc = Lex.getLoc();
552 Lex.Lex();
553
554 if (ParseToken(lltok::equal, "expected '=' here"))
555 return true;
556
557 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
558 return TokError("expected comdat type");
559
560 Comdat::SelectionKind SK;
561 switch (Lex.getKind()) {
562 default:
563 return TokError("unknown selection kind");
564 case lltok::kw_any:
565 SK = Comdat::Any;
566 break;
567 case lltok::kw_exactmatch:
568 SK = Comdat::ExactMatch;
569 break;
570 case lltok::kw_largest:
571 SK = Comdat::Largest;
572 break;
573 case lltok::kw_noduplicates:
574 SK = Comdat::NoDuplicates;
575 break;
576 case lltok::kw_samesize:
577 SK = Comdat::SameSize;
578 break;
579 }
580 Lex.Lex();
581
582 // See if the comdat was forward referenced, if so, use the comdat.
583 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
584 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
585 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
586 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
587
588 Comdat *C;
589 if (I != ComdatSymTab.end())
590 C = &I->second;
591 else
592 C = M->getOrInsertComdat(Name);
593 C->setSelectionKind(SK);
594
595 return false;
596}
597
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000598// MDString:
599// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000600bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000601 std::string Str;
602 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000603 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000604 return false;
605}
606
607// MDNode:
608// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000609bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000610 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000611 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000613 if (ParseUInt32(MID))
614 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000615
Chris Lattner8eff0152010-04-01 05:14:45 +0000616 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000617 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000618 Result = NumberedMetadata[MID];
619 return false;
620 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000621
Chris Lattner8eff0152010-04-01 05:14:45 +0000622 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000623 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000624 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000625
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000626 Result = FwdRef.first.get();
627 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000628 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000629}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000630
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000631/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000632/// !foo = !{ !1, !2 }
633bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000634 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000635 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000636 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000637
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000638 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000639 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000640 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000641 return true;
642
Dan Gohman2637cc12010-07-21 23:38:33 +0000643 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000644 if (Lex.getKind() != lltok::rbrace)
645 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 if (ParseToken(lltok::exclaim, "Expected '!' here"))
647 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000648
Craig Topper2617dcc2014-04-15 06:32:26 +0000649 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000650 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000651 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000652 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000653
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000654 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000655}
656
Devang Patel39e64d42009-07-01 19:21:12 +0000657/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000658/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000659bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000660 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000661 Lex.Lex();
662 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000663
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000665 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000666 ParseToken(lltok::equal, "expected '=' here"))
667 return true;
668
669 // Detect common error, from old metadata syntax.
670 if (Lex.getKind() == lltok::Type)
671 return TokError("unexpected type in metadata definition");
672
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000673 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000674 if (Lex.getKind() == lltok::MetadataVar) {
675 if (ParseSpecializedMDNode(Init, IsDistinct))
676 return true;
677 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
678 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000679 return true;
680
Chris Lattnerfc58af22009-12-30 04:51:58 +0000681 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000683 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000684 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000685 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000686
Chris Lattnerfc58af22009-12-30 04:51:58 +0000687 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
688 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000689 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000690 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000691 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000692 }
693
Devang Patel39e64d42009-07-01 19:21:12 +0000694 return false;
695}
696
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000697static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
698 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
699 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
700}
701
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000702/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000703/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
704/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000705/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000706///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000707/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000708/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000709///
Eric Christopher536f0a92015-05-28 23:07:39 +0000710/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000712bool LLParser::parseIndirectSymbol(
713 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
714 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
715 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000716 bool IsAlias;
717 if (Lex.getKind() == lltok::kw_alias)
718 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000719 else if (Lex.getKind() == lltok::kw_ifunc)
720 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000721 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000722 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000723 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000724
Rafael Espindola78527052013-10-06 15:10:43 +0000725 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
726
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000727 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000728 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000729
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000730 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000731 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000732 "symbol with local linkage must have default visibility");
733
David Blaikie2f408302015-09-11 03:22:04 +0000734 Type *Ty;
735 LocTy ExplicitTypeLoc = Lex.getLoc();
736 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000737 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000738 return true;
739
Rafael Espindola64c1e182014-06-03 02:41:57 +0000740 Constant *Aliasee;
741 LocTy AliaseeLoc = Lex.getLoc();
742 if (Lex.getKind() != lltok::kw_bitcast &&
743 Lex.getKind() != lltok::kw_getelementptr &&
744 Lex.getKind() != lltok::kw_addrspacecast &&
745 Lex.getKind() != lltok::kw_inttoptr) {
746 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000747 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000749 // The bitcast dest type is not present, it is implied by the dest type.
750 ValID ID;
751 if (ParseValID(ID))
752 return true;
753 if (ID.Kind != ValID::t_Constant)
754 return Error(AliaseeLoc, "invalid aliasee");
755 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757
Rafael Espindola64c1e182014-06-03 02:41:57 +0000758 Type *AliaseeType = Aliasee->getType();
759 auto *PTy = dyn_cast<PointerType>(AliaseeType);
760 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000761 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000762 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000763
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000764 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000765 return Error(
766 ExplicitTypeLoc,
767 "explicit pointee type doesn't match operand's pointee type");
768
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000769 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
770 return Error(
771 ExplicitTypeLoc,
772 "explicit pointee type should be a function type");
773
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000774 GlobalValue *GVal = nullptr;
775
776 // See if the alias was forward referenced, if so, prepare to replace the
777 // forward reference.
778 if (!Name.empty()) {
779 GVal = M->getNamedValue(Name);
780 if (GVal) {
781 if (!ForwardRefVals.erase(Name))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
783 }
784 } else {
785 auto I = ForwardRefValIDs.find(NumberedVals.size());
786 if (I != ForwardRefValIDs.end()) {
787 GVal = I->second.first;
788 ForwardRefValIDs.erase(I);
789 }
790 }
791
Chris Lattnerac161bf2009-01-02 07:01:27 +0000792 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000793 std::unique_ptr<GlobalIndirectSymbol> GA;
794 if (IsAlias)
795 GA.reset(GlobalAlias::create(Ty, AddrSpace,
796 (GlobalValue::LinkageTypes)Linkage, Name,
797 Aliasee, /*Parent*/ nullptr));
798 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000799 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
800 (GlobalValue::LinkageTypes)Linkage, Name,
801 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000802 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000803 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000804 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000805 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Rafael Espindola54fc2982015-06-17 17:53:31 +0000807 if (Name.empty())
808 NumberedVals.push_back(GA.get());
809
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000810 if (GVal) {
811 // Verify that types agree.
812 if (GVal->getType() != GA->getType())
813 return Error(
814 ExplicitTypeLoc,
815 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 // If they agree, just RAUW the old value with the alias and remove the
818 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000819 GVal->replaceAllUsesWith(GA.get());
820 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000821 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000822
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000824 if (IsAlias)
825 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
826 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000827 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000828 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Rafael Espindolaaa273822014-05-09 21:49:17 +0000830 // The module owns this now
831 GA.release();
832
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833 return false;
834}
835
836/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000837/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000838/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000839/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Nico Rieck7157bb72014-01-14 15:22:47 +0000840/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000841/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000842/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843///
Eric Christopher536f0a92015-05-28 23:07:39 +0000844/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000845/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000846///
847bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
848 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000849 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000850 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000851 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000852 if (!isValidVisibilityForLinkage(Visibility, Linkage))
853 return Error(NameLoc,
854 "symbol with local linkage must have default visibility");
855
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000857 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000858 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000859 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000860
Craig Topper2617dcc2014-04-15 06:32:26 +0000861 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000862 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000863 ParseOptionalToken(lltok::kw_externally_initialized,
864 IsExternallyInitialized,
865 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 ParseGlobalType(IsConstant) ||
867 ParseType(Ty, TyLoc))
868 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
Chris Lattnerac161bf2009-01-02 07:01:27 +0000870 // If the linkage is specified and is external, then no initializer is
871 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000872 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000873 if (!HasLinkage ||
874 !GlobalValue::isValidDeclarationLinkage(
875 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000876 if (ParseGlobalValue(Ty, Init))
877 return true;
878 }
879
David Majnemer49b3d9b2015-02-16 08:41:08 +0000880 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000881 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
David Majnemer598bd052014-12-09 05:56:09 +0000883 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884
885 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000886 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000887 GVal = M->getNamedValue(Name);
888 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000889 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000890 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000891 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000893 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000895 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000896 ForwardRefValIDs.erase(I);
897 }
898 }
899
David Majnemer598bd052014-12-09 05:56:09 +0000900 GlobalVariable *GV;
901 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000902 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
903 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000904 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000905 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000906 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 return Error(TyLoc,
908 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000909
David Majnemer598bd052014-12-09 05:56:09 +0000910 GV = cast<GlobalVariable>(GVal);
911
Chris Lattnerac161bf2009-01-02 07:01:27 +0000912 // Move the forward-reference to the correct spot in the module.
913 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
914 }
915
916 if (Name.empty())
917 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000918
Chris Lattnerac161bf2009-01-02 07:01:27 +0000919 // Set the parsed properties on the global.
920 if (Init)
921 GV->setInitializer(Init);
922 GV->setConstant(IsConstant);
923 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
924 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000925 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000926 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000927 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000928 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000929
Chris Lattnerac161bf2009-01-02 07:01:27 +0000930 // Parse attributes on the global.
931 while (Lex.getKind() == lltok::comma) {
932 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000933
Chris Lattnerac161bf2009-01-02 07:01:27 +0000934 if (Lex.getKind() == lltok::kw_section) {
935 Lex.Lex();
936 GV->setSection(Lex.getStrVal());
937 if (ParseToken(lltok::StringConstant, "expected global section string"))
938 return true;
939 } else if (Lex.getKind() == lltok::kw_align) {
940 unsigned Alignment;
941 if (ParseOptionalAlignment(Alignment)) return true;
942 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000943 } else if (Lex.getKind() == lltok::MetadataVar) {
944 if (ParseGlobalObjectMetadataAttachment(*GV))
945 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000946 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000947 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000948 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000949 return true;
950 if (C)
951 GV->setComdat(C);
952 else
953 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000954 }
955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000956
Javed Absarf3d79042017-05-11 12:28:08 +0000957 AttrBuilder Attrs;
958 LocTy BuiltinLoc;
959 std::vector<unsigned> FwdRefAttrGrps;
960 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
961 return true;
962 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
963 GV->setAttributes(AttributeSet::get(Context, Attrs));
964 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
965 }
966
Chris Lattnerac161bf2009-01-02 07:01:27 +0000967 return false;
968}
969
Bill Wendling63b88192013-02-06 06:52:58 +0000970/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000971/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000972bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000973 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000974 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000975 Lex.Lex();
976
David Majnemerb39e22b2014-12-09 18:33:57 +0000977 if (Lex.getKind() != lltok::AttrGrpID)
978 return TokError("expected attribute group id");
979
Bill Wendling63b88192013-02-06 06:52:58 +0000980 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000981 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000982 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000983 Lex.Lex();
984
985 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000986 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000987 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000988 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000989 ParseToken(lltok::rbrace, "expected end of attribute group"))
990 return true;
991
Bill Wendlingb32b0412013-02-08 06:32:06 +0000992 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000993 return Error(AttrGrpLoc, "attribute group has no attributes");
994
995 return false;
996}
997
Bill Wendling8b0321d2013-02-08 00:52:31 +0000998/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000999/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001000bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1001 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001002 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001003 bool HaveError = false;
1004
1005 B.clear();
1006
Bill Wendling63b88192013-02-06 06:52:58 +00001007 while (true) {
1008 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001009 if (Token == lltok::kw_builtin)
1010 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001011 switch (Token) {
1012 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001013 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001014 return Error(Lex.getLoc(), "unterminated attribute group");
1015 case lltok::rbrace:
1016 // Finished.
1017 return false;
1018
Bill Wendlingb32b0412013-02-08 06:32:06 +00001019 case lltok::AttrGrpID: {
1020 // Allow a function to reference an attribute group:
1021 //
1022 // define void @foo() #1 { ... }
1023 if (inAttrGrp)
1024 HaveError |=
1025 Error(Lex.getLoc(),
1026 "cannot have an attribute group reference in an attribute group");
1027
1028 unsigned AttrGrpNum = Lex.getUIntVal();
1029 if (inAttrGrp) break;
1030
1031 // Save the reference to the attribute group. We'll fill it in later.
1032 FwdRefAttrGrps.push_back(AttrGrpNum);
1033 break;
1034 }
Bill Wendling63b88192013-02-06 06:52:58 +00001035 // Target-dependent attributes:
1036 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001037 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001038 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001039 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001040 }
1041
1042 // Target-independent attributes:
1043 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001044 // As a hack, we allow function alignment to be initially parsed as an
1045 // attribute on a function declaration/definition or added to an attribute
1046 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001047 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001048 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001049 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001050 if (ParseToken(lltok::equal, "expected '=' here") ||
1051 ParseUInt32(Alignment))
1052 return true;
1053 } else {
1054 if (ParseOptionalAlignment(Alignment))
1055 return true;
1056 }
Bill Wendling63b88192013-02-06 06:52:58 +00001057 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001058 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001059 }
1060 case lltok::kw_alignstack: {
1061 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001062 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001063 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001064 if (ParseToken(lltok::equal, "expected '=' here") ||
1065 ParseUInt32(Alignment))
1066 return true;
1067 } else {
1068 if (ParseOptionalStackAlignment(Alignment))
1069 return true;
1070 }
Bill Wendling63b88192013-02-06 06:52:58 +00001071 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001072 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001073 }
George Burgess IV278199f2016-04-12 01:05:35 +00001074 case lltok::kw_allocsize: {
1075 unsigned ElemSizeArg;
1076 Optional<unsigned> NumElemsArg;
1077 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1078 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1079 return true;
1080 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1081 continue;
1082 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001083 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1084 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1085 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1086 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1087 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001088 case lltok::kw_inaccessiblememonly:
1089 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1090 case lltok::kw_inaccessiblemem_or_argmemonly:
1091 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001092 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1093 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1094 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1095 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1096 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1097 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1098 case lltok::kw_noimplicitfloat:
1099 B.addAttribute(Attribute::NoImplicitFloat); break;
1100 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1101 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1102 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1103 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001104 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001105 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1106 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1107 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1108 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1109 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1110 case lltok::kw_returns_twice:
1111 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001112 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001113 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1114 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1115 case lltok::kw_sspstrong:
1116 B.addAttribute(Attribute::StackProtectStrong); break;
1117 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1118 case lltok::kw_sanitize_address:
1119 B.addAttribute(Attribute::SanitizeAddress); break;
1120 case lltok::kw_sanitize_thread:
1121 B.addAttribute(Attribute::SanitizeThread); break;
1122 case lltok::kw_sanitize_memory:
1123 B.addAttribute(Attribute::SanitizeMemory); break;
1124 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001125 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001126
1127 // Error handling.
1128 case lltok::kw_inreg:
1129 case lltok::kw_signext:
1130 case lltok::kw_zeroext:
1131 HaveError |=
1132 Error(Lex.getLoc(),
1133 "invalid use of attribute on a function");
1134 break;
1135 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001136 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001137 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001138 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001139 case lltok::kw_nest:
1140 case lltok::kw_noalias:
1141 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001142 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001143 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001144 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001145 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001146 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001147 HaveError |=
1148 Error(Lex.getLoc(),
1149 "invalid use of parameter-only attribute on a function");
1150 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001151 }
1152
1153 Lex.Lex();
1154 }
1155}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001156
1157//===----------------------------------------------------------------------===//
1158// GlobalValue Reference/Resolution Routines.
1159//===----------------------------------------------------------------------===//
1160
Karl Schimpf77729782015-09-03 18:06:44 +00001161static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1162 const std::string &Name) {
1163 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1164 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1165 else
1166 return new GlobalVariable(*M, PTy->getElementType(), false,
1167 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1168 nullptr, GlobalVariable::NotThreadLocal,
1169 PTy->getAddressSpace());
1170}
1171
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172/// GetGlobalVal - Get a value with the specified name or ID, creating a
1173/// forward reference record if needed. This can return null if the value
1174/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001175GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001176 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001177 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001178 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001179 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001182
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183 // Look this name up in the normal function symbol table.
1184 GlobalValue *Val =
1185 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001186
Chris Lattnerac161bf2009-01-02 07:01:27 +00001187 // If this is a forward reference for the value, see if we already created a
1188 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001189 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001190 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 if (I != ForwardRefVals.end())
1192 Val = I->second.first;
1193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001194
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195 // If we have the value in the symbol table or fwd-ref table, return it.
1196 if (Val) {
1197 if (Val->getType() == Ty) return Val;
1198 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001199 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001200 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001201 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001202
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001204 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1206 return FwdVal;
1207}
1208
Chris Lattner229907c2011-07-18 04:54:35 +00001209GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1210 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001211 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001213 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001215
Craig Topper2617dcc2014-04-15 06:32:26 +00001216 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001217
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218 // If this is a forward reference for the value, see if we already created a
1219 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001220 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001221 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 if (I != ForwardRefValIDs.end())
1223 Val = I->second.first;
1224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001225
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 // If we have the value in the symbol table or fwd-ref table, return it.
1227 if (Val) {
1228 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001229 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001230 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001231 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001233
Chris Lattnerac161bf2009-01-02 07:01:27 +00001234 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001235 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001236 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1237 return FwdVal;
1238}
1239
Chris Lattnerac161bf2009-01-02 07:01:27 +00001240//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001241// Comdat Reference/Resolution Routines.
1242//===----------------------------------------------------------------------===//
1243
1244Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1245 // Look this name up in the comdat symbol table.
1246 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1247 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1248 if (I != ComdatSymTab.end())
1249 return &I->second;
1250
1251 // Otherwise, create a new forward reference for this value and remember it.
1252 Comdat *C = M->getOrInsertComdat(Name);
1253 ForwardRefComdats[Name] = Loc;
1254 return C;
1255}
1256
David Majnemerdad0a642014-06-27 18:19:56 +00001257//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001258// Helper Routines.
1259//===----------------------------------------------------------------------===//
1260
1261/// ParseToken - If the current token has the specified kind, eat it and return
1262/// success. Otherwise, emit the specified error and return failure.
1263bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1264 if (Lex.getKind() != T)
1265 return TokError(ErrMsg);
1266 Lex.Lex();
1267 return false;
1268}
1269
Chris Lattner3822f632009-01-02 08:05:26 +00001270/// ParseStringConstant
1271/// ::= StringConstant
1272bool LLParser::ParseStringConstant(std::string &Result) {
1273 if (Lex.getKind() != lltok::StringConstant)
1274 return TokError("expected string constant");
1275 Result = Lex.getStrVal();
1276 Lex.Lex();
1277 return false;
1278}
1279
1280/// ParseUInt32
1281/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001282bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001283 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1284 return TokError("expected integer");
1285 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1286 if (Val64 != unsigned(Val64))
1287 return TokError("expected 32-bit integer (too large)");
1288 Val = Val64;
1289 Lex.Lex();
1290 return false;
1291}
1292
Hal Finkelb0407ba2014-07-18 15:51:28 +00001293/// ParseUInt64
1294/// ::= uint64
1295bool LLParser::ParseUInt64(uint64_t &Val) {
1296 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1297 return TokError("expected integer");
1298 Val = Lex.getAPSIntVal().getLimitedValue();
1299 Lex.Lex();
1300 return false;
1301}
1302
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001303/// ParseTLSModel
1304/// := 'localdynamic'
1305/// := 'initialexec'
1306/// := 'localexec'
1307bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1308 switch (Lex.getKind()) {
1309 default:
1310 return TokError("expected localdynamic, initialexec or localexec");
1311 case lltok::kw_localdynamic:
1312 TLM = GlobalVariable::LocalDynamicTLSModel;
1313 break;
1314 case lltok::kw_initialexec:
1315 TLM = GlobalVariable::InitialExecTLSModel;
1316 break;
1317 case lltok::kw_localexec:
1318 TLM = GlobalVariable::LocalExecTLSModel;
1319 break;
1320 }
1321
1322 Lex.Lex();
1323 return false;
1324}
1325
1326/// ParseOptionalThreadLocal
1327/// := /*empty*/
1328/// := 'thread_local'
1329/// := 'thread_local' '(' tlsmodel ')'
1330bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1331 TLM = GlobalVariable::NotThreadLocal;
1332 if (!EatIfPresent(lltok::kw_thread_local))
1333 return false;
1334
1335 TLM = GlobalVariable::GeneralDynamicTLSModel;
1336 if (Lex.getKind() == lltok::lparen) {
1337 Lex.Lex();
1338 return ParseTLSModel(TLM) ||
1339 ParseToken(lltok::rparen, "expected ')' after thread local model");
1340 }
1341 return false;
1342}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001343
1344/// ParseOptionalAddrSpace
1345/// := /*empty*/
1346/// := 'addrspace' '(' uint32 ')'
1347bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1348 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001349 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001350 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001351 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001352 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001353 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001354}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001355
Artur Pilipenko17376c42015-08-03 14:31:49 +00001356/// ParseStringAttribute
1357/// := StringConstant
1358/// := StringConstant '=' StringConstant
1359bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1360 std::string Attr = Lex.getStrVal();
1361 Lex.Lex();
1362 std::string Val;
1363 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1364 return true;
1365 B.addAttribute(Attr, Val);
1366 return false;
1367}
1368
Bill Wendling34c2eb22012-12-04 23:40:58 +00001369/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1370bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1371 bool HaveError = false;
1372
1373 B.clear();
1374
Eugene Zelenko1804a772016-08-25 00:45:04 +00001375 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001376 lltok::Kind Token = Lex.getKind();
1377 switch (Token) {
1378 default: // End of attributes.
1379 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001380 case lltok::StringConstant: {
1381 if (ParseStringAttribute(B))
1382 return true;
1383 continue;
1384 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385 case lltok::kw_align: {
1386 unsigned Alignment;
1387 if (ParseOptionalAlignment(Alignment))
1388 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001389 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001390 continue;
1391 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001392 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001393 case lltok::kw_dereferenceable: {
1394 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001395 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001396 return true;
1397 B.addDereferenceableAttr(Bytes);
1398 continue;
1399 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001400 case lltok::kw_dereferenceable_or_null: {
1401 uint64_t Bytes;
1402 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1403 return true;
1404 B.addDereferenceableOrNullAttr(Bytes);
1405 continue;
1406 }
Reid Klecknera534a382013-12-19 02:14:12 +00001407 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001408 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1409 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1410 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1411 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001412 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001413 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1414 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001415 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001416 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1417 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001418 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001419 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001420 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001421 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001422
Stephen Lin7577ed52013-04-20 13:16:13 +00001423 case lltok::kw_alignstack:
1424 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001425 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001426 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001427 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001428 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001429 case lltok::kw_minsize:
1430 case lltok::kw_naked:
1431 case lltok::kw_nobuiltin:
1432 case lltok::kw_noduplicate:
1433 case lltok::kw_noimplicitfloat:
1434 case lltok::kw_noinline:
1435 case lltok::kw_nonlazybind:
1436 case lltok::kw_noredzone:
1437 case lltok::kw_noreturn:
1438 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001439 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001440 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001441 case lltok::kw_returns_twice:
1442 case lltok::kw_sanitize_address:
1443 case lltok::kw_sanitize_memory:
1444 case lltok::kw_sanitize_thread:
1445 case lltok::kw_ssp:
1446 case lltok::kw_sspreq:
1447 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001448 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001449 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001450 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1451 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001452 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001453
Bill Wendling34c2eb22012-12-04 23:40:58 +00001454 Lex.Lex();
1455 }
1456}
1457
1458/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1459bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1460 bool HaveError = false;
1461
1462 B.clear();
1463
Eugene Zelenko1804a772016-08-25 00:45:04 +00001464 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001465 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001466 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001467 default: // End of attributes.
1468 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001469 case lltok::StringConstant: {
1470 if (ParseStringAttribute(B))
1471 return true;
1472 continue;
1473 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001474 case lltok::kw_dereferenceable: {
1475 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001476 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001477 return true;
1478 B.addDereferenceableAttr(Bytes);
1479 continue;
1480 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001481 case lltok::kw_dereferenceable_or_null: {
1482 uint64_t Bytes;
1483 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1484 return true;
1485 B.addDereferenceableOrNullAttr(Bytes);
1486 continue;
1487 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001488 case lltok::kw_align: {
1489 unsigned Alignment;
1490 if (ParseOptionalAlignment(Alignment))
1491 return true;
1492 B.addAlignmentAttr(Alignment);
1493 continue;
1494 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001495 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1496 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001497 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001498 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1499 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001500
Bill Wendling34c2eb22012-12-04 23:40:58 +00001501 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001502 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001503 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001504 case lltok::kw_nest:
1505 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001506 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001507 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001508 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001509 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001510 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001511 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001512
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001513 case lltok::kw_alignstack:
1514 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001515 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001516 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001517 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001518 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001519 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001520 case lltok::kw_minsize:
1521 case lltok::kw_naked:
1522 case lltok::kw_nobuiltin:
1523 case lltok::kw_noduplicate:
1524 case lltok::kw_noimplicitfloat:
1525 case lltok::kw_noinline:
1526 case lltok::kw_nonlazybind:
1527 case lltok::kw_noredzone:
1528 case lltok::kw_noreturn:
1529 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001530 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001531 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001532 case lltok::kw_returns_twice:
1533 case lltok::kw_sanitize_address:
1534 case lltok::kw_sanitize_memory:
1535 case lltok::kw_sanitize_thread:
1536 case lltok::kw_ssp:
1537 case lltok::kw_sspreq:
1538 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001539 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001540 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001541 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001542 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001543
1544 case lltok::kw_readnone:
1545 case lltok::kw_readonly:
1546 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001547 }
1548
Chris Lattnerac161bf2009-01-02 07:01:27 +00001549 Lex.Lex();
1550 }
1551}
1552
Rafael Espindolac6269912016-05-10 17:16:45 +00001553static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1554 HasLinkage = true;
1555 switch (Kind) {
1556 default:
1557 HasLinkage = false;
1558 return GlobalValue::ExternalLinkage;
1559 case lltok::kw_private:
1560 return GlobalValue::PrivateLinkage;
1561 case lltok::kw_internal:
1562 return GlobalValue::InternalLinkage;
1563 case lltok::kw_weak:
1564 return GlobalValue::WeakAnyLinkage;
1565 case lltok::kw_weak_odr:
1566 return GlobalValue::WeakODRLinkage;
1567 case lltok::kw_linkonce:
1568 return GlobalValue::LinkOnceAnyLinkage;
1569 case lltok::kw_linkonce_odr:
1570 return GlobalValue::LinkOnceODRLinkage;
1571 case lltok::kw_available_externally:
1572 return GlobalValue::AvailableExternallyLinkage;
1573 case lltok::kw_appending:
1574 return GlobalValue::AppendingLinkage;
1575 case lltok::kw_common:
1576 return GlobalValue::CommonLinkage;
1577 case lltok::kw_extern_weak:
1578 return GlobalValue::ExternalWeakLinkage;
1579 case lltok::kw_external:
1580 return GlobalValue::ExternalLinkage;
1581 }
1582}
1583
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584/// ParseOptionalLinkage
1585/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001586/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001587/// ::= 'internal'
1588/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001589/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001590/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001591/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001592/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001593/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001594/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001595/// ::= 'extern_weak'
1596/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001597bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1598 unsigned &Visibility,
1599 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001600 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1601 if (HasLinkage)
1602 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001603 ParseOptionalVisibility(Visibility);
1604 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001605 return false;
1606}
1607
1608/// ParseOptionalVisibility
1609/// ::= /*empty*/
1610/// ::= 'default'
1611/// ::= 'hidden'
1612/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001613///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001614void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001615 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001616 default:
1617 Res = GlobalValue::DefaultVisibility;
1618 return;
1619 case lltok::kw_default:
1620 Res = GlobalValue::DefaultVisibility;
1621 break;
1622 case lltok::kw_hidden:
1623 Res = GlobalValue::HiddenVisibility;
1624 break;
1625 case lltok::kw_protected:
1626 Res = GlobalValue::ProtectedVisibility;
1627 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001628 }
1629 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001630}
1631
Nico Rieck7157bb72014-01-14 15:22:47 +00001632/// ParseOptionalDLLStorageClass
1633/// ::= /*empty*/
1634/// ::= 'dllimport'
1635/// ::= 'dllexport'
1636///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001637void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001638 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001639 default:
1640 Res = GlobalValue::DefaultStorageClass;
1641 return;
1642 case lltok::kw_dllimport:
1643 Res = GlobalValue::DLLImportStorageClass;
1644 break;
1645 case lltok::kw_dllexport:
1646 Res = GlobalValue::DLLExportStorageClass;
1647 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001648 }
1649 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001650}
1651
Chris Lattnerac161bf2009-01-02 07:01:27 +00001652/// ParseOptionalCallingConv
1653/// ::= /*empty*/
1654/// ::= 'ccc'
1655/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001656/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001657/// ::= 'coldcc'
1658/// ::= 'x86_stdcallcc'
1659/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001660/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001661/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001662/// ::= 'arm_apcscc'
1663/// ::= 'arm_aapcscc'
1664/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001665/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001666/// ::= 'avr_intrcc'
1667/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001668/// ::= 'ptx_kernel'
1669/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001670/// ::= 'spir_func'
1671/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001672/// ::= 'x86_64_sysvcc'
1673/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001674/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001675/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001676/// ::= 'preserve_mostcc'
1677/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001678/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001679/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001680/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001681/// ::= 'hhvmcc'
1682/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001683/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001684/// ::= 'amdgpu_vs'
Marek Olsaka302a7362017-05-02 15:41:10 +00001685/// ::= 'amdgpu_hs'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001686/// ::= 'amdgpu_gs'
1687/// ::= 'amdgpu_ps'
1688/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001689/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001690/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001691///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001692bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001693 switch (Lex.getKind()) {
1694 default: CC = CallingConv::C; return false;
1695 case lltok::kw_ccc: CC = CallingConv::C; break;
1696 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1697 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1698 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1699 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001700 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001701 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001702 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001703 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1704 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1705 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001706 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001707 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1708 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001709 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1710 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001711 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1712 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001713 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001714 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1715 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001716 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001717 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001718 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1719 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001720 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001721 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001722 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001723 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1724 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001725 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001726 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001727 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001728 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1729 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1730 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001731 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001732 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001733 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001734 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001735 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001736 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001737
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 Lex.Lex();
1739 return false;
1740}
1741
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001742/// ParseMetadataAttachment
1743/// ::= !dbg !42
1744bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1745 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1746
1747 std::string Name = Lex.getStrVal();
1748 Kind = M->getMDKindID(Name);
1749 Lex.Lex();
1750
1751 return ParseMDNode(MD);
1752}
1753
Chris Lattner5c427632009-12-30 05:31:19 +00001754/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001755/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001756bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001757 do {
1758 if (Lex.getKind() != lltok::MetadataVar)
1759 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001760
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001761 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001762 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001763 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001764 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001765
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001766 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001767 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001768 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001769
Chris Lattner596760d2009-12-29 21:25:40 +00001770 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001771 } while (EatIfPresent(lltok::comma));
1772 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001773}
1774
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001775/// ParseGlobalObjectMetadataAttachment
1776/// ::= !dbg !57
1777bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1778 unsigned MDK;
1779 MDNode *N;
1780 if (ParseMetadataAttachment(MDK, N))
1781 return true;
1782
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001783 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001784 return false;
1785}
1786
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001787/// ParseOptionalFunctionMetadata
1788/// ::= (!dbg !57)*
1789bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001790 while (Lex.getKind() == lltok::MetadataVar)
1791 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001792 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001793 return false;
1794}
1795
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796/// ParseOptionalAlignment
1797/// ::= /* empty */
1798/// ::= 'align' 4
1799bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1800 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001801 if (!EatIfPresent(lltok::kw_align))
1802 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001803 LocTy AlignLoc = Lex.getLoc();
1804 if (ParseUInt32(Alignment)) return true;
1805 if (!isPowerOf2_32(Alignment))
1806 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001807 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001808 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001809 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810}
1811
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001812/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001813/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001814/// ::= AttrKind '(' 4 ')'
1815///
1816/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1817bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1818 uint64_t &Bytes) {
1819 assert((AttrKind == lltok::kw_dereferenceable ||
1820 AttrKind == lltok::kw_dereferenceable_or_null) &&
1821 "contract!");
1822
Hal Finkelb0407ba2014-07-18 15:51:28 +00001823 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001824 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001825 return false;
1826 LocTy ParenLoc = Lex.getLoc();
1827 if (!EatIfPresent(lltok::lparen))
1828 return Error(ParenLoc, "expected '('");
1829 LocTy DerefLoc = Lex.getLoc();
1830 if (ParseUInt64(Bytes)) return true;
1831 ParenLoc = Lex.getLoc();
1832 if (!EatIfPresent(lltok::rparen))
1833 return Error(ParenLoc, "expected ')'");
1834 if (!Bytes)
1835 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1836 return false;
1837}
1838
Chris Lattnerb2f39502009-12-30 05:44:30 +00001839/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001840/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001841/// ::= ',' align 4
1842///
1843/// This returns with AteExtraComma set to true if it ate an excess comma at the
1844/// end.
1845bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1846 bool &AteExtraComma) {
1847 AteExtraComma = false;
1848 while (EatIfPresent(lltok::comma)) {
1849 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001850 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001851 AteExtraComma = true;
1852 return false;
1853 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001854
Chris Lattner95b0ff42010-04-23 00:50:50 +00001855 if (Lex.getKind() != lltok::kw_align)
1856 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001857
Chris Lattner95b0ff42010-04-23 00:50:50 +00001858 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001859 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001860
Devang Patelea8a4b92009-09-17 23:04:48 +00001861 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001862}
1863
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001864/// ParseOptionalCommaAddrSpace
1865/// ::=
1866/// ::= ',' addrspace(1)
1867///
1868/// This returns with AteExtraComma set to true if it ate an excess comma at the
1869/// end.
1870bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1871 LocTy &Loc,
1872 bool &AteExtraComma) {
1873 AteExtraComma = false;
1874 while (EatIfPresent(lltok::comma)) {
1875 // Metadata at the end is an early exit.
1876 if (Lex.getKind() == lltok::MetadataVar) {
1877 AteExtraComma = true;
1878 return false;
1879 }
1880
1881 Loc = Lex.getLoc();
1882 if (Lex.getKind() != lltok::kw_addrspace)
1883 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1884
1885 if (ParseOptionalAddrSpace(AddrSpace))
1886 return true;
1887 }
1888
1889 return false;
1890}
1891
George Burgess IV278199f2016-04-12 01:05:35 +00001892bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1893 Optional<unsigned> &HowManyArg) {
1894 Lex.Lex();
1895
1896 auto StartParen = Lex.getLoc();
1897 if (!EatIfPresent(lltok::lparen))
1898 return Error(StartParen, "expected '('");
1899
1900 if (ParseUInt32(BaseSizeArg))
1901 return true;
1902
1903 if (EatIfPresent(lltok::comma)) {
1904 auto HowManyAt = Lex.getLoc();
1905 unsigned HowMany;
1906 if (ParseUInt32(HowMany))
1907 return true;
1908 if (HowMany == BaseSizeArg)
1909 return Error(HowManyAt,
1910 "'allocsize' indices can't refer to the same parameter");
1911 HowManyArg = HowMany;
1912 } else
1913 HowManyArg = None;
1914
1915 auto EndParen = Lex.getLoc();
1916 if (!EatIfPresent(lltok::rparen))
1917 return Error(EndParen, "expected ')'");
1918 return false;
1919}
1920
Eli Friedmanfee02c62011-07-25 23:16:38 +00001921/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001922/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00001923/// else: ::=
1924///
1925/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001926bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00001927 AtomicOrdering &Ordering) {
1928 if (!isAtomic)
1929 return false;
1930
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001931 return ParseScope(SSID) || ParseOrdering(Ordering);
1932}
Tim Northovere94a5182014-03-11 10:48:52 +00001933
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001934/// ParseScope
1935/// ::= syncscope("singlethread" | "<target scope>")?
1936///
1937/// This sets synchronization scope ID to the ID of the parsed value.
1938bool LLParser::ParseScope(SyncScope::ID &SSID) {
1939 SSID = SyncScope::System;
1940 if (EatIfPresent(lltok::kw_syncscope)) {
1941 auto StartParenAt = Lex.getLoc();
1942 if (!EatIfPresent(lltok::lparen))
1943 return Error(StartParenAt, "Expected '(' in syncscope");
1944
1945 std::string SSN;
1946 auto SSNAt = Lex.getLoc();
1947 if (ParseStringConstant(SSN))
1948 return Error(SSNAt, "Expected synchronization scope name");
1949
1950 auto EndParenAt = Lex.getLoc();
1951 if (!EatIfPresent(lltok::rparen))
1952 return Error(EndParenAt, "Expected ')' in syncscope");
1953
1954 SSID = Context.getOrInsertSyncScopeID(SSN);
1955 }
1956
1957 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00001958}
1959
1960/// ParseOrdering
1961/// ::= AtomicOrdering
1962///
1963/// This sets Ordering to the parsed value.
1964bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001965 switch (Lex.getKind()) {
1966 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001967 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1968 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1969 // Not specified yet:
1970 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1971 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1972 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1973 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1974 case lltok::kw_seq_cst:
1975 Ordering = AtomicOrdering::SequentiallyConsistent;
1976 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001977 }
1978 Lex.Lex();
1979 return false;
1980}
1981
Charles Davisbe5557e2010-02-12 00:31:15 +00001982/// ParseOptionalStackAlignment
1983/// ::= /* empty */
1984/// ::= 'alignstack' '(' 4 ')'
1985bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1986 Alignment = 0;
1987 if (!EatIfPresent(lltok::kw_alignstack))
1988 return false;
1989 LocTy ParenLoc = Lex.getLoc();
1990 if (!EatIfPresent(lltok::lparen))
1991 return Error(ParenLoc, "expected '('");
1992 LocTy AlignLoc = Lex.getLoc();
1993 if (ParseUInt32(Alignment)) return true;
1994 ParenLoc = Lex.getLoc();
1995 if (!EatIfPresent(lltok::rparen))
1996 return Error(ParenLoc, "expected ')'");
1997 if (!isPowerOf2_32(Alignment))
1998 return Error(AlignLoc, "stack alignment is not a power of two");
1999 return false;
2000}
Devang Patelea8a4b92009-09-17 23:04:48 +00002001
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002002/// ParseIndexList - This parses the index list for an insert/extractvalue
2003/// instruction. This sets AteExtraComma in the case where we eat an extra
2004/// comma at the end of the line and find that it is followed by metadata.
2005/// Clients that don't allow metadata can call the version of this function that
2006/// only takes one argument.
2007///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008/// ParseIndexList
2009/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002010///
2011bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2012 bool &AteExtraComma) {
2013 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002014
Chris Lattnerac161bf2009-01-02 07:01:27 +00002015 if (Lex.getKind() != lltok::comma)
2016 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002017
Chris Lattner3822f632009-01-02 08:05:26 +00002018 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002019 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002020 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002021 AteExtraComma = true;
2022 return false;
2023 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002024 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002025 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002026 Indices.push_back(Idx);
2027 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002028
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029 return false;
2030}
2031
2032//===----------------------------------------------------------------------===//
2033// Type Parsing.
2034//===----------------------------------------------------------------------===//
2035
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002036/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002037bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002038 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002039 switch (Lex.getKind()) {
2040 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002041 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002045 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002047 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002048 // Type ::= StructType
2049 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 return true;
2051 break;
2052 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054 Lex.Lex(); // eat the lsquare.
2055 if (ParseArrayVectorType(Result, false))
2056 return true;
2057 break;
2058 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002060 Lex.Lex();
2061 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002062 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002063 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 } else if (ParseArrayVectorType(Result, true))
2066 return true;
2067 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002068 case lltok::LocalVar: {
2069 // Type ::= %foo
2070 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002071
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002072 // If the type hasn't been defined yet, create a forward definition and
2073 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002074 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002075 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002076 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002077 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079 Lex.Lex();
2080 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002082
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002083 case lltok::LocalVarID: {
2084 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002085 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002086
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002087 // If the type hasn't been defined yet, create a forward definition and
2088 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002089 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002090 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002093 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094 Lex.Lex();
2095 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 }
2097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
2099 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002100 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 switch (Lex.getKind()) {
2102 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002103 default:
2104 if (!AllowVoid && Result->isVoidTy())
2105 return Error(TypeLoc, "void type only allowed for function results");
2106 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002108 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002109 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002110 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002112 if (Result->isVoidTy())
2113 return TokError("pointers to void are invalid - use i8* instead");
2114 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002115 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002116 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002117 Lex.Lex();
2118 break;
2119
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002120 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002122 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002124 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002125 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002126 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002127 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002128 unsigned AddrSpace;
2129 if (ParseOptionalAddrSpace(AddrSpace) ||
2130 ParseToken(lltok::star, "expected '*' in address space"))
2131 return true;
2132
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002133 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 break;
2135 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002136
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2138 case lltok::lparen:
2139 if (ParseFunctionType(Result))
2140 return true;
2141 break;
2142 }
2143 }
2144}
2145
2146/// ParseParameterList
2147/// ::= '(' ')'
2148/// ::= '(' Arg (',' Arg)* ')'
2149/// Arg
2150/// ::= Type OptionalAttributes Value OptionalAttributes
2151bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002152 PerFunctionState &PFS, bool IsMustTailCall,
2153 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 if (ParseToken(lltok::lparen, "expected '(' in call"))
2155 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 while (Lex.getKind() != lltok::rparen) {
2158 // If this isn't the first argument, we need a comma.
2159 if (!ArgList.empty() &&
2160 ParseToken(lltok::comma, "expected ',' in argument list"))
2161 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002162
Reid Kleckner83498642014-08-26 00:33:28 +00002163 // Parse an ellipsis if this is a musttail call in a variadic function.
2164 if (Lex.getKind() == lltok::dotdotdot) {
2165 const char *Msg = "unexpected ellipsis in argument list for ";
2166 if (!IsMustTailCall)
2167 return TokError(Twine(Msg) + "non-musttail call");
2168 if (!InVarArgsFunc)
2169 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2170 Lex.Lex(); // Lex the '...', it is purely for readability.
2171 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2172 }
2173
Chris Lattnerac161bf2009-01-02 07:01:27 +00002174 // Parse the argument.
2175 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002176 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002177 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002179 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002181
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002182 if (ArgTy->isMetadataTy()) {
2183 if (ParseMetadataAsValue(V, PFS))
2184 return true;
2185 } else {
2186 // Otherwise, handle normal operands.
2187 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2188 return true;
2189 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002190 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002191 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 }
2193
Reid Kleckner83498642014-08-26 00:33:28 +00002194 if (IsMustTailCall && InVarArgsFunc)
2195 return TokError("expected '...' at end of argument list for musttail call "
2196 "in varargs function");
2197
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 Lex.Lex(); // Lex the ')'.
2199 return false;
2200}
2201
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002202/// ParseOptionalOperandBundles
2203/// ::= /*empty*/
2204/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2205///
2206/// OperandBundle
2207/// ::= bundle-tag '(' ')'
2208/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2209///
2210/// bundle-tag ::= String Constant
2211bool LLParser::ParseOptionalOperandBundles(
2212 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2213 LocTy BeginLoc = Lex.getLoc();
2214 if (!EatIfPresent(lltok::lsquare))
2215 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002217 while (Lex.getKind() != lltok::rsquare) {
2218 // If this isn't the first operand bundle, we need a comma.
2219 if (!BundleList.empty() &&
2220 ParseToken(lltok::comma, "expected ',' in input list"))
2221 return true;
2222
2223 std::string Tag;
2224 if (ParseStringConstant(Tag))
2225 return true;
2226
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002227 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2228 return true;
2229
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002230 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002231 while (Lex.getKind() != lltok::rparen) {
2232 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002233 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002234 ParseToken(lltok::comma, "expected ',' in input list"))
2235 return true;
2236
2237 Type *Ty = nullptr;
2238 Value *Input = nullptr;
2239 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2240 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002241 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002242 }
2243
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002244 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2245
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002246 Lex.Lex(); // Lex the ')'.
2247 }
2248
2249 if (BundleList.empty())
2250 return Error(BeginLoc, "operand bundle set must not be empty");
2251
2252 Lex.Lex(); // Lex the ']'.
2253 return false;
2254}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255
Chris Lattner2ed06b42009-01-05 18:34:07 +00002256/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002257/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258/// ::= '(' ArgTypeListI ')'
2259/// ArgTypeListI
2260/// ::= /*empty*/
2261/// ::= '...'
2262/// ::= ArgTypeList ',' '...'
2263/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002264///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002265bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2266 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 isVarArg = false;
2268 assert(Lex.getKind() == lltok::lparen);
2269 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 if (Lex.getKind() == lltok::rparen) {
2272 // empty
2273 } else if (Lex.getKind() == lltok::dotdotdot) {
2274 isVarArg = true;
2275 Lex.Lex();
2276 } else {
2277 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002278 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002279 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002282 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002283 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerfdd87902009-10-05 05:54:46 +00002285 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002286 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002287
Chris Lattnerdef19492011-06-17 06:36:20 +00002288 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002289 Name = Lex.getStrVal();
2290 Lex.Lex();
2291 }
Chris Lattner3822f632009-01-02 08:05:26 +00002292
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002293 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002294 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002295
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002296 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002297 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002298 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002299
Chris Lattner3822f632009-01-02 08:05:26 +00002300 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002302 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002303 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 break;
2305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002306
Chris Lattnerac161bf2009-01-02 07:01:27 +00002307 // Otherwise must be an argument type.
2308 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002309 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002310
Chris Lattnerfdd87902009-10-05 05:54:46 +00002311 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002312 return Error(TypeLoc, "argument can not have void type");
2313
Chris Lattnerdef19492011-06-17 06:36:20 +00002314 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 Name = Lex.getStrVal();
2316 Lex.Lex();
2317 } else {
2318 Name = "";
2319 }
Chris Lattner3822f632009-01-02 08:05:26 +00002320
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002322 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002323
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002324 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002325 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002326 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 }
2328 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002329
Chris Lattner3822f632009-01-02 08:05:26 +00002330 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333/// ParseFunctionType
2334/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002336 assert(Lex.getKind() == lltok::lparen);
2337
Chris Lattnerce473c72009-01-05 08:04:33 +00002338 if (!FunctionType::isValidReturnType(Result))
2339 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002340
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002342 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002343 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 // Reject names on the arguments lists.
2347 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2348 if (!ArgList[i].Name.empty())
2349 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002350 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002351 return Error(ArgList[i].Loc,
2352 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002354
Jay Foadb804a2b2011-07-12 14:06:48 +00002355 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002358
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002359 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002360 return false;
2361}
2362
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002363/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2364/// other structs.
2365bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2366 SmallVector<Type*, 8> Elts;
2367 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002368
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002369 Result = StructType::get(Context, Elts, Packed);
2370 return false;
2371}
2372
2373/// ParseStructDefinition - Parse a struct in a 'type' definition.
2374bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2375 std::pair<Type*, LocTy> &Entry,
2376 Type *&ResultTy) {
2377 // If the type was already defined, diagnose the redefinition.
2378 if (Entry.first && !Entry.second.isValid())
2379 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002380
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002381 // If we have opaque, just return without filling in the definition for the
2382 // struct. This counts as a definition as far as the .ll file goes.
2383 if (EatIfPresent(lltok::kw_opaque)) {
2384 // This type is being defined, so clear the location to indicate this.
2385 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002386
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002387 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002388 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002389 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002390 ResultTy = Entry.first;
2391 return false;
2392 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002393
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002394 // If the type starts with '<', then it is either a packed struct or a vector.
2395 bool isPacked = EatIfPresent(lltok::less);
2396
2397 // If we don't have a struct, then we have a random type alias, which we
2398 // accept for compatibility with old files. These types are not allowed to be
2399 // forward referenced and not allowed to be recursive.
2400 if (Lex.getKind() != lltok::lbrace) {
2401 if (Entry.first)
2402 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002403
Craig Topper2617dcc2014-04-15 06:32:26 +00002404 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002405 if (isPacked)
2406 return ParseArrayVectorType(ResultTy, true);
2407 return ParseType(ResultTy);
2408 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002410 // This type is being defined, so clear the location to indicate this.
2411 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002412
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002413 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002414 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002415 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002416
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002417 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002419 SmallVector<Type*, 8> Body;
2420 if (ParseStructBody(Body) ||
2421 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2422 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002423
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002424 STy->setBody(Body, isPacked);
2425 ResultTy = STy;
2426 return false;
2427}
2428
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002432/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002434/// ::= '<' '{' Type (',' Type)* '}' '>'
2435bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 assert(Lex.getKind() == lltok::lbrace);
2437 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002438
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002439 // Handle the empty struct.
2440 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002441 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002442
Chris Lattnerf880ca22009-03-09 04:49:14 +00002443 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002444 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002445 if (ParseType(Ty)) return true;
2446 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002448 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002449 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002450
Chris Lattner3822f632009-01-02 08:05:26 +00002451 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002452 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002453 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002454
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002455 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002456 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002458 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002461 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002462}
2463
2464/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2465/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002466/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467/// ::= '[' APSINTVAL 'x' Types ']'
2468/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002469bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002470 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2471 Lex.getAPSIntVal().getBitWidth() > 64)
2472 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002473
Chris Lattnerac161bf2009-01-02 07:01:27 +00002474 LocTy SizeLoc = Lex.getLoc();
2475 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002476 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002477
Chris Lattner3822f632009-01-02 08:05:26 +00002478 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2479 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002480
2481 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002482 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002483 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002484
Chris Lattner3822f632009-01-02 08:05:26 +00002485 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2486 "expected end of sequential type"))
2487 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002490 if (Size == 0)
2491 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 if ((unsigned)Size != Size)
2493 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002494 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002495 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002496 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002498 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002499 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002500 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501 }
2502 return false;
2503}
2504
2505//===----------------------------------------------------------------------===//
2506// Function Semantic Analysis.
2507//===----------------------------------------------------------------------===//
2508
Chris Lattner3432c622009-10-28 03:39:23 +00002509LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2510 int functionNumber)
2511 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512
2513 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002514 for (Argument &A : F.args())
2515 if (!A.hasName())
2516 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517}
2518
2519LLParser::PerFunctionState::~PerFunctionState() {
2520 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
David Blaikie9ebdc692015-09-21 21:07:50 +00002522 for (const auto &P : ForwardRefVals) {
2523 if (isa<BasicBlock>(P.second.first))
2524 continue;
2525 P.second.first->replaceAllUsesWith(
2526 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002527 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002528 }
2529
2530 for (const auto &P : ForwardRefValIDs) {
2531 if (isa<BasicBlock>(P.second.first))
2532 continue;
2533 P.second.first->replaceAllUsesWith(
2534 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002535 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002536 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537}
2538
Chris Lattner3432c622009-10-28 03:39:23 +00002539bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 if (!ForwardRefVals.empty())
2541 return P.Error(ForwardRefVals.begin()->second.second,
2542 "use of undefined value '%" + ForwardRefVals.begin()->first +
2543 "'");
2544 if (!ForwardRefValIDs.empty())
2545 return P.Error(ForwardRefValIDs.begin()->second.second,
2546 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002547 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 return false;
2549}
2550
Chris Lattnerac161bf2009-01-02 07:01:27 +00002551/// GetVal - Get a value with the specified name or ID, creating a
2552/// forward reference record if needed. This can return null if the value
2553/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002554Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002555 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002557 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002558
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559 // If this is a forward reference for the value, see if we already created a
2560 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002561 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002562 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 if (I != ForwardRefVals.end())
2564 Val = I->second.first;
2565 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566
Chris Lattnerac161bf2009-01-02 07:01:27 +00002567 // If we have the value in the symbol table or fwd-ref table, return it.
2568 if (Val) {
2569 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002570 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002571 P.Error(Loc, "'%" + Name + "' is not a basic block");
2572 else
2573 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002574 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002575 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002577
Chris Lattnerac161bf2009-01-02 07:01:27 +00002578 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002579 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002580 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002581 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002582 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002583
Chris Lattnerac161bf2009-01-02 07:01:27 +00002584 // Otherwise, create a new forward reference for this value and remember it.
2585 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002586 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002587 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002588 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002589 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002590 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002591
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2593 return FwdVal;
2594}
2595
David Majnemer8a1c45d2015-12-12 05:38:55 +00002596Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002598 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002599
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 // If this is a forward reference for the value, see if we already created a
2601 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002602 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002603 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002604 if (I != ForwardRefValIDs.end())
2605 Val = I->second.first;
2606 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002607
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 // If we have the value in the symbol table or fwd-ref table, return it.
2609 if (Val) {
2610 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002611 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002612 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002614 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002615 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002616 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002619 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002621 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002622 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002623
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 // Otherwise, create a new forward reference for this value and remember it.
2625 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002626 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002627 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002628 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002629 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002630 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002631
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2633 return FwdVal;
2634}
2635
2636/// SetInstName - After an instruction is parsed and inserted into its
2637/// basic block, this installs its name.
2638bool LLParser::PerFunctionState::SetInstName(int NameID,
2639 const std::string &NameStr,
2640 LocTy NameLoc, Instruction *Inst) {
2641 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002642 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 if (NameID != -1 || !NameStr.empty())
2644 return P.Error(NameLoc, "instructions returning void cannot have a name");
2645 return false;
2646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002647
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 // If this was a numbered instruction, verify that the instruction is the
2649 // expected value and resolve any forward references.
2650 if (NameStr.empty()) {
2651 // If neither a name nor an ID was specified, just use the next ID.
2652 if (NameID == -1)
2653 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002654
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 if (unsigned(NameID) != NumberedVals.size())
2656 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002657 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002658
David Blaikie9ebdc692015-09-21 21:07:50 +00002659 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002661 Value *Sentinel = FI->second.first;
2662 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002664 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002665
2666 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002667 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 ForwardRefValIDs.erase(FI);
2669 }
2670
2671 NumberedVals.push_back(Inst);
2672 return false;
2673 }
2674
2675 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002676 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002678 Value *Sentinel = FI->second.first;
2679 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002680 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002681 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002682
2683 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002684 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 ForwardRefVals.erase(FI);
2686 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002687
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 // Set the name on the instruction.
2689 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002691 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002692 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 NameStr + "'");
2694 return false;
2695}
2696
2697/// GetBB - Get a basic block with the specified name or ID, creating a
2698/// forward reference record if needed.
2699BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2700 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002701 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2702 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002703}
2704
2705BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002706 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2707 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708}
2709
2710/// DefineBB - Define the specified basic block, which is either named or
2711/// unnamed. If there is an error, this returns null otherwise it returns
2712/// the block being defined.
2713BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2714 LocTy Loc) {
2715 BasicBlock *BB;
2716 if (Name.empty())
2717 BB = GetBB(NumberedVals.size(), Loc);
2718 else
2719 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002720 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002721
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 // Move the block to the end of the function. Forward ref'd blocks are
2723 // inserted wherever they happen to be referenced.
2724 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002725
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 // Remove the block from forward ref sets.
2727 if (Name.empty()) {
2728 ForwardRefValIDs.erase(NumberedVals.size());
2729 NumberedVals.push_back(BB);
2730 } else {
2731 // BB forward references are already in the function symbol table.
2732 ForwardRefVals.erase(Name);
2733 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002734
Chris Lattnerac161bf2009-01-02 07:01:27 +00002735 return BB;
2736}
2737
2738//===----------------------------------------------------------------------===//
2739// Constants.
2740//===----------------------------------------------------------------------===//
2741
2742/// ParseValID - Parse an abstract value that doesn't necessarily have a
2743/// type implied. For example, if we parse "4" we don't know what integer type
2744/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002745/// sanity. PFS is used to convert function-local operands of metadata (since
2746/// metadata operands are not just parsed here but also converted to values).
2747/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002748bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 ID.Loc = Lex.getLoc();
2750 switch (Lex.getKind()) {
2751 default: return TokError("expected value token");
2752 case lltok::GlobalID: // @42
2753 ID.UIntVal = Lex.getUIntVal();
2754 ID.Kind = ValID::t_GlobalID;
2755 break;
2756 case lltok::GlobalVar: // @foo
2757 ID.StrVal = Lex.getStrVal();
2758 ID.Kind = ValID::t_GlobalName;
2759 break;
2760 case lltok::LocalVarID: // %42
2761 ID.UIntVal = Lex.getUIntVal();
2762 ID.Kind = ValID::t_LocalID;
2763 break;
2764 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765 ID.StrVal = Lex.getStrVal();
2766 ID.Kind = ValID::t_LocalName;
2767 break;
2768 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002769 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002770 ID.Kind = ValID::t_APSInt;
2771 break;
2772 case lltok::APFloat:
2773 ID.APFloatVal = Lex.getAPFloatVal();
2774 ID.Kind = ValID::t_APFloat;
2775 break;
2776 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002777 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002778 ID.Kind = ValID::t_Constant;
2779 break;
2780 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002781 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 ID.Kind = ValID::t_Constant;
2783 break;
2784 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2785 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2786 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002787 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002788
Chris Lattnerac161bf2009-01-02 07:01:27 +00002789 case lltok::lbrace: {
2790 // ValID ::= '{' ConstVector '}'
2791 Lex.Lex();
2792 SmallVector<Constant*, 16> Elts;
2793 if (ParseGlobalValueVector(Elts) ||
2794 ParseToken(lltok::rbrace, "expected end of struct constant"))
2795 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002796
David Blaikieadbda4b2015-08-03 20:08:41 +00002797 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002798 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002799 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2800 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002801 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 return false;
2803 }
2804 case lltok::less: {
2805 // ValID ::= '<' ConstVector '>' --> Vector.
2806 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2807 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002808 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002809
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 SmallVector<Constant*, 16> Elts;
2811 LocTy FirstEltLoc = Lex.getLoc();
2812 if (ParseGlobalValueVector(Elts) ||
2813 (isPackedStruct &&
2814 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2815 ParseToken(lltok::greater, "expected end of constant"))
2816 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002817
Chris Lattnerac161bf2009-01-02 07:01:27 +00002818 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002819 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2820 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2821 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002822 ID.UIntVal = Elts.size();
2823 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 return false;
2825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 if (Elts.empty())
2828 return Error(ID.Loc, "constant vector must not be empty");
2829
Duncan Sands9dff9be2010-02-15 16:12:20 +00002830 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002831 !Elts[0]->getType()->isFloatingPointTy() &&
2832 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002834 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002835
Chris Lattnerac161bf2009-01-02 07:01:27 +00002836 // Verify that all the vector elements have the same type.
2837 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2838 if (Elts[i]->getType() != Elts[0]->getType())
2839 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002840 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002841 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002842
Chris Lattner69229312011-02-15 00:14:00 +00002843 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 ID.Kind = ValID::t_Constant;
2845 return false;
2846 }
2847 case lltok::lsquare: { // Array Constant
2848 Lex.Lex();
2849 SmallVector<Constant*, 16> Elts;
2850 LocTy FirstEltLoc = Lex.getLoc();
2851 if (ParseGlobalValueVector(Elts) ||
2852 ParseToken(lltok::rsquare, "expected end of array constant"))
2853 return true;
2854
2855 // Handle empty element.
2856 if (Elts.empty()) {
2857 // Use undef instead of an array because it's inconvenient to determine
2858 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002859 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 return false;
2861 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002862
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002864 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002865 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002866
Owen Anderson4056ca92009-07-29 22:17:13 +00002867 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002870 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 if (Elts[i]->getType() != Elts[0]->getType())
2872 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002873 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002874 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002875 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002876
Jay Foad83be3612011-06-22 09:24:39 +00002877 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002878 ID.Kind = ValID::t_Constant;
2879 return false;
2880 }
2881 case lltok::kw_c: // c "foo"
2882 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002883 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2884 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2886 ID.Kind = ValID::t_Constant;
2887 return false;
2888
2889 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002890 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2891 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002892 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 Lex.Lex();
2894 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002895 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002896 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002897 ParseStringConstant(ID.StrVal) ||
2898 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002899 ParseToken(lltok::StringConstant, "expected constraint string"))
2900 return true;
2901 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002902 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002903 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002904 ID.Kind = ValID::t_InlineAsm;
2905 return false;
2906 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002907
Chris Lattner3432c622009-10-28 03:39:23 +00002908 case lltok::kw_blockaddress: {
2909 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2910 Lex.Lex();
2911
2912 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002913
Chris Lattner3432c622009-10-28 03:39:23 +00002914 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2915 ParseValID(Fn) ||
2916 ParseToken(lltok::comma, "expected comma in block address expression")||
2917 ParseValID(Label) ||
2918 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2919 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002920
Chris Lattner3432c622009-10-28 03:39:23 +00002921 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2922 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002923 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002924 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002925
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002926 // Try to find the function (but skip it if it's forward-referenced).
2927 GlobalValue *GV = nullptr;
2928 if (Fn.Kind == ValID::t_GlobalID) {
2929 if (Fn.UIntVal < NumberedVals.size())
2930 GV = NumberedVals[Fn.UIntVal];
2931 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2932 GV = M->getNamedValue(Fn.StrVal);
2933 }
2934 Function *F = nullptr;
2935 if (GV) {
2936 // Confirm that it's actually a function with a definition.
2937 if (!isa<Function>(GV))
2938 return Error(Fn.Loc, "expected function name in blockaddress");
2939 F = cast<Function>(GV);
2940 if (F->isDeclaration())
2941 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2942 }
2943
2944 if (!F) {
2945 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002946 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002947 ForwardRefBlockAddresses.insert(std::make_pair(
2948 std::move(Fn),
2949 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002950 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2951 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002952 if (!FwdRef)
2953 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2954 GlobalValue::InternalLinkage, nullptr, "");
2955 ID.ConstantVal = FwdRef;
2956 ID.Kind = ValID::t_Constant;
2957 return false;
2958 }
2959
2960 // We found the function; now find the basic block. Don't use PFS, since we
2961 // might be inside a constant expression.
2962 BasicBlock *BB;
2963 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2964 if (Label.Kind == ValID::t_LocalID)
2965 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2966 else
2967 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2968 if (!BB)
2969 return Error(Label.Loc, "referenced value is not a basic block");
2970 } else {
2971 if (Label.Kind == ValID::t_LocalID)
2972 return Error(Label.Loc, "cannot take address of numeric label after "
2973 "the function is defined");
2974 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002975 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002976 if (!BB)
2977 return Error(Label.Loc, "referenced value is not a basic block");
2978 }
2979
2980 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002981 ID.Kind = ValID::t_Constant;
2982 return false;
2983 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002984
Chris Lattnerac161bf2009-01-02 07:01:27 +00002985 case lltok::kw_trunc:
2986 case lltok::kw_zext:
2987 case lltok::kw_sext:
2988 case lltok::kw_fptrunc:
2989 case lltok::kw_fpext:
2990 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002991 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002992 case lltok::kw_uitofp:
2993 case lltok::kw_sitofp:
2994 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002995 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002997 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002999 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003000 Constant *SrcVal;
3001 Lex.Lex();
3002 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3003 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003004 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003005 ParseType(DestTy) ||
3006 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3007 return true;
3008 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3009 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003010 getTypeString(SrcVal->getType()) + "' to '" +
3011 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003013 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003014 ID.Kind = ValID::t_Constant;
3015 return false;
3016 }
3017 case lltok::kw_extractvalue: {
3018 Lex.Lex();
3019 Constant *Val;
3020 SmallVector<unsigned, 4> Indices;
3021 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3022 ParseGlobalTypeAndValue(Val) ||
3023 ParseIndexList(Indices) ||
3024 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3025 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003026
Chris Lattner392be582010-02-12 20:49:41 +00003027 if (!Val->getType()->isAggregateType())
3028 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003029 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003031 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 ID.Kind = ValID::t_Constant;
3033 return false;
3034 }
3035 case lltok::kw_insertvalue: {
3036 Lex.Lex();
3037 Constant *Val0, *Val1;
3038 SmallVector<unsigned, 4> Indices;
3039 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3040 ParseGlobalTypeAndValue(Val0) ||
3041 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3042 ParseGlobalTypeAndValue(Val1) ||
3043 ParseIndexList(Indices) ||
3044 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3045 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003046 if (!Val0->getType()->isAggregateType())
3047 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003048 Type *IndexedType =
3049 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3050 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003051 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003052 if (IndexedType != Val1->getType())
3053 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3054 getTypeString(Val1->getType()) +
3055 "' instead of '" + getTypeString(IndexedType) +
3056 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003057 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003058 ID.Kind = ValID::t_Constant;
3059 return false;
3060 }
3061 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003062 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 unsigned PredVal, Opc = Lex.getUIntVal();
3064 Constant *Val0, *Val1;
3065 Lex.Lex();
3066 if (ParseCmpPredicate(PredVal, Opc) ||
3067 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3068 ParseGlobalTypeAndValue(Val0) ||
3069 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3070 ParseGlobalTypeAndValue(Val1) ||
3071 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3072 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003073
Chris Lattnerac161bf2009-01-02 07:01:27 +00003074 if (Val0->getType() != Val1->getType())
3075 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003076
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003078
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003080 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003081 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003082 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003083 } else {
3084 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003085 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003086 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003087 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003088 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003089 }
3090 ID.Kind = ValID::t_Constant;
3091 return false;
3092 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003093
Chris Lattnerac161bf2009-01-02 07:01:27 +00003094 // Binary Operators.
3095 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003096 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003098 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003099 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003100 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003101 case lltok::kw_udiv:
3102 case lltok::kw_sdiv:
3103 case lltok::kw_fdiv:
3104 case lltok::kw_urem:
3105 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003106 case lltok::kw_frem:
3107 case lltok::kw_shl:
3108 case lltok::kw_lshr:
3109 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003110 bool NUW = false;
3111 bool NSW = false;
3112 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003113 unsigned Opc = Lex.getUIntVal();
3114 Constant *Val0, *Val1;
3115 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003116 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003117 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3118 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003119 if (EatIfPresent(lltok::kw_nuw))
3120 NUW = true;
3121 if (EatIfPresent(lltok::kw_nsw)) {
3122 NSW = true;
3123 if (EatIfPresent(lltok::kw_nuw))
3124 NUW = true;
3125 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003126 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3127 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003128 if (EatIfPresent(lltok::kw_exact))
3129 Exact = true;
3130 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003131 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3132 ParseGlobalTypeAndValue(Val0) ||
3133 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3134 ParseGlobalTypeAndValue(Val1) ||
3135 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3136 return true;
3137 if (Val0->getType() != Val1->getType())
3138 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003139 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003140 if (NUW)
3141 return Error(ModifierLoc, "nuw only applies to integer operations");
3142 if (NSW)
3143 return Error(ModifierLoc, "nsw only applies to integer operations");
3144 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003145 // Check that the type is valid for the operator.
3146 switch (Opc) {
3147 case Instruction::Add:
3148 case Instruction::Sub:
3149 case Instruction::Mul:
3150 case Instruction::UDiv:
3151 case Instruction::SDiv:
3152 case Instruction::URem:
3153 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003154 case Instruction::Shl:
3155 case Instruction::AShr:
3156 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003157 if (!Val0->getType()->isIntOrIntVectorTy())
3158 return Error(ID.Loc, "constexpr requires integer operands");
3159 break;
3160 case Instruction::FAdd:
3161 case Instruction::FSub:
3162 case Instruction::FMul:
3163 case Instruction::FDiv:
3164 case Instruction::FRem:
3165 if (!Val0->getType()->isFPOrFPVectorTy())
3166 return Error(ID.Loc, "constexpr requires fp operands");
3167 break;
3168 default: llvm_unreachable("Unknown binary operator!");
3169 }
Dan Gohman1b849082009-09-07 23:54:19 +00003170 unsigned Flags = 0;
3171 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3172 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003173 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003174 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003175 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 ID.Kind = ValID::t_Constant;
3177 return false;
3178 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003179
Chris Lattnerac161bf2009-01-02 07:01:27 +00003180 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 case lltok::kw_and:
3182 case lltok::kw_or:
3183 case lltok::kw_xor: {
3184 unsigned Opc = Lex.getUIntVal();
3185 Constant *Val0, *Val1;
3186 Lex.Lex();
3187 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3188 ParseGlobalTypeAndValue(Val0) ||
3189 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3190 ParseGlobalTypeAndValue(Val1) ||
3191 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3192 return true;
3193 if (Val0->getType() != Val1->getType())
3194 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003195 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003196 return Error(ID.Loc,
3197 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003198 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003199 ID.Kind = ValID::t_Constant;
3200 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003201 }
3202
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 case lltok::kw_getelementptr:
3204 case lltok::kw_shufflevector:
3205 case lltok::kw_insertelement:
3206 case lltok::kw_extractelement:
3207 case lltok::kw_select: {
3208 unsigned Opc = Lex.getUIntVal();
3209 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003210 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003211 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003212 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003213
Dan Gohman1639c392009-07-27 21:53:46 +00003214 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003215 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003216
3217 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3218 return true;
3219
3220 LocTy ExplicitTypeLoc = Lex.getLoc();
3221 if (Opc == Instruction::GetElementPtr) {
3222 if (ParseType(Ty) ||
3223 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3224 return true;
3225 }
3226
Peter Collingbourned93620b2016-11-10 22:34:55 +00003227 Optional<unsigned> InRangeOp;
3228 if (ParseGlobalValueVector(
3229 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003230 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3231 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003232
Chris Lattnerac161bf2009-01-02 07:01:27 +00003233 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003234 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003235 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003236 return Error(ID.Loc, "base of getelementptr must be a pointer");
3237
3238 Type *BaseType = Elts[0]->getType();
3239 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003240 if (Ty != BasePointerType->getElementType())
3241 return Error(
3242 ExplicitTypeLoc,
3243 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003244
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003245 unsigned GEPWidth =
3246 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3247
Jay Foaded8db7d2011-07-21 14:31:17 +00003248 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003249 for (Constant *Val : Indices) {
3250 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003251 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003252 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003253 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003254 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003255 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003256 return Error(
3257 ID.Loc,
3258 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003259 // GEPWidth may have been unknown because the base is a scalar,
3260 // but it is known now.
3261 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003262 }
3263 }
3264
Craig Toppere3dcce92015-08-01 22:20:21 +00003265 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003266 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003267 return Error(ID.Loc, "base element of getelementptr must be sized");
3268
David Blaikie4a2e73b2015-04-02 18:55:32 +00003269 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003270 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003271
3272 if (InRangeOp) {
3273 if (*InRangeOp == 0)
3274 return Error(ID.Loc,
3275 "inrange keyword may not appear on pointer operand");
3276 --*InRangeOp;
3277 }
3278
3279 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3280 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003281 } else if (Opc == Instruction::Select) {
3282 if (Elts.size() != 3)
3283 return Error(ID.Loc, "expected three operands to select");
3284 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3285 Elts[2]))
3286 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003287 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003288 } else if (Opc == Instruction::ShuffleVector) {
3289 if (Elts.size() != 3)
3290 return Error(ID.Loc, "expected three operands to shufflevector");
3291 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3292 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003293 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003294 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003295 } else if (Opc == Instruction::ExtractElement) {
3296 if (Elts.size() != 2)
3297 return Error(ID.Loc, "expected two operands to extractelement");
3298 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3299 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003300 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003301 } else {
3302 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3303 if (Elts.size() != 3)
3304 return Error(ID.Loc, "expected three operands to insertelement");
3305 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3306 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003307 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003308 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003309 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003310
Chris Lattnerac161bf2009-01-02 07:01:27 +00003311 ID.Kind = ValID::t_Constant;
3312 return false;
3313 }
3314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003315
Chris Lattnerac161bf2009-01-02 07:01:27 +00003316 Lex.Lex();
3317 return false;
3318}
3319
3320/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003321bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003322 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003324 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003325 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003326 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003327 if (V && !(C = dyn_cast<Constant>(V)))
3328 return Error(ID.Loc, "global values must be constants");
3329 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003330}
3331
Victor Hernandez9d75c962010-01-11 22:31:58 +00003332bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003333 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003334 return ParseType(Ty) ||
3335 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003336}
3337
Rafael Espindola83a362c2015-01-06 22:55:16 +00003338bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003339 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003340
3341 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003342 if (!EatIfPresent(lltok::kw_comdat))
3343 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003344
3345 if (EatIfPresent(lltok::lparen)) {
3346 if (Lex.getKind() != lltok::ComdatVar)
3347 return TokError("expected comdat variable");
3348 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3349 Lex.Lex();
3350 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3351 return true;
3352 } else {
3353 if (GlobalName.empty())
3354 return TokError("comdat cannot be unnamed");
3355 C = getComdat(GlobalName, KwLoc);
3356 }
3357
David Majnemerdad0a642014-06-27 18:19:56 +00003358 return false;
3359}
3360
Victor Hernandez9d75c962010-01-11 22:31:58 +00003361/// ParseGlobalValueVector
3362/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003363/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3364bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3365 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003366 // Empty list.
3367 if (Lex.getKind() == lltok::rbrace ||
3368 Lex.getKind() == lltok::rsquare ||
3369 Lex.getKind() == lltok::greater ||
3370 Lex.getKind() == lltok::rparen)
3371 return false;
3372
Peter Collingbourned93620b2016-11-10 22:34:55 +00003373 do {
3374 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3375 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003376
Peter Collingbourned93620b2016-11-10 22:34:55 +00003377 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003378 if (ParseGlobalTypeAndValue(C)) return true;
3379 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003380 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003381
3382 return false;
3383}
3384
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003385bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003386 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003387 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003388 return true;
3389
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003390 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003391 return false;
3392}
3393
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003394/// MDNode:
3395/// ::= !{ ... }
3396/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003397/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003398bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003399 if (Lex.getKind() == lltok::MetadataVar)
3400 return ParseSpecializedMDNode(N);
3401
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003402 return ParseToken(lltok::exclaim, "expected '!' here") ||
3403 ParseMDNodeTail(N);
3404}
3405
3406bool LLParser::ParseMDNodeTail(MDNode *&N) {
3407 // !{ ... }
3408 if (Lex.getKind() == lltok::lbrace)
3409 return ParseMDTuple(N);
3410
3411 // !42
3412 return ParseMDNodeID(N);
3413}
3414
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003415namespace {
3416
3417/// Structure to represent an optional metadata field.
3418template <class FieldTy> struct MDFieldImpl {
3419 typedef MDFieldImpl ImplTy;
3420 FieldTy Val;
3421 bool Seen;
3422
3423 void assign(FieldTy Val) {
3424 Seen = true;
3425 this->Val = std::move(Val);
3426 }
3427
3428 explicit MDFieldImpl(FieldTy Default)
3429 : Val(std::move(Default)), Seen(false) {}
3430};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003431
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003432struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3433 uint64_t Max;
3434
3435 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3436 : ImplTy(Default), Max(Max) {}
3437};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003438
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003439struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003440 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003441};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003442
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003443struct ColumnField : public MDUnsignedField {
3444 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3445};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003446
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003447struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003448 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003449 DwarfTagField(dwarf::Tag DefaultTag)
3450 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003451};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003452
Amjad Abouda9bcf162015-12-10 12:56:35 +00003453struct DwarfMacinfoTypeField : public MDUnsignedField {
3454 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3455 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3456 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3457};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003458
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003459struct DwarfAttEncodingField : public MDUnsignedField {
3460 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3461};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003462
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003463struct DwarfVirtualityField : public MDUnsignedField {
3464 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3465};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003466
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003467struct DwarfLangField : public MDUnsignedField {
3468 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3469};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003470
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003471struct DwarfCCField : public MDUnsignedField {
3472 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3473};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003474
Adrian Prantlb939a252016-03-31 23:56:58 +00003475struct EmissionKindField : public MDUnsignedField {
3476 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3477};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003478
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003479struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3480 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003481};
3482
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003483struct MDSignedField : public MDFieldImpl<int64_t> {
3484 int64_t Min;
3485 int64_t Max;
3486
3487 MDSignedField(int64_t Default = 0)
3488 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3489 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3490 : ImplTy(Default), Min(Min), Max(Max) {}
3491};
3492
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003493struct MDBoolField : public MDFieldImpl<bool> {
3494 MDBoolField(bool Default = false) : ImplTy(Default) {}
3495};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003496
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003497struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003498 bool AllowNull;
3499
3500 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003501};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003502
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003503struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3504 MDConstant() : ImplTy(nullptr) {}
3505};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003506
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003507struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003508 bool AllowEmpty;
3509 MDStringField(bool AllowEmpty = true)
3510 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003511};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003512
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003513struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3514 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3515};
3516
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003517struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3518 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3519 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3520};
3521
Eugene Zelenko1804a772016-08-25 00:45:04 +00003522} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003523
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003524namespace llvm {
3525
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003526template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003527bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003528 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003529 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3530 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003531
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003532 auto &U = Lex.getAPSIntVal();
3533 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003534 return TokError("value for '" + Name + "' too large, limit is " +
3535 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003536 Result.assign(U.getZExtValue());
3537 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003538 Lex.Lex();
3539 return false;
3540}
3541
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003542template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003543bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3544 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3545}
3546template <>
3547bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3548 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3549}
3550
3551template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003552bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3553 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003554 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003555
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003556 if (Lex.getKind() != lltok::DwarfTag)
3557 return TokError("expected DWARF tag");
3558
3559 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3560 if (Tag == dwarf::DW_TAG_invalid)
3561 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003562 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003563
3564 Result.assign(Tag);
3565 Lex.Lex();
3566 return false;
3567}
3568
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003569template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003570bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003571 DwarfMacinfoTypeField &Result) {
3572 if (Lex.getKind() == lltok::APSInt)
3573 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3574
3575 if (Lex.getKind() != lltok::DwarfMacinfo)
3576 return TokError("expected DWARF macinfo type");
3577
3578 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3579 if (Macinfo == dwarf::DW_MACINFO_invalid)
3580 return TokError(
3581 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3582 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3583
3584 Result.assign(Macinfo);
3585 Lex.Lex();
3586 return false;
3587}
3588
3589template <>
3590bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003591 DwarfVirtualityField &Result) {
3592 if (Lex.getKind() == lltok::APSInt)
3593 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3594
3595 if (Lex.getKind() != lltok::DwarfVirtuality)
3596 return TokError("expected DWARF virtuality code");
3597
3598 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003599 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003600 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3601 Lex.getStrVal() + "'");
3602 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3603 Result.assign(Virtuality);
3604 Lex.Lex();
3605 return false;
3606}
3607
3608template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003609bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3610 if (Lex.getKind() == lltok::APSInt)
3611 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3612
3613 if (Lex.getKind() != lltok::DwarfLang)
3614 return TokError("expected DWARF language");
3615
3616 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3617 if (!Lang)
3618 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3619 "'");
3620 assert(Lang <= Result.Max && "Expected valid DWARF language");
3621 Result.assign(Lang);
3622 Lex.Lex();
3623 return false;
3624}
3625
3626template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003627bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3628 if (Lex.getKind() == lltok::APSInt)
3629 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3630
3631 if (Lex.getKind() != lltok::DwarfCC)
3632 return TokError("expected DWARF calling convention");
3633
3634 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3635 if (!CC)
3636 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3637 "'");
3638 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3639 Result.assign(CC);
3640 Lex.Lex();
3641 return false;
3642}
3643
3644template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003645bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3646 if (Lex.getKind() == lltok::APSInt)
3647 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3648
3649 if (Lex.getKind() != lltok::EmissionKind)
3650 return TokError("expected emission kind");
3651
3652 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3653 if (!Kind)
3654 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3655 "'");
3656 assert(*Kind <= Result.Max && "Expected valid emission kind");
3657 Result.assign(*Kind);
3658 Lex.Lex();
3659 return false;
3660}
3661
3662template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003663bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003664 DwarfAttEncodingField &Result) {
3665 if (Lex.getKind() == lltok::APSInt)
3666 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3667
3668 if (Lex.getKind() != lltok::DwarfAttEncoding)
3669 return TokError("expected DWARF type attribute encoding");
3670
3671 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3672 if (!Encoding)
3673 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3674 Lex.getStrVal() + "'");
3675 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3676 Result.assign(Encoding);
3677 Lex.Lex();
3678 return false;
3679}
3680
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003681/// DIFlagField
3682/// ::= uint32
3683/// ::= DIFlagVector
3684/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3685template <>
3686bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003687
3688 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003689 auto parseFlag = [&](DINode::DIFlags &Val) {
3690 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3691 uint32_t TempVal = static_cast<uint32_t>(Val);
3692 bool Res = ParseUInt32(TempVal);
3693 Val = static_cast<DINode::DIFlags>(TempVal);
3694 return Res;
3695 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003696
3697 if (Lex.getKind() != lltok::DIFlag)
3698 return TokError("expected debug info flag");
3699
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003700 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003701 if (!Val)
3702 return TokError(Twine("invalid debug info flag flag '") +
3703 Lex.getStrVal() + "'");
3704 Lex.Lex();
3705 return false;
3706 };
3707
3708 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003709 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003710 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003711 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003712 if (parseFlag(Val))
3713 return true;
3714 Combined |= Val;
3715 } while (EatIfPresent(lltok::bar));
3716
3717 Result.assign(Combined);
3718 return false;
3719}
3720
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003721template <>
3722bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003723 MDSignedField &Result) {
3724 if (Lex.getKind() != lltok::APSInt)
3725 return TokError("expected signed integer");
3726
3727 auto &S = Lex.getAPSIntVal();
3728 if (S < Result.Min)
3729 return TokError("value for '" + Name + "' too small, limit is " +
3730 Twine(Result.Min));
3731 if (S > Result.Max)
3732 return TokError("value for '" + Name + "' too large, limit is " +
3733 Twine(Result.Max));
3734 Result.assign(S.getExtValue());
3735 assert(Result.Val >= Result.Min && "Expected value in range");
3736 assert(Result.Val <= Result.Max && "Expected value in range");
3737 Lex.Lex();
3738 return false;
3739}
3740
3741template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003742bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3743 switch (Lex.getKind()) {
3744 default:
3745 return TokError("expected 'true' or 'false'");
3746 case lltok::kw_true:
3747 Result.assign(true);
3748 break;
3749 case lltok::kw_false:
3750 Result.assign(false);
3751 break;
3752 }
3753 Lex.Lex();
3754 return false;
3755}
3756
3757template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003758bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003759 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003760 if (!Result.AllowNull)
3761 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003762 Lex.Lex();
3763 Result.assign(nullptr);
3764 return false;
3765 }
3766
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003767 Metadata *MD;
3768 if (ParseMetadata(MD, nullptr))
3769 return true;
3770
3771 Result.assign(MD);
3772 return false;
3773}
3774
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003775template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003776bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003777 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003778 std::string S;
3779 if (ParseStringConstant(S))
3780 return true;
3781
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003782 if (!Result.AllowEmpty && S.empty())
3783 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3784
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003785 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003786 return false;
3787}
3788
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003789template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003790bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3791 SmallVector<Metadata *, 4> MDs;
3792 if (ParseMDNodeVector(MDs))
3793 return true;
3794
3795 Result.assign(std::move(MDs));
3796 return false;
3797}
3798
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003799template <>
3800bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3801 ChecksumKindField &Result) {
3802 if (Lex.getKind() != lltok::ChecksumKind)
3803 return TokError(
3804 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3805
3806 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3807
3808 Result.assign(CSKind);
3809 Lex.Lex();
3810 return false;
3811}
3812
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003813} // end namespace llvm
3814
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003815template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003816bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003817 do {
3818 if (Lex.getKind() != lltok::LabelStr)
3819 return TokError("expected field label here");
3820
3821 if (parseField())
3822 return true;
3823 } while (EatIfPresent(lltok::comma));
3824
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003825 return false;
3826}
3827
3828template <class ParserTy>
3829bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3830 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3831 Lex.Lex();
3832
3833 if (ParseToken(lltok::lparen, "expected '(' here"))
3834 return true;
3835 if (Lex.getKind() != lltok::rparen)
3836 if (ParseMDFieldsImplBody(parseField))
3837 return true;
3838
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003839 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003840 return ParseToken(lltok::rparen, "expected ')' here");
3841}
3842
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003843template <class FieldTy>
3844bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3845 if (Result.Seen)
3846 return TokError("field '" + Name + "' cannot be specified more than once");
3847
3848 LocTy Loc = Lex.getLoc();
3849 Lex.Lex();
3850 return ParseMDField(Loc, Name, Result);
3851}
3852
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003853bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3854 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003855
3856#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003857 if (Lex.getStrVal() == #CLASS) \
3858 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003859#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003860
3861 return TokError("expected metadata type");
3862}
3863
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003864#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3865#define NOP_FIELD(NAME, TYPE, INIT)
3866#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3867 if (!NAME.Seen) \
3868 return Error(ClosingLoc, "missing required field '" #NAME "'");
3869#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003870 if (Lex.getStrVal() == #NAME) \
3871 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003872#define PARSE_MD_FIELDS() \
3873 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3874 do { \
3875 LocTy ClosingLoc; \
3876 if (ParseMDFieldsImpl([&]() -> bool { \
3877 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3878 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3879 }, ClosingLoc)) \
3880 return true; \
3881 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3882 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003883#define GET_OR_DISTINCT(CLASS, ARGS) \
3884 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003885
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003886/// ParseDILocationFields:
3887/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3888bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003889#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003890 OPTIONAL(line, LineField, ); \
3891 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003892 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003893 OPTIONAL(inlinedAt, MDField, );
3894 PARSE_MD_FIELDS();
3895#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003896
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003897 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003898 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003899 return false;
3900}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003901
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003902/// ParseGenericDINode:
3903/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3904bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003905#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003906 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003907 OPTIONAL(header, MDStringField, ); \
3908 OPTIONAL(operands, MDFieldList, );
3909 PARSE_MD_FIELDS();
3910#undef VISIT_MD_FIELDS
3911
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003912 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003913 (Context, tag.Val, header.Val, operands.Val));
3914 return false;
3915}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003916
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003917/// ParseDISubrange:
3918/// ::= !DISubrange(count: 30, lowerBound: 2)
3919bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003921 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003922 OPTIONAL(lowerBound, MDSignedField, );
3923 PARSE_MD_FIELDS();
3924#undef VISIT_MD_FIELDS
3925
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003926 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003927 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003928}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003929
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003930/// ParseDIEnumerator:
3931/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3932bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003933#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003934 REQUIRED(name, MDStringField, ); \
3935 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003936 PARSE_MD_FIELDS();
3937#undef VISIT_MD_FIELDS
3938
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003939 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003940 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003941}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003942
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003943/// ParseDIBasicType:
3944/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3945bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003946#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003947 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003948 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003949 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003950 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003951 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003952 PARSE_MD_FIELDS();
3953#undef VISIT_MD_FIELDS
3954
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003955 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003956 align.Val, encoding.Val));
3957 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003958}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003959
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003960/// ParseDIDerivedType:
3961/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003962/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003963/// align: 32, offset: 0, flags: 0, extraData: !3,
3964/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003965bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003966#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3967 REQUIRED(tag, DwarfTagField, ); \
3968 OPTIONAL(name, MDStringField, ); \
3969 OPTIONAL(file, MDField, ); \
3970 OPTIONAL(line, LineField, ); \
3971 OPTIONAL(scope, MDField, ); \
3972 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003973 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003974 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003975 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003976 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003977 OPTIONAL(extraData, MDField, ); \
3978 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003979 PARSE_MD_FIELDS();
3980#undef VISIT_MD_FIELDS
3981
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003982 Optional<unsigned> DWARFAddressSpace;
3983 if (dwarfAddressSpace.Val != UINT32_MAX)
3984 DWARFAddressSpace = dwarfAddressSpace.Val;
3985
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003986 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003987 (Context, tag.Val, name.Val, file.Val, line.Val,
3988 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003989 offset.Val, DWARFAddressSpace, flags.Val,
3990 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003991 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003992}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003993
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003994bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003995#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3996 REQUIRED(tag, DwarfTagField, ); \
3997 OPTIONAL(name, MDStringField, ); \
3998 OPTIONAL(file, MDField, ); \
3999 OPTIONAL(line, LineField, ); \
4000 OPTIONAL(scope, MDField, ); \
4001 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004002 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004003 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004004 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004005 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004006 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004007 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004008 OPTIONAL(vtableHolder, MDField, ); \
4009 OPTIONAL(templateParams, MDField, ); \
4010 OPTIONAL(identifier, MDStringField, );
4011 PARSE_MD_FIELDS();
4012#undef VISIT_MD_FIELDS
4013
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004014 // If this has an identifier try to build an ODR type.
4015 if (identifier.Val)
4016 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004017 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4018 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4019 elements.Val, runtimeLang.Val, vtableHolder.Val,
4020 templateParams.Val)) {
4021 Result = CT;
4022 return false;
4023 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004024
4025 // Create a new node, and save it in the context if it belongs in the type
4026 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004027 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004028 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004029 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4030 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4031 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4032 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004033}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004034
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004035bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004036#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004037 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004038 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004039 REQUIRED(types, MDField, );
4040 PARSE_MD_FIELDS();
4041#undef VISIT_MD_FIELDS
4042
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004043 Result = GET_OR_DISTINCT(DISubroutineType,
4044 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004045 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004046}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004047
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004048/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004049/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4050/// checksumkind: CSK_MD5,
4051/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004052bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004053#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4054 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004055 REQUIRED(directory, MDStringField, ); \
4056 OPTIONAL(checksumkind, ChecksumKindField, ); \
4057 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004058 PARSE_MD_FIELDS();
4059#undef VISIT_MD_FIELDS
4060
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004061 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4062 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004063 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004064}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004065
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004066/// ParseDICompileUnit:
4067/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004068/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004069/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004070/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004071/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004072bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004073 if (!IsDistinct)
4074 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4075
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004076#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4077 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004078 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004079 OPTIONAL(producer, MDStringField, ); \
4080 OPTIONAL(isOptimized, MDBoolField, ); \
4081 OPTIONAL(flags, MDStringField, ); \
4082 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4083 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004084 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004085 OPTIONAL(enums, MDField, ); \
4086 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004087 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004088 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004089 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004090 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004091 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4092 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004093 PARSE_MD_FIELDS();
4094#undef VISIT_MD_FIELDS
4095
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004096 Result = DICompileUnit::getDistinct(
4097 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4098 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004099 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004100 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004101 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004102}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004103
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004104/// ParseDISubprogram:
4105/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004106/// file: !1, line: 7, type: !2, isLocal: false,
4107/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004108/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004109/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004110/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004111/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004112bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004113 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004114#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4115 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004116 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004117 OPTIONAL(linkageName, MDStringField, ); \
4118 OPTIONAL(file, MDField, ); \
4119 OPTIONAL(line, LineField, ); \
4120 OPTIONAL(type, MDField, ); \
4121 OPTIONAL(isLocal, MDBoolField, ); \
4122 OPTIONAL(isDefinition, MDBoolField, (true)); \
4123 OPTIONAL(scopeLine, LineField, ); \
4124 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004125 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004126 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004127 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004128 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004129 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004130 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004131 OPTIONAL(templateParams, MDField, ); \
4132 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004133 OPTIONAL(variables, MDField, ); \
4134 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004135 PARSE_MD_FIELDS();
4136#undef VISIT_MD_FIELDS
4137
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004138 if (isDefinition.Val && !IsDistinct)
4139 return Lex.Error(
4140 Loc,
4141 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4142
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004143 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004144 DISubprogram,
4145 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4146 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4147 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4148 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4149 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004150 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004151}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004152
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004153/// ParseDILexicalBlock:
4154/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4155bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004156#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004157 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004158 OPTIONAL(file, MDField, ); \
4159 OPTIONAL(line, LineField, ); \
4160 OPTIONAL(column, ColumnField, );
4161 PARSE_MD_FIELDS();
4162#undef VISIT_MD_FIELDS
4163
4164 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004165 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004166 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004167}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004168
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004169/// ParseDILexicalBlockFile:
4170/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4171bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004172#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004173 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004174 OPTIONAL(file, MDField, ); \
4175 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4176 PARSE_MD_FIELDS();
4177#undef VISIT_MD_FIELDS
4178
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004179 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004180 (Context, scope.Val, file.Val, discriminator.Val));
4181 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004182}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004183
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004184/// ParseDINamespace:
4185/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4186bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004187#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4188 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004189 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004190 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004191 PARSE_MD_FIELDS();
4192#undef VISIT_MD_FIELDS
4193
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004194 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004195 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004196 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004197}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004198
Amjad Abouda9bcf162015-12-10 12:56:35 +00004199/// ParseDIMacro:
4200/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4201bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4202#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4203 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004204 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004205 REQUIRED(name, MDStringField, ); \
4206 OPTIONAL(value, MDStringField, );
4207 PARSE_MD_FIELDS();
4208#undef VISIT_MD_FIELDS
4209
4210 Result = GET_OR_DISTINCT(DIMacro,
4211 (Context, type.Val, line.Val, name.Val, value.Val));
4212 return false;
4213}
4214
4215/// ParseDIMacroFile:
4216/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4217bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4218#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4219 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004220 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004221 REQUIRED(file, MDField, ); \
4222 OPTIONAL(nodes, MDField, );
4223 PARSE_MD_FIELDS();
4224#undef VISIT_MD_FIELDS
4225
4226 Result = GET_OR_DISTINCT(DIMacroFile,
4227 (Context, type.Val, line.Val, file.Val, nodes.Val));
4228 return false;
4229}
4230
Adrian Prantlab1243f2015-06-29 23:03:47 +00004231/// ParseDIModule:
4232/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4233/// includePath: "/usr/include", isysroot: "/")
4234bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4235#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4236 REQUIRED(scope, MDField, ); \
4237 REQUIRED(name, MDStringField, ); \
4238 OPTIONAL(configMacros, MDStringField, ); \
4239 OPTIONAL(includePath, MDStringField, ); \
4240 OPTIONAL(isysroot, MDStringField, );
4241 PARSE_MD_FIELDS();
4242#undef VISIT_MD_FIELDS
4243
4244 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4245 configMacros.Val, includePath.Val, isysroot.Val));
4246 return false;
4247}
4248
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004249/// ParseDITemplateTypeParameter:
4250/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4251bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004252#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004253 OPTIONAL(name, MDStringField, ); \
4254 REQUIRED(type, MDField, );
4255 PARSE_MD_FIELDS();
4256#undef VISIT_MD_FIELDS
4257
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004258 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004259 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004260 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004261}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004262
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004263/// ParseDITemplateValueParameter:
4264/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004265/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004266bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004267#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004268 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004269 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004270 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004271 REQUIRED(value, MDField, );
4272 PARSE_MD_FIELDS();
4273#undef VISIT_MD_FIELDS
4274
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004275 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004276 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004277 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004278}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004279
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004280/// ParseDIGlobalVariable:
4281/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004282/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004283/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004284bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004285#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004286 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004287 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004288 OPTIONAL(linkageName, MDStringField, ); \
4289 OPTIONAL(file, MDField, ); \
4290 OPTIONAL(line, LineField, ); \
4291 OPTIONAL(type, MDField, ); \
4292 OPTIONAL(isLocal, MDBoolField, ); \
4293 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004294 OPTIONAL(declaration, MDField, ); \
4295 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004296 PARSE_MD_FIELDS();
4297#undef VISIT_MD_FIELDS
4298
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004299 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004300 (Context, scope.Val, name.Val, linkageName.Val,
4301 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004302 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004303 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004304}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004305
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004306/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004307/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004308/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4309/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004310/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004311/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4312/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004313bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004315 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004316 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004317 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004318 OPTIONAL(file, MDField, ); \
4319 OPTIONAL(line, LineField, ); \
4320 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004321 OPTIONAL(flags, DIFlagField, ); \
4322 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004323 PARSE_MD_FIELDS();
4324#undef VISIT_MD_FIELDS
4325
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004326 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004327 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004328 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004329 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004330}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004331
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004332/// ParseDIExpression:
4333/// ::= !DIExpression(0, 7, -1)
4334bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004335 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4336 Lex.Lex();
4337
4338 if (ParseToken(lltok::lparen, "expected '(' here"))
4339 return true;
4340
4341 SmallVector<uint64_t, 8> Elements;
4342 if (Lex.getKind() != lltok::rparen)
4343 do {
4344 if (Lex.getKind() == lltok::DwarfOp) {
4345 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4346 Lex.Lex();
4347 Elements.push_back(Op);
4348 continue;
4349 }
4350 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4351 }
4352
4353 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4354 return TokError("expected unsigned integer");
4355
4356 auto &U = Lex.getAPSIntVal();
4357 if (U.ugt(UINT64_MAX))
4358 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4359 Elements.push_back(U.getZExtValue());
4360 Lex.Lex();
4361 } while (EatIfPresent(lltok::comma));
4362
4363 if (ParseToken(lltok::rparen, "expected ')' here"))
4364 return true;
4365
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004366 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004367 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004368}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004369
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004370/// ParseDIGlobalVariableExpression:
4371/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4372bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4373 bool IsDistinct) {
4374#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4375 REQUIRED(var, MDField, ); \
4376 OPTIONAL(expr, MDField, );
4377 PARSE_MD_FIELDS();
4378#undef VISIT_MD_FIELDS
4379
4380 Result =
4381 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4382 return false;
4383}
4384
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004385/// ParseDIObjCProperty:
4386/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004387/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004388bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004389#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004390 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004391 OPTIONAL(file, MDField, ); \
4392 OPTIONAL(line, LineField, ); \
4393 OPTIONAL(setter, MDStringField, ); \
4394 OPTIONAL(getter, MDStringField, ); \
4395 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4396 OPTIONAL(type, MDField, );
4397 PARSE_MD_FIELDS();
4398#undef VISIT_MD_FIELDS
4399
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004400 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004401 (Context, name.Val, file.Val, line.Val, setter.Val,
4402 getter.Val, attributes.Val, type.Val));
4403 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004404}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004405
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004406/// ParseDIImportedEntity:
4407/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004408/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004409bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004410#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4411 REQUIRED(tag, DwarfTagField, ); \
4412 REQUIRED(scope, MDField, ); \
4413 OPTIONAL(entity, MDField, ); \
4414 OPTIONAL(line, LineField, ); \
4415 OPTIONAL(name, MDStringField, );
4416 PARSE_MD_FIELDS();
4417#undef VISIT_MD_FIELDS
4418
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004419 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004420 entity.Val, line.Val, name.Val));
4421 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004422}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004423
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004424#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004425#undef NOP_FIELD
4426#undef REQUIRE_FIELD
4427#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004428
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004429/// ParseMetadataAsValue
4430/// ::= metadata i32 %local
4431/// ::= metadata i32 @global
4432/// ::= metadata i32 7
4433/// ::= metadata !0
4434/// ::= metadata !{...}
4435/// ::= metadata !"string"
4436bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4437 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004438 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004439 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004440 return true;
4441
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004442 V = MetadataAsValue::get(Context, MD);
4443 return false;
4444}
4445
4446/// ParseValueAsMetadata
4447/// ::= i32 %local
4448/// ::= i32 @global
4449/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004450bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4451 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004452 Type *Ty;
4453 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004454 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004455 return true;
4456 if (Ty->isMetadataTy())
4457 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4458
4459 Value *V;
4460 if (ParseValue(Ty, V, PFS))
4461 return true;
4462
4463 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004464 return false;
4465}
4466
4467/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004468/// ::= i32 %local
4469/// ::= i32 @global
4470/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004471/// ::= !42
4472/// ::= !{...}
4473/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004474/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004475bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004476 if (Lex.getKind() == lltok::MetadataVar) {
4477 MDNode *N;
4478 if (ParseSpecializedMDNode(N))
4479 return true;
4480 MD = N;
4481 return false;
4482 }
4483
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004484 // ValueAsMetadata:
4485 // <type> <value>
4486 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004487 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004488
4489 // '!'.
4490 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4491 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004492
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004493 // MDString:
4494 // ::= '!' STRINGCONSTANT
4495 if (Lex.getKind() == lltok::StringConstant) {
4496 MDString *S;
4497 if (ParseMDString(S))
4498 return true;
4499 MD = S;
4500 return false;
4501 }
4502
Dan Gohman8939ba332010-07-14 18:26:50 +00004503 // MDNode:
4504 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004505 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004506 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004507 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004508 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004509 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004510 return false;
4511}
4512
Victor Hernandez9d75c962010-01-11 22:31:58 +00004513//===----------------------------------------------------------------------===//
4514// Function Parsing.
4515//===----------------------------------------------------------------------===//
4516
Chris Lattner229907c2011-07-18 04:54:35 +00004517bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004518 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004519 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004521
Chris Lattnerac161bf2009-01-02 07:01:27 +00004522 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004524 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004525 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004526 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004527 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004528 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004529 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004530 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004531 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004532 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004533 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004534 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4535 (ID.UIntVal >> 1) & 1,
4536 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004537 return false;
4538 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004539 case ValID::t_GlobalName:
4540 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004541 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542 case ValID::t_GlobalID:
4543 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004544 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004546 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004547 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004548 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004549 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 return false;
4551 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004552 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004553 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4554 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004555
Dan Gohman518cda42011-12-17 00:04:22 +00004556 // The lexer has no type info, so builds all half, float, and double FP
4557 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004558 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004559 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004560 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004561 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004562 &Ignored);
4563 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004564 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004565 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004566 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004567 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004568
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004569 if (V->getType() != Ty)
4570 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004571 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004572
Chris Lattnerac161bf2009-01-02 07:01:27 +00004573 return false;
4574 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004575 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004576 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004577 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578 return false;
4579 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004580 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004581 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004582 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004583 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004585 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004586 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004587 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004588 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004589 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004590 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004591 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004592 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004594 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004595 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004596 case ValID::t_None:
4597 if (!Ty->isTokenTy())
4598 return Error(ID.Loc, "invalid type for none constant");
4599 V = Constant::getNullValue(Ty);
4600 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004602 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004604
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605 V = ID.ConstantVal;
4606 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004607 case ValID::t_ConstantStruct:
4608 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004609 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004610 if (ST->getNumElements() != ID.UIntVal)
4611 return Error(ID.Loc,
4612 "initializer with struct type has wrong # elements");
4613 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4614 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004615
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004616 // Verify that the elements are compatible with the structtype.
4617 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4618 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4619 return Error(ID.Loc, "element " + Twine(i) +
4620 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004621
David Blaikieadbda4b2015-08-03 20:08:41 +00004622 V = ConstantStruct::get(
4623 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004624 } else
4625 return Error(ID.Loc, "constant expression type mismatch");
4626 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004628 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004629}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004630
Alex Lorenzd2255952015-07-17 22:07:03 +00004631bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4632 C = nullptr;
4633 ValID ID;
4634 auto Loc = Lex.getLoc();
4635 if (ParseValID(ID, /*PFS=*/nullptr))
4636 return true;
4637 switch (ID.Kind) {
4638 case ValID::t_APSInt:
4639 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004640 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004641 case ValID::t_Constant:
4642 case ValID::t_ConstantStruct:
4643 case ValID::t_PackedConstantStruct: {
4644 Value *V;
4645 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4646 return true;
4647 assert(isa<Constant>(V) && "Expected a constant value");
4648 C = cast<Constant>(V);
4649 return false;
4650 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004651 case ValID::t_Null:
4652 C = Constant::getNullValue(Ty);
4653 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004654 default:
4655 return Error(Loc, "expected a constant value");
4656 }
4657}
4658
David Majnemer8a1c45d2015-12-12 05:38:55 +00004659bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004660 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004662 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004663}
4664
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004665bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004666 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004667 return ParseType(Ty) ||
4668 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669}
4670
Chris Lattner3ed871f2009-10-27 19:13:16 +00004671bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4672 PerFunctionState &PFS) {
4673 Value *V;
4674 Loc = Lex.getLoc();
4675 if (ParseTypeAndValue(V, PFS)) return true;
4676 if (!isa<BasicBlock>(V))
4677 return Error(Loc, "expected a basic block");
4678 BB = cast<BasicBlock>(V);
4679 return false;
4680}
4681
Chris Lattnerac161bf2009-01-02 07:01:27 +00004682/// FunctionHeader
4683/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004684/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004685/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004686bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4687 // Parse the linkage.
4688 LocTy LinkageLoc = Lex.getLoc();
4689 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004690
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004691 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004692 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004693 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004694 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004695 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004696 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004697 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004698 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4699 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004700 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701 return true;
4702
4703 // Verify that the linkage is ok.
4704 switch ((GlobalValue::LinkageTypes)Linkage) {
4705 case GlobalValue::ExternalLinkage:
4706 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004707 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004708 if (isDefine)
4709 return Error(LinkageLoc, "invalid linkage for function definition");
4710 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004711 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004712 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004713 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004714 case GlobalValue::LinkOnceAnyLinkage:
4715 case GlobalValue::LinkOnceODRLinkage:
4716 case GlobalValue::WeakAnyLinkage:
4717 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 if (!isDefine)
4719 return Error(LinkageLoc, "invalid linkage for function declaration");
4720 break;
4721 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004722 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 return Error(LinkageLoc, "invalid function linkage type");
4724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004725
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004726 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4727 return Error(LinkageLoc,
4728 "symbol with local linkage must have default visibility");
4729
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004730 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004732
Chris Lattnerac161bf2009-01-02 07:01:27 +00004733 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004734
4735 std::string FunctionName;
4736 if (Lex.getKind() == lltok::GlobalVar) {
4737 FunctionName = Lex.getStrVal();
4738 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4739 unsigned NameID = Lex.getUIntVal();
4740
4741 if (NameID != NumberedVals.size())
4742 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004743 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004744 } else {
4745 return TokError("expected function name");
4746 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004747
Chris Lattner3822f632009-01-02 08:05:26 +00004748 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004749
Chris Lattner3822f632009-01-02 08:05:26 +00004750 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004752
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004753 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004754 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004755 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004756 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004757 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004758 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004760 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004761 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004762 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004763 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004764 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004765 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004766 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004767
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004768 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004769 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004770 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004771 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004772 (EatIfPresent(lltok::kw_section) &&
4773 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004774 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004775 ParseOptionalAlignment(Alignment) ||
4776 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004777 ParseStringConstant(GC)) ||
4778 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004779 ParseGlobalTypeAndValue(Prefix)) ||
4780 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004781 ParseGlobalTypeAndValue(Prologue)) ||
4782 (EatIfPresent(lltok::kw_personality) &&
4783 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004784 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785
Michael Gottesman41748d72013-06-27 00:25:01 +00004786 if (FuncAttrs.contains(Attribute::Builtin))
4787 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004788
Chris Lattnerac161bf2009-01-02 07:01:27 +00004789 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004790 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004791 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004792 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004793 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004794
Chris Lattnerac161bf2009-01-02 07:01:27 +00004795 // Okay, if we got here, the function is syntactically valid. Convert types
4796 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004797 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004798 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004799
Chris Lattnerac161bf2009-01-02 07:01:27 +00004800 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004801 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004802 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803 }
4804
Reid Kleckner7f720332017-04-13 00:58:09 +00004805 AttributeList PAL =
4806 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4807 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004808
Bill Wendling749a43d2012-12-30 13:50:49 +00004809 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004810 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4811
Chris Lattner229907c2011-07-18 04:54:35 +00004812 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004813 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004814 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004815
Craig Topper2617dcc2014-04-15 06:32:26 +00004816 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 if (!FunctionName.empty()) {
4818 // If this was a definition of a forward reference, remove the definition
4819 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004820 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004821 if (FRVI != ForwardRefVals.end()) {
4822 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004823 if (!Fn)
4824 return Error(FRVI->second.second, "invalid forward reference to "
4825 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004826 if (Fn->getType() != PFT)
4827 return Error(FRVI->second.second, "invalid forward reference to "
4828 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004829
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 ForwardRefVals.erase(FRVI);
4831 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004832 // Reject redefinitions.
4833 return Error(NameLoc, "invalid redefinition of function '" +
4834 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004835 } else if (M->getNamedValue(FunctionName)) {
4836 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004837 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004838
Dan Gohman399d6ae2009-08-29 23:37:49 +00004839 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 // If this is a definition of a forward referenced function, make sure the
4841 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004842 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004843 if (I != ForwardRefValIDs.end()) {
4844 Fn = cast<Function>(I->second.first);
4845 if (Fn->getType() != PFT)
4846 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004847 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 ForwardRefValIDs.erase(I);
4849 }
4850 }
4851
Craig Topper2617dcc2014-04-15 06:32:26 +00004852 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004853 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4854 else // Move the forward-reference to the correct spot in the module.
4855 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4856
4857 if (FunctionName.empty())
4858 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004859
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4861 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004862 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 Fn->setCallingConv(CC);
4864 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004865 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004866 Fn->setAlignment(Alignment);
4867 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004868 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004869 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004870 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004871 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004872 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004873 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004874
Chris Lattnerac161bf2009-01-02 07:01:27 +00004875 // Add all of the arguments we parsed to the function.
4876 Function::arg_iterator ArgIt = Fn->arg_begin();
4877 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4878 // If the argument has a name, insert it into the argument symbol table.
4879 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004880
Chris Lattnerac161bf2009-01-02 07:01:27 +00004881 // Set the name, if it conflicted, it will be auto-renamed.
4882 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004883
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004884 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004885 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4886 ArgList[i].Name + "'");
4887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004888
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004889 if (isDefine)
4890 return false;
4891
Robin Morisset039781e2014-08-29 21:53:01 +00004892 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004893 ValID ID;
4894 if (FunctionName.empty()) {
4895 ID.Kind = ValID::t_GlobalID;
4896 ID.UIntVal = NumberedVals.size() - 1;
4897 } else {
4898 ID.Kind = ValID::t_GlobalName;
4899 ID.StrVal = FunctionName;
4900 }
4901 auto Blocks = ForwardRefBlockAddresses.find(ID);
4902 if (Blocks != ForwardRefBlockAddresses.end())
4903 return Error(Blocks->first.Loc,
4904 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905 return false;
4906}
4907
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004908bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4909 ValID ID;
4910 if (FunctionNumber == -1) {
4911 ID.Kind = ValID::t_GlobalName;
4912 ID.StrVal = F.getName();
4913 } else {
4914 ID.Kind = ValID::t_GlobalID;
4915 ID.UIntVal = FunctionNumber;
4916 }
4917
4918 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4919 if (Blocks == P.ForwardRefBlockAddresses.end())
4920 return false;
4921
4922 for (const auto &I : Blocks->second) {
4923 const ValID &BBID = I.first;
4924 GlobalValue *GV = I.second;
4925
4926 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4927 "Expected local id or name");
4928 BasicBlock *BB;
4929 if (BBID.Kind == ValID::t_LocalName)
4930 BB = GetBB(BBID.StrVal, BBID.Loc);
4931 else
4932 BB = GetBB(BBID.UIntVal, BBID.Loc);
4933 if (!BB)
4934 return P.Error(BBID.Loc, "referenced value is not a basic block");
4935
4936 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4937 GV->eraseFromParent();
4938 }
4939
4940 P.ForwardRefBlockAddresses.erase(Blocks);
4941 return false;
4942}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943
4944/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004945/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004947 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 return TokError("expected '{' in function body");
4949 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004950
Chris Lattner3432c622009-10-28 03:39:23 +00004951 int FunctionNumber = -1;
4952 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004953
Chris Lattner3432c622009-10-28 03:39:23 +00004954 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004955
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004956 // Resolve block addresses and allow basic blocks to be forward-declared
4957 // within this function.
4958 if (PFS.resolveForwardRefBlockAddresses())
4959 return true;
4960 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4961
Chris Lattnerbbddd962010-01-09 19:20:07 +00004962 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004963 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004964 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004965
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004966 while (Lex.getKind() != lltok::rbrace &&
4967 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004968 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004969
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004970 while (Lex.getKind() != lltok::rbrace)
4971 if (ParseUseListOrder(&PFS))
4972 return true;
4973
Chris Lattnerac161bf2009-01-02 07:01:27 +00004974 // Eat the }.
4975 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004976
Chris Lattnerac161bf2009-01-02 07:01:27 +00004977 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004978 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979}
4980
4981/// ParseBasicBlock
4982/// ::= LabelStr? Instruction*
4983bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4984 // If this basic block starts out with a name, remember it.
4985 std::string Name;
4986 LocTy NameLoc = Lex.getLoc();
4987 if (Lex.getKind() == lltok::LabelStr) {
4988 Name = Lex.getStrVal();
4989 Lex.Lex();
4990 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004991
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004993 if (!BB)
4994 return Error(NameLoc,
4995 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004996
Chris Lattnerac161bf2009-01-02 07:01:27 +00004997 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004998
Chris Lattnerac161bf2009-01-02 07:01:27 +00004999 // Parse the instructions in this block until we get a terminator.
5000 Instruction *Inst;
5001 do {
5002 // This instruction may have three possibilities for a name: a) none
5003 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5004 LocTy NameLoc = Lex.getLoc();
5005 int NameID = -1;
5006 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005007
Chris Lattnerac161bf2009-01-02 07:01:27 +00005008 if (Lex.getKind() == lltok::LocalVarID) {
5009 NameID = Lex.getUIntVal();
5010 Lex.Lex();
5011 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5012 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005013 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 NameStr = Lex.getStrVal();
5015 Lex.Lex();
5016 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5017 return true;
5018 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005019
Chris Lattner77b89dc2009-12-30 05:23:43 +00005020 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005021 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005022 case InstError: return true;
5023 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005024 BB->getInstList().push_back(Inst);
5025
Chris Lattner77b89dc2009-12-30 05:23:43 +00005026 // With a normal result, we check to see if the instruction is followed by
5027 // a comma and metadata.
5028 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005029 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005030 return true;
5031 break;
5032 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005033 BB->getInstList().push_back(Inst);
5034
Chris Lattner77b89dc2009-12-30 05:23:43 +00005035 // If the instruction parser ate an extra comma at the end of it, it
5036 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005037 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005038 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005039 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005040 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005041
Chris Lattnerac161bf2009-01-02 07:01:27 +00005042 // Set the name on the instruction.
5043 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5044 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005045
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 return false;
5047}
5048
5049//===----------------------------------------------------------------------===//
5050// Instruction Parsing.
5051//===----------------------------------------------------------------------===//
5052
5053/// ParseInstruction - Parse one of the many different instructions.
5054///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005055int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5056 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005057 lltok::Kind Token = Lex.getKind();
5058 if (Token == lltok::Eof)
5059 return TokError("found end of file when expecting more instructions");
5060 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005061 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005062 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005063
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 switch (Token) {
5065 default: return Error(Loc, "expected instruction opcode");
5066 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005067 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005068 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5069 case lltok::kw_br: return ParseBr(Inst, PFS);
5070 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005071 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005073 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005074 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5075 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005076 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5077 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005078 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005079 // Binary Operators.
5080 case lltok::kw_add:
5081 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005082 case lltok::kw_mul:
5083 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005084 bool NUW = EatIfPresent(lltok::kw_nuw);
5085 bool NSW = EatIfPresent(lltok::kw_nsw);
5086 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005087
Chris Lattnera676c0f2011-02-07 16:40:21 +00005088 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005089
Chris Lattnera676c0f2011-02-07 16:40:21 +00005090 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5091 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5092 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005093 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005094 case lltok::kw_fadd:
5095 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005096 case lltok::kw_fmul:
5097 case lltok::kw_fdiv:
5098 case lltok::kw_frem: {
5099 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5100 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5101 if (Res != 0)
5102 return Res;
5103 if (FMF.any())
5104 Inst->setFastMathFlags(FMF);
5105 return 0;
5106 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005107
Chris Lattner35315d02011-02-06 21:44:57 +00005108 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005109 case lltok::kw_udiv:
5110 case lltok::kw_lshr:
5111 case lltok::kw_ashr: {
5112 bool Exact = EatIfPresent(lltok::kw_exact);
5113
5114 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5115 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5116 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005117 }
5118
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005120 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005121 case lltok::kw_and:
5122 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005123 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005124 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5125 case lltok::kw_fcmp: {
5126 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5127 int Res = ParseCompare(Inst, PFS, KeywordVal);
5128 if (Res != 0)
5129 return Res;
5130 if (FMF.any())
5131 Inst->setFastMathFlags(FMF);
5132 return 0;
5133 }
5134
Chris Lattnerac161bf2009-01-02 07:01:27 +00005135 // Casts.
5136 case lltok::kw_trunc:
5137 case lltok::kw_zext:
5138 case lltok::kw_sext:
5139 case lltok::kw_fptrunc:
5140 case lltok::kw_fpext:
5141 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005142 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005143 case lltok::kw_uitofp:
5144 case lltok::kw_sitofp:
5145 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005146 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005148 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149 // Other.
5150 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005151 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005152 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5153 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5154 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5155 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005156 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005157 // Call.
5158 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5159 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5160 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005161 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005163 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005164 case lltok::kw_load: return ParseLoad(Inst, PFS);
5165 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005166 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5167 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005168 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005169 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5170 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5171 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5172 }
5173}
5174
5175/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5176bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005177 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005178 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005179 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005180 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5181 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5182 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5183 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5184 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5185 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5186 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5187 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5188 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5189 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5190 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5191 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5192 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5193 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5194 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5195 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5196 }
5197 } else {
5198 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005199 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5201 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5202 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5203 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5204 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5205 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5206 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5207 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5208 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5209 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5210 }
5211 }
5212 Lex.Lex();
5213 return false;
5214}
5215
5216//===----------------------------------------------------------------------===//
5217// Terminator Instructions.
5218//===----------------------------------------------------------------------===//
5219
5220/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005221/// ::= 'ret' void (',' !dbg, !1)*
5222/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005223bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005224 PerFunctionState &PFS) {
5225 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005226 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005227 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005228
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005229 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005230
Chris Lattnerfdd87902009-10-05 05:54:46 +00005231 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005232 if (!ResType->isVoidTy())
5233 return Error(TypeLoc, "value doesn't match function result type '" +
5234 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005235
Owen Anderson55f1c092009-08-13 21:58:54 +00005236 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005237 return false;
5238 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005239
Chris Lattnerac161bf2009-01-02 07:01:27 +00005240 Value *RV;
5241 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005243 if (ResType != RV->getType())
5244 return Error(TypeLoc, "value doesn't match function result type '" +
5245 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005246
Owen Anderson55f1c092009-08-13 21:58:54 +00005247 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005248 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005249}
5250
Chris Lattnerac161bf2009-01-02 07:01:27 +00005251/// ParseBr
5252/// ::= 'br' TypeAndValue
5253/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5254bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5255 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005256 Value *Op0;
5257 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005258 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5261 Inst = BranchInst::Create(BB);
5262 return false;
5263 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005264
Owen Anderson55f1c092009-08-13 21:58:54 +00005265 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005266 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005267
Chris Lattnerac161bf2009-01-02 07:01:27 +00005268 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005269 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005271 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005273
Chris Lattner3ed871f2009-10-27 19:13:16 +00005274 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005275 return false;
5276}
5277
5278/// ParseSwitch
5279/// Instruction
5280/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5281/// JumpTable
5282/// ::= (TypeAndValue ',' TypeAndValue)*
5283bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5284 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005285 Value *Cond;
5286 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5288 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005289 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5291 return true;
5292
Duncan Sands19d0b472010-02-16 11:11:14 +00005293 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005295
Chris Lattnerac161bf2009-01-02 07:01:27 +00005296 // Parse the jump table pairs.
5297 SmallPtrSet<Value*, 32> SeenCases;
5298 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5299 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005300 Value *Constant;
5301 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005302
Chris Lattnerac161bf2009-01-02 07:01:27 +00005303 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5304 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005305 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005306 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005307
David Blaikie70573dc2014-11-19 07:49:26 +00005308 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005309 return Error(CondLoc, "duplicate case value in switch");
5310 if (!isa<ConstantInt>(Constant))
5311 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005312
Chris Lattner3ed871f2009-10-27 19:13:16 +00005313 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005315
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005317
Chris Lattner3ed871f2009-10-27 19:13:16 +00005318 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005319 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5320 SI->addCase(Table[i].first, Table[i].second);
5321 Inst = SI;
5322 return false;
5323}
5324
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005325/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005326/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005327/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5328bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005329 LocTy AddrLoc;
5330 Value *Address;
5331 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005332 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5333 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005334 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005335
Duncan Sands19d0b472010-02-16 11:11:14 +00005336 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005337 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005338
Chris Lattner3ed871f2009-10-27 19:13:16 +00005339 // Parse the destination list.
5340 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005341
Chris Lattner3ed871f2009-10-27 19:13:16 +00005342 if (Lex.getKind() != lltok::rsquare) {
5343 BasicBlock *DestBB;
5344 if (ParseTypeAndBasicBlock(DestBB, PFS))
5345 return true;
5346 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005347
Chris Lattner3ed871f2009-10-27 19:13:16 +00005348 while (EatIfPresent(lltok::comma)) {
5349 if (ParseTypeAndBasicBlock(DestBB, PFS))
5350 return true;
5351 DestList.push_back(DestBB);
5352 }
5353 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005354
Chris Lattner3ed871f2009-10-27 19:13:16 +00005355 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5356 return true;
5357
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005358 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005359 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5360 IBI->addDestination(DestList[i]);
5361 Inst = IBI;
5362 return false;
5363}
5364
Chris Lattnerac161bf2009-01-02 07:01:27 +00005365/// ParseInvoke
5366/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5367/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5368bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5369 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005370 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005371 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005372 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005373 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005374 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 LocTy RetTypeLoc;
5376 ValID CalleeID;
5377 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005378 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005379
Chris Lattner3ed871f2009-10-27 19:13:16 +00005380 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005381 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005382 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005383 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005384 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5385 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005386 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005388 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005389 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005390 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005391 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005392
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393 // If RetType is a non-function pointer type, then this is the short syntax
5394 // for the call, which means that RetType is just the return type. Infer the
5395 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005396 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5397 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005398 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005399 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005400 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5401 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005402
Chris Lattnerac161bf2009-01-02 07:01:27 +00005403 if (!FunctionType::isValidReturnType(RetType))
5404 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005405
Owen Anderson4056ca92009-07-29 22:17:13 +00005406 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005408
David Blaikie41ba2b42015-07-27 23:32:19 +00005409 CalleeID.FTy = Ty;
5410
Chris Lattnerac161bf2009-01-02 07:01:27 +00005411 // Look up the callee.
5412 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005413 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5414 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005415
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005416 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005417 SmallVector<Value *, 8> Args;
5418 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005419
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420 // Loop through FunctionType's arguments and ensure they are specified
5421 // correctly. Also, gather any parameter attributes.
5422 FunctionType::param_iterator I = Ty->param_begin();
5423 FunctionType::param_iterator E = Ty->param_end();
5424 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005425 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005426 if (I != E) {
5427 ExpectedTy = *I++;
5428 } else if (!Ty->isVarArg()) {
5429 return Error(ArgList[i].Loc, "too many arguments specified");
5430 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005431
Chris Lattnerac161bf2009-01-02 07:01:27 +00005432 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5433 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005434 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005435 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005436 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005438
Chris Lattnerac161bf2009-01-02 07:01:27 +00005439 if (I != E)
5440 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005441
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005442 if (FnAttrs.hasAlignmentAttr())
5443 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005444
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005445 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005446 AttributeList PAL =
5447 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5448 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005449
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005450 InvokeInst *II =
5451 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005452 II->setCallingConv(CC);
5453 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005454 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005455 Inst = II;
5456 return false;
5457}
5458
Bill Wendlingf891bf82011-07-31 06:30:59 +00005459/// ParseResume
5460/// ::= 'resume' TypeAndValue
5461bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5462 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005463 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5464 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005465
Bill Wendlingf891bf82011-07-31 06:30:59 +00005466 ResumeInst *RI = ResumeInst::Create(Exn);
5467 Inst = RI;
5468 return false;
5469}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005470
David Majnemer654e1302015-07-31 17:58:14 +00005471bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5472 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005473 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005474 return true;
5475
5476 while (Lex.getKind() != lltok::rsquare) {
5477 // If this isn't the first argument, we need a comma.
5478 if (!Args.empty() &&
5479 ParseToken(lltok::comma, "expected ',' in argument list"))
5480 return true;
5481
5482 // Parse the argument.
5483 LocTy ArgLoc;
5484 Type *ArgTy = nullptr;
5485 if (ParseType(ArgTy, ArgLoc))
5486 return true;
5487
5488 Value *V;
5489 if (ArgTy->isMetadataTy()) {
5490 if (ParseMetadataAsValue(V, PFS))
5491 return true;
5492 } else {
5493 if (ParseValue(ArgTy, V, PFS))
5494 return true;
5495 }
5496 Args.push_back(V);
5497 }
5498
5499 Lex.Lex(); // Lex the ']'.
5500 return false;
5501}
5502
5503/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005504/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005505bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005506 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005507
David Majnemer8a1c45d2015-12-12 05:38:55 +00005508 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5509 return true;
5510
5511 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005512 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005513
5514 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5515 return true;
5516
5517 BasicBlock *UnwindBB = nullptr;
5518 if (Lex.getKind() == lltok::kw_to) {
5519 Lex.Lex();
5520 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5521 return true;
5522 } else {
5523 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5524 return true;
5525 }
5526 }
5527
David Majnemer8a1c45d2015-12-12 05:38:55 +00005528 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005529 return false;
5530}
5531
5532/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005533/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005534bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005535 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005536
David Majnemer8a1c45d2015-12-12 05:38:55 +00005537 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5538 return true;
5539
5540 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005541 return true;
5542
David Majnemer0bc0eef2015-08-15 02:46:08 +00005543 BasicBlock *BB;
5544 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5545 ParseTypeAndBasicBlock(BB, PFS))
5546 return true;
5547
David Majnemer8a1c45d2015-12-12 05:38:55 +00005548 Inst = CatchReturnInst::Create(CatchPad, BB);
5549 return false;
5550}
5551
5552/// ParseCatchSwitch
5553/// ::= 'catchswitch' within Parent
5554bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5555 Value *ParentPad;
5556 LocTy BBLoc;
5557
5558 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5559 return true;
5560
5561 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5562 Lex.getKind() != lltok::LocalVarID)
5563 return TokError("expected scope value for catchswitch");
5564
5565 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5566 return true;
5567
5568 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5569 return true;
5570
5571 SmallVector<BasicBlock *, 32> Table;
5572 do {
5573 BasicBlock *DestBB;
5574 if (ParseTypeAndBasicBlock(DestBB, PFS))
5575 return true;
5576 Table.push_back(DestBB);
5577 } while (EatIfPresent(lltok::comma));
5578
5579 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5580 return true;
5581
5582 if (ParseToken(lltok::kw_unwind,
5583 "expected 'unwind' after catchswitch scope"))
5584 return true;
5585
5586 BasicBlock *UnwindBB = nullptr;
5587 if (EatIfPresent(lltok::kw_to)) {
5588 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5589 return true;
5590 } else {
5591 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5592 return true;
5593 }
5594
5595 auto *CatchSwitch =
5596 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5597 for (BasicBlock *DestBB : Table)
5598 CatchSwitch->addHandler(DestBB);
5599 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005600 return false;
5601}
5602
5603/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005604/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005605bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005606 Value *CatchSwitch = nullptr;
5607
5608 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5609 return true;
5610
5611 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5612 return TokError("expected scope value for catchpad");
5613
5614 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5615 return true;
5616
David Majnemer654e1302015-07-31 17:58:14 +00005617 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005618 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005619 return true;
5620
David Majnemer8a1c45d2015-12-12 05:38:55 +00005621 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005622 return false;
5623}
5624
David Majnemer654e1302015-07-31 17:58:14 +00005625/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005626/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005627bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005628 Value *ParentPad = nullptr;
5629
5630 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5631 return true;
5632
5633 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5634 Lex.getKind() != lltok::LocalVarID)
5635 return TokError("expected scope value for cleanuppad");
5636
5637 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5638 return true;
5639
David Majnemer654e1302015-07-31 17:58:14 +00005640 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005641 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005642 return true;
5643
David Majnemer8a1c45d2015-12-12 05:38:55 +00005644 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005645 return false;
5646}
5647
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648//===----------------------------------------------------------------------===//
5649// Binary Operators.
5650//===----------------------------------------------------------------------===//
5651
5652/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005653/// ::= ArithmeticOps TypeAndValue ',' Value
5654///
5655/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5656/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005658 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005659 LocTy Loc; Value *LHS, *RHS;
5660 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5661 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5662 ParseValue(LHS->getType(), RHS, PFS))
5663 return true;
5664
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005665 bool Valid;
5666 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005667 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005668 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005669 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5670 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005671 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005672 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5673 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005674 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005675
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005676 if (!Valid)
5677 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005678
Chris Lattnerac161bf2009-01-02 07:01:27 +00005679 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5680 return false;
5681}
5682
5683/// ParseLogical
5684/// ::= ArithmeticOps TypeAndValue ',' Value {
5685bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5686 unsigned Opc) {
5687 LocTy Loc; Value *LHS, *RHS;
5688 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5689 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5690 ParseValue(LHS->getType(), RHS, PFS))
5691 return true;
5692
Duncan Sands9dff9be2010-02-15 16:12:20 +00005693 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005694 return Error(Loc,"instruction requires integer or integer vector operands");
5695
5696 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5697 return false;
5698}
5699
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700/// ParseCompare
5701/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5702/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005703bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5704 unsigned Opc) {
5705 // Parse the integer/fp comparison predicate.
5706 LocTy Loc;
5707 unsigned Pred;
5708 Value *LHS, *RHS;
5709 if (ParseCmpPredicate(Pred, Opc) ||
5710 ParseTypeAndValue(LHS, Loc, PFS) ||
5711 ParseToken(lltok::comma, "expected ',' after compare value") ||
5712 ParseValue(LHS->getType(), RHS, PFS))
5713 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005714
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005716 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005718 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005719 } else {
5720 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005721 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00005722 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005723 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005724 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005725 }
5726 return false;
5727}
5728
5729//===----------------------------------------------------------------------===//
5730// Other Instructions.
5731//===----------------------------------------------------------------------===//
5732
5733
5734/// ParseCast
5735/// ::= CastOpc TypeAndValue 'to' Type
5736bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5737 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005738 LocTy Loc;
5739 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005740 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005741 if (ParseTypeAndValue(Op, Loc, PFS) ||
5742 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5743 ParseType(DestTy))
5744 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005745
Chris Lattner89d856e2009-03-01 00:53:13 +00005746 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5747 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005748 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005749 getTypeString(Op->getType()) + "' to '" +
5750 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005751 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005752 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5753 return false;
5754}
5755
5756/// ParseSelect
5757/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5758bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5759 LocTy Loc;
5760 Value *Op0, *Op1, *Op2;
5761 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5762 ParseToken(lltok::comma, "expected ',' after select condition") ||
5763 ParseTypeAndValue(Op1, PFS) ||
5764 ParseToken(lltok::comma, "expected ',' after select value") ||
5765 ParseTypeAndValue(Op2, PFS))
5766 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005767
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5769 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005770
Chris Lattnerac161bf2009-01-02 07:01:27 +00005771 Inst = SelectInst::Create(Op0, Op1, Op2);
5772 return false;
5773}
5774
Chris Lattnerb55ab542009-01-05 08:18:44 +00005775/// ParseVA_Arg
5776/// ::= 'va_arg' TypeAndValue ',' Type
5777bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005778 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005779 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005780 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005781 if (ParseTypeAndValue(Op, PFS) ||
5782 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005783 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005785
Chris Lattnerb55ab542009-01-05 08:18:44 +00005786 if (!EltTy->isFirstClassType())
5787 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788
5789 Inst = new VAArgInst(Op, EltTy);
5790 return false;
5791}
5792
5793/// ParseExtractElement
5794/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5795bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5796 LocTy Loc;
5797 Value *Op0, *Op1;
5798 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5799 ParseToken(lltok::comma, "expected ',' after extract value") ||
5800 ParseTypeAndValue(Op1, PFS))
5801 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005802
Chris Lattnerac161bf2009-01-02 07:01:27 +00005803 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5804 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005805
Eric Christopherc9742252009-07-25 02:28:41 +00005806 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005807 return false;
5808}
5809
5810/// ParseInsertElement
5811/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5812bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5813 LocTy Loc;
5814 Value *Op0, *Op1, *Op2;
5815 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5816 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5817 ParseTypeAndValue(Op1, PFS) ||
5818 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5819 ParseTypeAndValue(Op2, PFS))
5820 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005821
Chris Lattnerac161bf2009-01-02 07:01:27 +00005822 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005823 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005824
Chris Lattnerac161bf2009-01-02 07:01:27 +00005825 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5826 return false;
5827}
5828
5829/// ParseShuffleVector
5830/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5831bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5832 LocTy Loc;
5833 Value *Op0, *Op1, *Op2;
5834 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5835 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5836 ParseTypeAndValue(Op1, PFS) ||
5837 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5838 ParseTypeAndValue(Op2, PFS))
5839 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005840
Chris Lattnerac161bf2009-01-02 07:01:27 +00005841 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005842 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005843
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5845 return false;
5846}
5847
5848/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005849/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005850int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005851 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005853
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005854 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5856 ParseValue(Ty, Op0, PFS) ||
5857 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005858 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5860 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005861
Chris Lattnerf4f03422009-12-30 05:27:33 +00005862 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005863 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005864
5865 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005867
Chris Lattner3822f632009-01-02 08:05:26 +00005868 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005869 break;
5870
Chris Lattnerf4f03422009-12-30 05:27:33 +00005871 if (Lex.getKind() == lltok::MetadataVar) {
5872 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005873 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005874 }
Devang Patel8f842d32009-10-16 18:45:49 +00005875
Chris Lattner3822f632009-01-02 08:05:26 +00005876 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005877 ParseValue(Ty, Op0, PFS) ||
5878 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005879 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005880 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5881 return true;
5882 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005883
Chris Lattnerac161bf2009-01-02 07:01:27 +00005884 if (!Ty->isFirstClassType())
5885 return Error(TypeLoc, "phi node must have first class type");
5886
Jay Foad52131342011-03-30 11:28:46 +00005887 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005888 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5889 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5890 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005891 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005892}
5893
Bill Wendlingfae14752011-08-12 20:24:12 +00005894/// ParseLandingPad
5895/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5896/// Clause
5897/// ::= 'catch' TypeAndValue
5898/// ::= 'filter'
5899/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5900bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005901 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005902
David Majnemer7fddecc2015-06-17 20:52:32 +00005903 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005904 return true;
5905
David Majnemer7fddecc2015-06-17 20:52:32 +00005906 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005907 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5908
5909 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5910 LandingPadInst::ClauseType CT;
5911 if (EatIfPresent(lltok::kw_catch))
5912 CT = LandingPadInst::Catch;
5913 else if (EatIfPresent(lltok::kw_filter))
5914 CT = LandingPadInst::Filter;
5915 else
5916 return TokError("expected 'catch' or 'filter' clause type");
5917
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005918 Value *V;
5919 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005920 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005921 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005922
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005923 // A 'catch' type expects a non-array constant. A filter clause expects an
5924 // array constant.
5925 if (CT == LandingPadInst::Catch) {
5926 if (isa<ArrayType>(V->getType()))
5927 Error(VLoc, "'catch' clause has an invalid type");
5928 } else {
5929 if (!isa<ArrayType>(V->getType()))
5930 Error(VLoc, "'filter' clause has an invalid type");
5931 }
5932
Owen Andersonf8f259d2015-03-09 07:13:42 +00005933 Constant *CV = dyn_cast<Constant>(V);
5934 if (!CV)
5935 return Error(VLoc, "clause argument must be a constant");
5936 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005937 }
5938
Owen Andersonf8f259d2015-03-09 07:13:42 +00005939 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005940 return false;
5941}
5942
Chris Lattnerac161bf2009-01-02 07:01:27 +00005943/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005944/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5945/// OptionalAttrs Type Value ParameterList OptionalAttrs
5946/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5947/// OptionalAttrs Type Value ParameterList OptionalAttrs
5948/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5949/// OptionalAttrs Type Value ParameterList OptionalAttrs
5950/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5951/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005952bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005953 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005954 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005955 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005956 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005957 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005958 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005959 LocTy RetTypeLoc;
5960 ValID CalleeID;
5961 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005962 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005963 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005964
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005965 if (TCK != CallInst::TCK_None &&
5966 ParseToken(lltok::kw_call,
5967 "expected 'tail call', 'musttail call', or 'notail call'"))
5968 return true;
5969
5970 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5971
5972 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005973 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005974 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005975 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5976 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005977 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5978 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005979 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005980
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005981 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5982 return Error(CallLoc, "fast-math-flags specified for call without "
5983 "floating-point scalar or vector return type");
5984
Chris Lattnerac161bf2009-01-02 07:01:27 +00005985 // If RetType is a non-function pointer type, then this is the short syntax
5986 // for the call, which means that RetType is just the return type. Infer the
5987 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005988 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5989 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005990 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005991 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005992 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5993 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005994
Chris Lattnerac161bf2009-01-02 07:01:27 +00005995 if (!FunctionType::isValidReturnType(RetType))
5996 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005997
Owen Anderson4056ca92009-07-29 22:17:13 +00005998 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005999 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006000
David Blaikie41ba2b42015-07-27 23:32:19 +00006001 CalleeID.FTy = Ty;
6002
Chris Lattnerac161bf2009-01-02 07:01:27 +00006003 // Look up the callee.
6004 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00006005 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6006 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006007
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006008 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006009 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006010
Chris Lattnerac161bf2009-01-02 07:01:27 +00006011 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006012
Chris Lattnerac161bf2009-01-02 07:01:27 +00006013 // Loop through FunctionType's arguments and ensure they are specified
6014 // correctly. Also, gather any parameter attributes.
6015 FunctionType::param_iterator I = Ty->param_begin();
6016 FunctionType::param_iterator E = Ty->param_end();
6017 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006018 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006019 if (I != E) {
6020 ExpectedTy = *I++;
6021 } else if (!Ty->isVarArg()) {
6022 return Error(ArgList[i].Loc, "too many arguments specified");
6023 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006024
Chris Lattnerac161bf2009-01-02 07:01:27 +00006025 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6026 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006027 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006029 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006031
Chris Lattnerac161bf2009-01-02 07:01:27 +00006032 if (I != E)
6033 return Error(CallLoc, "not enough parameters specified for call");
6034
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006035 if (FnAttrs.hasAlignmentAttr())
6036 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006037
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006038 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006039 AttributeList PAL =
6040 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6041 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006042
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006043 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006044 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006045 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006046 if (FMF.any())
6047 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006048 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006049 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006050 Inst = CI;
6051 return false;
6052}
6053
6054//===----------------------------------------------------------------------===//
6055// Memory Instructions.
6056//===----------------------------------------------------------------------===//
6057
6058/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006059/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6060/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006061int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006062 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006063 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006064 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006065 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006066 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006067
6068 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006069 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006070
David Majnemera3b0eb22015-02-16 08:38:03 +00006071 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006072
David Majnemera3b0eb22015-02-16 08:38:03 +00006073 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6074 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006075
Chris Lattnerb2f39502009-12-30 05:44:30 +00006076 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006077 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006078 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006079 if (ParseOptionalAlignment(Alignment))
6080 return true;
6081 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6082 return true;
6083 } else if (Lex.getKind() == lltok::kw_addrspace) {
6084 ASLoc = Lex.getLoc();
6085 if (ParseOptionalAddrSpace(AddrSpace))
6086 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006087 } else if (Lex.getKind() == lltok::MetadataVar) {
6088 AteExtraComma = true;
6089 } else {
6090 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006091 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6092 (!AteExtraComma &&
6093 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006094 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006095 }
6096 }
6097
Dan Gohman2140a742010-05-28 01:14:11 +00006098 if (Size && !Size->getType()->isIntegerTy())
6099 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006100
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006101 const DataLayout &DL = M->getDataLayout();
6102 unsigned AS = DL.getAllocaAddrSpace();
6103 if (AS != AddrSpace) {
6104 // TODO: In the future it should be possible to specify addrspace per-alloca.
6105 return Error(ASLoc, "address space must match datalayout");
6106 }
6107
6108 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006109 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006110 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006111 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006112 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006113}
6114
6115/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006116/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006117/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006118/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006119int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006120 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006121 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006122 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006123 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006124 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006125 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006126
6127 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006128 isAtomic = true;
6129 Lex.Lex();
6130 }
6131
Chris Lattnerbc639292011-11-27 06:56:53 +00006132 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006133 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006134 isVolatile = true;
6135 Lex.Lex();
6136 }
6137
David Blaikie15d9a4c2015-04-06 20:59:48 +00006138 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006139 LocTy ExplicitTypeLoc = Lex.getLoc();
6140 if (ParseType(Ty) ||
6141 ParseToken(lltok::comma, "expected comma after load's type") ||
6142 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006143 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006144 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6145 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006146
David Blaikie15d9a4c2015-04-06 20:59:48 +00006147 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006148 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006149 if (isAtomic && !Alignment)
6150 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006151 if (Ordering == AtomicOrdering::Release ||
6152 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006153 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006154
David Blaikiea79ac142015-02-27 21:17:42 +00006155 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6156 return Error(ExplicitTypeLoc,
6157 "explicit pointee type doesn't match operand's pointee type");
6158
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006159 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006160 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006161}
6162
6163/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006164
6165/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6166/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006167/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006168int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006169 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006170 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006171 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006172 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006173 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006174 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006175
6176 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006177 isAtomic = true;
6178 Lex.Lex();
6179 }
6180
Chris Lattnerbc639292011-11-27 06:56:53 +00006181 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006182 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006183 isVolatile = true;
6184 Lex.Lex();
6185 }
6186
Chris Lattnerac161bf2009-01-02 07:01:27 +00006187 if (ParseTypeAndValue(Val, Loc, PFS) ||
6188 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006189 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006190 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006191 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006192 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006193
Duncan Sands19d0b472010-02-16 11:11:14 +00006194 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006195 return Error(PtrLoc, "store operand must be a pointer");
6196 if (!Val->getType()->isFirstClassType())
6197 return Error(Loc, "store operand must be a first class value");
6198 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6199 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006200 if (isAtomic && !Alignment)
6201 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006202 if (Ordering == AtomicOrdering::Acquire ||
6203 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006204 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006205
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006206 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006207 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006208}
6209
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006210/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006211/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6212/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006213int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006214 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6215 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006216 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6217 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006218 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006219 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006220 bool isWeak = false;
6221
6222 if (EatIfPresent(lltok::kw_weak))
6223 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006224
6225 if (EatIfPresent(lltok::kw_volatile))
6226 isVolatile = true;
6227
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006228 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6229 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6230 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6231 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6232 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006233 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006234 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006235 return true;
6236
JF Bastien800f87a2016-04-06 21:19:33 +00006237 if (SuccessOrdering == AtomicOrdering::Unordered ||
6238 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006239 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006240 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6241 return TokError("cmpxchg failure argument shall be no stronger than the "
6242 "success argument");
6243 if (FailureOrdering == AtomicOrdering::Release ||
6244 FailureOrdering == AtomicOrdering::AcquireRelease)
6245 return TokError(
6246 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006247 if (!Ptr->getType()->isPointerTy())
6248 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6249 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6250 return Error(CmpLoc, "compare value and pointer type do not match");
6251 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6252 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006253 if (!New->getType()->isFirstClassType())
6254 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006255 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006256 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006257 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006258 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006259 Inst = CXI;
6260 return AteExtraComma ? InstExtraComma : InstNormal;
6261}
6262
6263/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006264/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6265/// 'singlethread'? AtomicOrdering
6266int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006267 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6268 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006269 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006270 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006271 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006272 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006273
6274 if (EatIfPresent(lltok::kw_volatile))
6275 isVolatile = true;
6276
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006277 switch (Lex.getKind()) {
6278 default: return TokError("expected binary operation in atomicrmw");
6279 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6280 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6281 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6282 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6283 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6284 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6285 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6286 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6287 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6288 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6289 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6290 }
6291 Lex.Lex(); // Eat the operation.
6292
6293 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6294 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6295 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006296 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006297 return true;
6298
JF Bastien800f87a2016-04-06 21:19:33 +00006299 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006300 return TokError("atomicrmw cannot be unordered");
6301 if (!Ptr->getType()->isPointerTy())
6302 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6303 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6304 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6305 if (!Val->getType()->isIntegerTy())
6306 return Error(ValLoc, "atomicrmw operand must be an integer");
6307 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6308 if (Size < 8 || (Size & (Size - 1)))
6309 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6310 " integer");
6311
6312 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006313 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006314 RMWI->setVolatile(isVolatile);
6315 Inst = RMWI;
6316 return AteExtraComma ? InstExtraComma : InstNormal;
6317}
6318
Eli Friedmanfee02c62011-07-25 23:16:38 +00006319/// ParseFence
6320/// ::= 'fence' 'singlethread'? AtomicOrdering
6321int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006322 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006323 SyncScope::ID SSID = SyncScope::System;
6324 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006325 return true;
6326
JF Bastien800f87a2016-04-06 21:19:33 +00006327 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006328 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006329 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006330 return TokError("fence cannot be monotonic");
6331
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006332 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006333 return InstNormal;
6334}
6335
Chris Lattnerac161bf2009-01-02 07:01:27 +00006336/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006337/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006338int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006339 Value *Ptr = nullptr;
6340 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006341 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006342
Dan Gohman16cbbe42009-07-29 15:58:36 +00006343 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006344
David Blaikie79e6c742015-02-27 19:29:02 +00006345 Type *Ty = nullptr;
6346 LocTy ExplicitTypeLoc = Lex.getLoc();
6347 if (ParseType(Ty) ||
6348 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6349 ParseTypeAndValue(Ptr, Loc, PFS))
6350 return true;
6351
Eli Benderskyd9806682013-04-22 17:03:42 +00006352 Type *BaseType = Ptr->getType();
6353 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6354 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006355 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006356
David Blaikie8d757942015-03-09 23:08:44 +00006357 if (Ty != BasePointerType->getElementType())
6358 return Error(ExplicitTypeLoc,
6359 "explicit pointee type doesn't match operand's pointee type");
6360
Chris Lattnerac161bf2009-01-02 07:01:27 +00006361 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006362 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006363 // GEP returns a vector of pointers if at least one of parameters is a vector.
6364 // All vector parameters should have the same vector width.
6365 unsigned GEPWidth = BaseType->isVectorTy() ?
6366 BaseType->getVectorNumElements() : 0;
6367
Chris Lattner3822f632009-01-02 08:05:26 +00006368 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006369 if (Lex.getKind() == lltok::MetadataVar) {
6370 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006371 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006372 }
Chris Lattner3822f632009-01-02 08:05:26 +00006373 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006374 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006375 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006376
Nadav Rotem3924cb02011-12-05 06:29:09 +00006377 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006378 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6379 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006380 return Error(EltLoc,
6381 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006382 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006383 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006384 Indices.push_back(Val);
6385 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006386
Craig Toppere3dcce92015-08-01 22:20:21 +00006387 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006388 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006389 return Error(Loc, "base element of getelementptr must be sized");
6390
David Blaikied33bad32015-04-17 22:32:13 +00006391 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006392 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006393 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006394 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006395 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006396 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006397}
6398
6399/// ParseExtractValue
6400/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006401int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 Value *Val; LocTy Loc;
6403 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006404 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006405 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006406 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006407 return true;
6408
Chris Lattner392be582010-02-12 20:49:41 +00006409 if (!Val->getType()->isAggregateType())
6410 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006411
Jay Foad57aa6362011-07-13 10:26:04 +00006412 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006413 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006414 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006415 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006416}
6417
6418/// ParseInsertValue
6419/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006420int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006421 Value *Val0, *Val1; LocTy Loc0, Loc1;
6422 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006423 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006424 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6425 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6426 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006427 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006428 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006429
Chris Lattner392be582010-02-12 20:49:41 +00006430 if (!Val0->getType()->isAggregateType())
6431 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006432
David Majnemer30074532015-02-11 07:43:58 +00006433 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6434 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006435 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006436 if (IndexedType != Val1->getType())
6437 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6438 getTypeString(Val1->getType()) + "' instead of '" +
6439 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006440 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006441 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006442}
Nick Lewycky49f89192009-04-04 07:22:01 +00006443
6444//===----------------------------------------------------------------------===//
6445// Embedded metadata.
6446//===----------------------------------------------------------------------===//
6447
6448/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006449/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006450/// Element
6451/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006452bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006453 if (ParseToken(lltok::lbrace, "expected '{' here"))
6454 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006455
Dan Gohman1e0213a2010-07-13 19:33:27 +00006456 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006457 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006458 return false;
6459
Nick Lewycky49f89192009-04-04 07:22:01 +00006460 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006461 // Null is a special case since it is typeless.
6462 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006463 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006464 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006465 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006466
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006467 Metadata *MD;
6468 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006469 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006470 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006471 } while (EatIfPresent(lltok::comma));
6472
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006473 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006474}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006475
6476//===----------------------------------------------------------------------===//
6477// Use-list order directives.
6478//===----------------------------------------------------------------------===//
6479bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6480 SMLoc Loc) {
6481 if (V->use_empty())
6482 return Error(Loc, "value has no uses");
6483
6484 unsigned NumUses = 0;
6485 SmallDenseMap<const Use *, unsigned, 16> Order;
6486 for (const Use &U : V->uses()) {
6487 if (++NumUses > Indexes.size())
6488 break;
6489 Order[&U] = Indexes[NumUses - 1];
6490 }
6491 if (NumUses < 2)
6492 return Error(Loc, "value only has one use");
6493 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6494 return Error(Loc, "wrong number of indexes, expected " +
6495 Twine(std::distance(V->use_begin(), V->use_end())));
6496
6497 V->sortUseList([&](const Use &L, const Use &R) {
6498 return Order.lookup(&L) < Order.lookup(&R);
6499 });
6500 return false;
6501}
6502
6503/// ParseUseListOrderIndexes
6504/// ::= '{' uint32 (',' uint32)+ '}'
6505bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6506 SMLoc Loc = Lex.getLoc();
6507 if (ParseToken(lltok::lbrace, "expected '{' here"))
6508 return true;
6509 if (Lex.getKind() == lltok::rbrace)
6510 return Lex.Error("expected non-empty list of uselistorder indexes");
6511
6512 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6513 // indexes should be distinct numbers in the range [0, size-1], and should
6514 // not be in order.
6515 unsigned Offset = 0;
6516 unsigned Max = 0;
6517 bool IsOrdered = true;
6518 assert(Indexes.empty() && "Expected empty order vector");
6519 do {
6520 unsigned Index;
6521 if (ParseUInt32(Index))
6522 return true;
6523
6524 // Update consistency checks.
6525 Offset += Index - Indexes.size();
6526 Max = std::max(Max, Index);
6527 IsOrdered &= Index == Indexes.size();
6528
6529 Indexes.push_back(Index);
6530 } while (EatIfPresent(lltok::comma));
6531
6532 if (ParseToken(lltok::rbrace, "expected '}' here"))
6533 return true;
6534
6535 if (Indexes.size() < 2)
6536 return Error(Loc, "expected >= 2 uselistorder indexes");
6537 if (Offset != 0 || Max >= Indexes.size())
6538 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6539 if (IsOrdered)
6540 return Error(Loc, "expected uselistorder indexes to change the order");
6541
6542 return false;
6543}
6544
6545/// ParseUseListOrder
6546/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6547bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6548 SMLoc Loc = Lex.getLoc();
6549 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6550 return true;
6551
6552 Value *V;
6553 SmallVector<unsigned, 16> Indexes;
6554 if (ParseTypeAndValue(V, PFS) ||
6555 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6556 ParseUseListOrderIndexes(Indexes))
6557 return true;
6558
6559 return sortUseListOrder(V, Indexes, Loc);
6560}
6561
6562/// ParseUseListOrderBB
6563/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6564bool LLParser::ParseUseListOrderBB() {
6565 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6566 SMLoc Loc = Lex.getLoc();
6567 Lex.Lex();
6568
6569 ValID Fn, Label;
6570 SmallVector<unsigned, 16> Indexes;
6571 if (ParseValID(Fn) ||
6572 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6573 ParseValID(Label) ||
6574 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6575 ParseUseListOrderIndexes(Indexes))
6576 return true;
6577
6578 // Check the function.
6579 GlobalValue *GV;
6580 if (Fn.Kind == ValID::t_GlobalName)
6581 GV = M->getNamedValue(Fn.StrVal);
6582 else if (Fn.Kind == ValID::t_GlobalID)
6583 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6584 else
6585 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6586 if (!GV)
6587 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6588 auto *F = dyn_cast<Function>(GV);
6589 if (!F)
6590 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6591 if (F->isDeclaration())
6592 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6593
6594 // Check the basic block.
6595 if (Label.Kind == ValID::t_LocalID)
6596 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6597 if (Label.Kind != ValID::t_LocalName)
6598 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006599 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006600 if (!V)
6601 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6602 if (!isa<BasicBlock>(V))
6603 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6604
6605 return sortUseListOrder(V, Indexes, Loc);
6606}