Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/AsmParser/LLParser.cpp
Warning:line 3282, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LLParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/AsmParser/LLParser.cpp
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/AsmParser/LLParser.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/AsmParser/LLToken.h"
20#include "llvm/AsmParser/SlotMapping.h"
21#include "llvm/BinaryFormat/Dwarf.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
27#include "llvm/IR/ConstantRange.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DebugInfoMetadata.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalIFunc.h"
33#include "llvm/IR/GlobalObject.h"
34#include "llvm/IR/InlineAsm.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
40#include "llvm/IR/Value.h"
41#include "llvm/IR/ValueSymbolTable.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/SaveAndRestore.h"
46#include "llvm/Support/raw_ostream.h"
47#include <algorithm>
48#include <cassert>
49#include <cstring>
50#include <iterator>
51#include <vector>
52
53using namespace llvm;
54
55static std::string getTypeString(Type *T) {
56 std::string Result;
57 raw_string_ostream Tmp(Result);
58 Tmp << *T;
59 return Tmp.str();
60}
61
62/// Run: module ::= toplevelentity*
63bool LLParser::Run(bool UpgradeDebugInfo,
64 DataLayoutCallbackTy DataLayoutCallback) {
65 // Prime the lexer.
66 Lex.Lex();
67
68 if (Context.shouldDiscardValueNames())
69 return error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
72
73 if (M) {
74 if (parseTargetDefinitions())
75 return true;
76
77 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
78 M->setDataLayout(*LayoutOverride);
79 }
80
81 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
82 validateEndOfIndex();
83}
84
85bool LLParser::parseStandaloneConstantValue(Constant *&C,
86 const SlotMapping *Slots) {
87 restoreParsingState(Slots);
88 Lex.Lex();
89
90 Type *Ty = nullptr;
91 if (parseType(Ty) || parseConstantValue(Ty, C))
92 return true;
93 if (Lex.getKind() != lltok::Eof)
94 return error(Lex.getLoc(), "expected end of string");
95 return false;
96}
97
98bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
99 const SlotMapping *Slots) {
100 restoreParsingState(Slots);
101 Lex.Lex();
102
103 Read = 0;
104 SMLoc Start = Lex.getLoc();
105 Ty = nullptr;
106 if (parseType(Ty))
107 return true;
108 SMLoc End = Lex.getLoc();
109 Read = End.getPointer() - Start.getPointer();
110
111 return false;
112}
113
114void LLParser::restoreParsingState(const SlotMapping *Slots) {
115 if (!Slots)
116 return;
117 NumberedVals = Slots->GlobalValues;
118 NumberedMetadata = Slots->MetadataNodes;
119 for (const auto &I : Slots->NamedTypes)
120 NamedTypes.insert(
121 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
122 for (const auto &I : Slots->Types)
123 NumberedTypes.insert(
124 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
125}
126
127/// validateEndOfModule - Do final validity and sanity checks at the end of the
128/// module.
129bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
130 if (!M)
131 return false;
132 // Handle any function attribute group forward references.
133 for (const auto &RAG : ForwardRefAttrGroups) {
134 Value *V = RAG.first;
135 const std::vector<unsigned> &Attrs = RAG.second;
136 AttrBuilder B;
137
138 for (const auto &Attr : Attrs)
139 B.merge(NumberedAttrBuilders[Attr]);
140
141 if (Function *Fn = dyn_cast<Function>(V)) {
142 AttributeList AS = Fn->getAttributes();
143 AttrBuilder FnAttrs(AS.getFnAttributes());
144 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
145
146 FnAttrs.merge(B);
147
148 // If the alignment was parsed as an attribute, move to the alignment
149 // field.
150 if (FnAttrs.hasAlignmentAttr()) {
151 Fn->setAlignment(FnAttrs.getAlignment());
152 FnAttrs.removeAttribute(Attribute::Alignment);
153 }
154
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 Fn->setAttributes(AS);
158 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
159 AttributeList AS = CI->getAttributes();
160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 FnAttrs.merge(B);
163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
165 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeList AS = II->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
170 FnAttrs.merge(B);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 II->setAttributes(AS);
174 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
175 AttributeList AS = CBI->getAttributes();
176 AttrBuilder FnAttrs(AS.getFnAttributes());
177 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
178 FnAttrs.merge(B);
179 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
180 AttributeSet::get(Context, FnAttrs));
181 CBI->setAttributes(AS);
182 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
183 AttrBuilder Attrs(GV->getAttributes());
184 Attrs.merge(B);
185 GV->setAttributes(AttributeSet::get(Context,Attrs));
186 } else {
187 llvm_unreachable("invalid object with forward attribute group reference")__builtin_unreachable();
188 }
189 }
190
191 // If there are entries in ForwardRefBlockAddresses at this point, the
192 // function was never defined.
193 if (!ForwardRefBlockAddresses.empty())
194 return error(ForwardRefBlockAddresses.begin()->first.Loc,
195 "expected function name in blockaddress");
196
197 for (const auto &NT : NumberedTypes)
198 if (NT.second.second.isValid())
199 return error(NT.second.second,
200 "use of undefined type '%" + Twine(NT.first) + "'");
201
202 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
203 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
204 if (I->second.second.isValid())
205 return error(I->second.second,
206 "use of undefined type named '" + I->getKey() + "'");
207
208 if (!ForwardRefComdats.empty())
209 return error(ForwardRefComdats.begin()->second,
210 "use of undefined comdat '$" +
211 ForwardRefComdats.begin()->first + "'");
212
213 if (!ForwardRefVals.empty())
214 return error(ForwardRefVals.begin()->second.second,
215 "use of undefined value '@" + ForwardRefVals.begin()->first +
216 "'");
217
218 if (!ForwardRefValIDs.empty())
219 return error(ForwardRefValIDs.begin()->second.second,
220 "use of undefined value '@" +
221 Twine(ForwardRefValIDs.begin()->first) + "'");
222
223 if (!ForwardRefMDNodes.empty())
224 return error(ForwardRefMDNodes.begin()->second.second,
225 "use of undefined metadata '!" +
226 Twine(ForwardRefMDNodes.begin()->first) + "'");
227
228 // Resolve metadata cycles.
229 for (auto &N : NumberedMetadata) {
230 if (N.second && !N.second->isResolved())
231 N.second->resolveCycles();
232 }
233
234 for (auto *Inst : InstsWithTBAATag) {
235 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
236 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag")((void)0);
237 auto *UpgradedMD = UpgradeTBAANode(*MD);
238 if (MD != UpgradedMD)
239 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
240 }
241
242 // Look for intrinsic functions and CallInst that need to be upgraded
243 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
244 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
245
246 // Some types could be renamed during loading if several modules are
247 // loaded in the same LLVMContext (LTO scenario). In this case we should
248 // remangle intrinsics names as well.
249 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
250 Function *F = &*FI++;
251 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
252 F->replaceAllUsesWith(Remangled.getValue());
253 F->eraseFromParent();
254 }
255 }
256
257 if (UpgradeDebugInfo)
258 llvm::UpgradeDebugInfo(*M);
259
260 UpgradeModuleFlags(*M);
261 UpgradeSectionAttributes(*M);
262
263 if (!Slots)
264 return false;
265 // Initialize the slot mapping.
266 // Because by this point we've parsed and validated everything, we can "steal"
267 // the mapping from LLParser as it doesn't need it anymore.
268 Slots->GlobalValues = std::move(NumberedVals);
269 Slots->MetadataNodes = std::move(NumberedMetadata);
270 for (const auto &I : NamedTypes)
271 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
272 for (const auto &I : NumberedTypes)
273 Slots->Types.insert(std::make_pair(I.first, I.second.first));
274
275 return false;
276}
277
278/// Do final validity and sanity checks at the end of the index.
279bool LLParser::validateEndOfIndex() {
280 if (!Index)
281 return false;
282
283 if (!ForwardRefValueInfos.empty())
284 return error(ForwardRefValueInfos.begin()->second.front().second,
285 "use of undefined summary '^" +
286 Twine(ForwardRefValueInfos.begin()->first) + "'");
287
288 if (!ForwardRefAliasees.empty())
289 return error(ForwardRefAliasees.begin()->second.front().second,
290 "use of undefined summary '^" +
291 Twine(ForwardRefAliasees.begin()->first) + "'");
292
293 if (!ForwardRefTypeIds.empty())
294 return error(ForwardRefTypeIds.begin()->second.front().second,
295 "use of undefined type id summary '^" +
296 Twine(ForwardRefTypeIds.begin()->first) + "'");
297
298 return false;
299}
300
301//===----------------------------------------------------------------------===//
302// Top-Level Entities
303//===----------------------------------------------------------------------===//
304
305bool LLParser::parseTargetDefinitions() {
306 while (true) {
307 switch (Lex.getKind()) {
308 case lltok::kw_target:
309 if (parseTargetDefinition())
310 return true;
311 break;
312 case lltok::kw_source_filename:
313 if (parseSourceFileName())
314 return true;
315 break;
316 default:
317 return false;
318 }
319 }
320}
321
322bool LLParser::parseTopLevelEntities() {
323 // If there is no Module, then parse just the summary index entries.
324 if (!M) {
325 while (true) {
326 switch (Lex.getKind()) {
327 case lltok::Eof:
328 return false;
329 case lltok::SummaryID:
330 if (parseSummaryEntry())
331 return true;
332 break;
333 case lltok::kw_source_filename:
334 if (parseSourceFileName())
335 return true;
336 break;
337 default:
338 // Skip everything else
339 Lex.Lex();
340 }
341 }
342 }
343 while (true) {
344 switch (Lex.getKind()) {
345 default:
346 return tokError("expected top-level entity");
347 case lltok::Eof: return false;
348 case lltok::kw_declare:
349 if (parseDeclare())
350 return true;
351 break;
352 case lltok::kw_define:
353 if (parseDefine())
354 return true;
355 break;
356 case lltok::kw_module:
357 if (parseModuleAsm())
358 return true;
359 break;
360 case lltok::LocalVarID:
361 if (parseUnnamedType())
362 return true;
363 break;
364 case lltok::LocalVar:
365 if (parseNamedType())
366 return true;
367 break;
368 case lltok::GlobalID:
369 if (parseUnnamedGlobal())
370 return true;
371 break;
372 case lltok::GlobalVar:
373 if (parseNamedGlobal())
374 return true;
375 break;
376 case lltok::ComdatVar: if (parseComdat()) return true; break;
377 case lltok::exclaim:
378 if (parseStandaloneMetadata())
379 return true;
380 break;
381 case lltok::SummaryID:
382 if (parseSummaryEntry())
383 return true;
384 break;
385 case lltok::MetadataVar:
386 if (parseNamedMetadata())
387 return true;
388 break;
389 case lltok::kw_attributes:
390 if (parseUnnamedAttrGrp())
391 return true;
392 break;
393 case lltok::kw_uselistorder:
394 if (parseUseListOrder())
395 return true;
396 break;
397 case lltok::kw_uselistorder_bb:
398 if (parseUseListOrderBB())
399 return true;
400 break;
401 }
402 }
403}
404
405/// toplevelentity
406/// ::= 'module' 'asm' STRINGCONSTANT
407bool LLParser::parseModuleAsm() {
408 assert(Lex.getKind() == lltok::kw_module)((void)0);
409 Lex.Lex();
410
411 std::string AsmStr;
412 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
413 parseStringConstant(AsmStr))
414 return true;
415
416 M->appendModuleInlineAsm(AsmStr);
417 return false;
418}
419
420/// toplevelentity
421/// ::= 'target' 'triple' '=' STRINGCONSTANT
422/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
423bool LLParser::parseTargetDefinition() {
424 assert(Lex.getKind() == lltok::kw_target)((void)0);
425 std::string Str;
426 switch (Lex.Lex()) {
427 default:
428 return tokError("unknown target property");
429 case lltok::kw_triple:
430 Lex.Lex();
431 if (parseToken(lltok::equal, "expected '=' after target triple") ||
432 parseStringConstant(Str))
433 return true;
434 M->setTargetTriple(Str);
435 return false;
436 case lltok::kw_datalayout:
437 Lex.Lex();
438 if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
439 parseStringConstant(Str))
440 return true;
441 M->setDataLayout(Str);
442 return false;
443 }
444}
445
446/// toplevelentity
447/// ::= 'source_filename' '=' STRINGCONSTANT
448bool LLParser::parseSourceFileName() {
449 assert(Lex.getKind() == lltok::kw_source_filename)((void)0);
450 Lex.Lex();
451 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
452 parseStringConstant(SourceFileName))
453 return true;
454 if (M)
455 M->setSourceFileName(SourceFileName);
456 return false;
457}
458
459/// parseUnnamedType:
460/// ::= LocalVarID '=' 'type' type
461bool LLParser::parseUnnamedType() {
462 LocTy TypeLoc = Lex.getLoc();
463 unsigned TypeID = Lex.getUIntVal();
464 Lex.Lex(); // eat LocalVarID;
465
466 if (parseToken(lltok::equal, "expected '=' after name") ||
467 parseToken(lltok::kw_type, "expected 'type' after '='"))
468 return true;
469
470 Type *Result = nullptr;
471 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
472 return true;
473
474 if (!isa<StructType>(Result)) {
475 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
476 if (Entry.first)
477 return error(TypeLoc, "non-struct types may not be recursive");
478 Entry.first = Result;
479 Entry.second = SMLoc();
480 }
481
482 return false;
483}
484
485/// toplevelentity
486/// ::= LocalVar '=' 'type' type
487bool LLParser::parseNamedType() {
488 std::string Name = Lex.getStrVal();
489 LocTy NameLoc = Lex.getLoc();
490 Lex.Lex(); // eat LocalVar.
491
492 if (parseToken(lltok::equal, "expected '=' after name") ||
493 parseToken(lltok::kw_type, "expected 'type' after name"))
494 return true;
495
496 Type *Result = nullptr;
497 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
498 return true;
499
500 if (!isa<StructType>(Result)) {
501 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
502 if (Entry.first)
503 return error(NameLoc, "non-struct types may not be recursive");
504 Entry.first = Result;
505 Entry.second = SMLoc();
506 }
507
508 return false;
509}
510
511/// toplevelentity
512/// ::= 'declare' FunctionHeader
513bool LLParser::parseDeclare() {
514 assert(Lex.getKind() == lltok::kw_declare)((void)0);
515 Lex.Lex();
516
517 std::vector<std::pair<unsigned, MDNode *>> MDs;
518 while (Lex.getKind() == lltok::MetadataVar) {
519 unsigned MDK;
520 MDNode *N;
521 if (parseMetadataAttachment(MDK, N))
522 return true;
523 MDs.push_back({MDK, N});
524 }
525
526 Function *F;
527 if (parseFunctionHeader(F, false))
528 return true;
529 for (auto &MD : MDs)
530 F->addMetadata(MD.first, *MD.second);
531 return false;
532}
533
534/// toplevelentity
535/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
536bool LLParser::parseDefine() {
537 assert(Lex.getKind() == lltok::kw_define)((void)0);
538 Lex.Lex();
539
540 Function *F;
541 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
542 parseFunctionBody(*F);
543}
544
545/// parseGlobalType
546/// ::= 'constant'
547/// ::= 'global'
548bool LLParser::parseGlobalType(bool &IsConstant) {
549 if (Lex.getKind() == lltok::kw_constant)
550 IsConstant = true;
551 else if (Lex.getKind() == lltok::kw_global)
552 IsConstant = false;
553 else {
554 IsConstant = false;
555 return tokError("expected 'global' or 'constant'");
556 }
557 Lex.Lex();
558 return false;
559}
560
561bool LLParser::parseOptionalUnnamedAddr(
562 GlobalVariable::UnnamedAddr &UnnamedAddr) {
563 if (EatIfPresent(lltok::kw_unnamed_addr))
564 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
565 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
566 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
567 else
568 UnnamedAddr = GlobalValue::UnnamedAddr::None;
569 return false;
570}
571
572/// parseUnnamedGlobal:
573/// OptionalVisibility (ALIAS | IFUNC) ...
574/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
575/// OptionalDLLStorageClass
576/// ... -> global variable
577/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
578/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
579/// OptionalVisibility
580/// OptionalDLLStorageClass
581/// ... -> global variable
582bool LLParser::parseUnnamedGlobal() {
583 unsigned VarID = NumberedVals.size();
584 std::string Name;
585 LocTy NameLoc = Lex.getLoc();
586
587 // Handle the GlobalID form.
588 if (Lex.getKind() == lltok::GlobalID) {
589 if (Lex.getUIntVal() != VarID)
590 return error(Lex.getLoc(),
591 "variable expected to be numbered '%" + Twine(VarID) + "'");
592 Lex.Lex(); // eat GlobalID;
593
594 if (parseToken(lltok::equal, "expected '=' after name"))
595 return true;
596 }
597
598 bool HasLinkage;
599 unsigned Linkage, Visibility, DLLStorageClass;
600 bool DSOLocal;
601 GlobalVariable::ThreadLocalMode TLM;
602 GlobalVariable::UnnamedAddr UnnamedAddr;
603 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
604 DSOLocal) ||
605 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
606 return true;
607
608 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
609 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
610 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
611
612 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
613 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
614}
615
616/// parseNamedGlobal:
617/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
618/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
619/// OptionalVisibility OptionalDLLStorageClass
620/// ... -> global variable
621bool LLParser::parseNamedGlobal() {
622 assert(Lex.getKind() == lltok::GlobalVar)((void)0);
623 LocTy NameLoc = Lex.getLoc();
624 std::string Name = Lex.getStrVal();
625 Lex.Lex();
626
627 bool HasLinkage;
628 unsigned Linkage, Visibility, DLLStorageClass;
629 bool DSOLocal;
630 GlobalVariable::ThreadLocalMode TLM;
631 GlobalVariable::UnnamedAddr UnnamedAddr;
632 if (parseToken(lltok::equal, "expected '=' in global variable") ||
633 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
634 DSOLocal) ||
635 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
636 return true;
637
638 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
639 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
640 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
641
642 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
643 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
644}
645
646bool LLParser::parseComdat() {
647 assert(Lex.getKind() == lltok::ComdatVar)((void)0);
648 std::string Name = Lex.getStrVal();
649 LocTy NameLoc = Lex.getLoc();
650 Lex.Lex();
651
652 if (parseToken(lltok::equal, "expected '=' here"))
653 return true;
654
655 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
656 return tokError("expected comdat type");
657
658 Comdat::SelectionKind SK;
659 switch (Lex.getKind()) {
660 default:
661 return tokError("unknown selection kind");
662 case lltok::kw_any:
663 SK = Comdat::Any;
664 break;
665 case lltok::kw_exactmatch:
666 SK = Comdat::ExactMatch;
667 break;
668 case lltok::kw_largest:
669 SK = Comdat::Largest;
670 break;
671 case lltok::kw_nodeduplicate:
672 SK = Comdat::NoDeduplicate;
673 break;
674 case lltok::kw_samesize:
675 SK = Comdat::SameSize;
676 break;
677 }
678 Lex.Lex();
679
680 // See if the comdat was forward referenced, if so, use the comdat.
681 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
682 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
683 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
684 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
685
686 Comdat *C;
687 if (I != ComdatSymTab.end())
688 C = &I->second;
689 else
690 C = M->getOrInsertComdat(Name);
691 C->setSelectionKind(SK);
692
693 return false;
694}
695
696// MDString:
697// ::= '!' STRINGCONSTANT
698bool LLParser::parseMDString(MDString *&Result) {
699 std::string Str;
700 if (parseStringConstant(Str))
701 return true;
702 Result = MDString::get(Context, Str);
703 return false;
704}
705
706// MDNode:
707// ::= '!' MDNodeNumber
708bool LLParser::parseMDNodeID(MDNode *&Result) {
709 // !{ ..., !42, ... }
710 LocTy IDLoc = Lex.getLoc();
711 unsigned MID = 0;
712 if (parseUInt32(MID))
713 return true;
714
715 // If not a forward reference, just return it now.
716 if (NumberedMetadata.count(MID)) {
717 Result = NumberedMetadata[MID];
718 return false;
719 }
720
721 // Otherwise, create MDNode forward reference.
722 auto &FwdRef = ForwardRefMDNodes[MID];
723 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
724
725 Result = FwdRef.first.get();
726 NumberedMetadata[MID].reset(Result);
727 return false;
728}
729
730/// parseNamedMetadata:
731/// !foo = !{ !1, !2 }
732bool LLParser::parseNamedMetadata() {
733 assert(Lex.getKind() == lltok::MetadataVar)((void)0);
734 std::string Name = Lex.getStrVal();
735 Lex.Lex();
736
737 if (parseToken(lltok::equal, "expected '=' here") ||
738 parseToken(lltok::exclaim, "Expected '!' here") ||
739 parseToken(lltok::lbrace, "Expected '{' here"))
740 return true;
741
742 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
743 if (Lex.getKind() != lltok::rbrace)
744 do {
745 MDNode *N = nullptr;
746 // parse DIExpressions inline as a special case. They are still MDNodes,
747 // so they can still appear in named metadata. Remove this logic if they
748 // become plain Metadata.
749 if (Lex.getKind() == lltok::MetadataVar &&
750 Lex.getStrVal() == "DIExpression") {
751 if (parseDIExpression(N, /*IsDistinct=*/false))
752 return true;
753 // DIArgLists should only appear inline in a function, as they may
754 // contain LocalAsMetadata arguments which require a function context.
755 } else if (Lex.getKind() == lltok::MetadataVar &&
756 Lex.getStrVal() == "DIArgList") {
757 return tokError("found DIArgList outside of function");
758 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
759 parseMDNodeID(N)) {
760 return true;
761 }
762 NMD->addOperand(N);
763 } while (EatIfPresent(lltok::comma));
764
765 return parseToken(lltok::rbrace, "expected end of metadata node");
766}
767
768/// parseStandaloneMetadata:
769/// !42 = !{...}
770bool LLParser::parseStandaloneMetadata() {
771 assert(Lex.getKind() == lltok::exclaim)((void)0);
772 Lex.Lex();
773 unsigned MetadataID = 0;
774
775 MDNode *Init;
776 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
777 return true;
778
779 // Detect common error, from old metadata syntax.
780 if (Lex.getKind() == lltok::Type)
781 return tokError("unexpected type in metadata definition");
782
783 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
784 if (Lex.getKind() == lltok::MetadataVar) {
785 if (parseSpecializedMDNode(Init, IsDistinct))
786 return true;
787 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
788 parseMDTuple(Init, IsDistinct))
789 return true;
790
791 // See if this was forward referenced, if so, handle it.
792 auto FI = ForwardRefMDNodes.find(MetadataID);
793 if (FI != ForwardRefMDNodes.end()) {
794 FI->second.first->replaceAllUsesWith(Init);
795 ForwardRefMDNodes.erase(FI);
796
797 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work")((void)0);
798 } else {
799 if (NumberedMetadata.count(MetadataID))
800 return tokError("Metadata id is already used");
801 NumberedMetadata[MetadataID].reset(Init);
802 }
803
804 return false;
805}
806
807// Skips a single module summary entry.
808bool LLParser::skipModuleSummaryEntry() {
809 // Each module summary entry consists of a tag for the entry
810 // type, followed by a colon, then the fields which may be surrounded by
811 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
812 // support is in place we will look for the tokens corresponding to the
813 // expected tags.
814 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
815 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
816 Lex.getKind() != lltok::kw_blockcount)
817 return tokError(
818 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
819 "start of summary entry");
820 if (Lex.getKind() == lltok::kw_flags)
821 return parseSummaryIndexFlags();
822 if (Lex.getKind() == lltok::kw_blockcount)
823 return parseBlockCount();
824 Lex.Lex();
825 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
826 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
827 return true;
828 // Now walk through the parenthesized entry, until the number of open
829 // parentheses goes back down to 0 (the first '(' was parsed above).
830 unsigned NumOpenParen = 1;
831 do {
832 switch (Lex.getKind()) {
833 case lltok::lparen:
834 NumOpenParen++;
835 break;
836 case lltok::rparen:
837 NumOpenParen--;
838 break;
839 case lltok::Eof:
840 return tokError("found end of file while parsing summary entry");
841 default:
842 // Skip everything in between parentheses.
843 break;
844 }
845 Lex.Lex();
846 } while (NumOpenParen > 0);
847 return false;
848}
849
850/// SummaryEntry
851/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
852bool LLParser::parseSummaryEntry() {
853 assert(Lex.getKind() == lltok::SummaryID)((void)0);
854 unsigned SummaryID = Lex.getUIntVal();
855
856 // For summary entries, colons should be treated as distinct tokens,
857 // not an indication of the end of a label token.
858 Lex.setIgnoreColonInIdentifiers(true);
859
860 Lex.Lex();
861 if (parseToken(lltok::equal, "expected '=' here"))
862 return true;
863
864 // If we don't have an index object, skip the summary entry.
865 if (!Index)
866 return skipModuleSummaryEntry();
867
868 bool result = false;
869 switch (Lex.getKind()) {
870 case lltok::kw_gv:
871 result = parseGVEntry(SummaryID);
872 break;
873 case lltok::kw_module:
874 result = parseModuleEntry(SummaryID);
875 break;
876 case lltok::kw_typeid:
877 result = parseTypeIdEntry(SummaryID);
878 break;
879 case lltok::kw_typeidCompatibleVTable:
880 result = parseTypeIdCompatibleVtableEntry(SummaryID);
881 break;
882 case lltok::kw_flags:
883 result = parseSummaryIndexFlags();
884 break;
885 case lltok::kw_blockcount:
886 result = parseBlockCount();
887 break;
888 default:
889 result = error(Lex.getLoc(), "unexpected summary kind");
890 break;
891 }
892 Lex.setIgnoreColonInIdentifiers(false);
893 return result;
894}
895
896static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
897 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
898 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
899}
900
901// If there was an explicit dso_local, update GV. In the absence of an explicit
902// dso_local we keep the default value.
903static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
904 if (DSOLocal)
905 GV.setDSOLocal(true);
906}
907
908static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
909 Type *Ty2) {
910 std::string ErrString;
911 raw_string_ostream ErrOS(ErrString);
912 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
913 return ErrOS.str();
914}
915
916/// parseIndirectSymbol:
917/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
918/// OptionalVisibility OptionalDLLStorageClass
919/// OptionalThreadLocal OptionalUnnamedAddr
920/// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
921///
922/// IndirectSymbol
923/// ::= TypeAndValue
924///
925/// IndirectSymbolAttr
926/// ::= ',' 'partition' StringConstant
927///
928/// Everything through OptionalUnnamedAddr has already been parsed.
929///
930bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
931 unsigned L, unsigned Visibility,
932 unsigned DLLStorageClass, bool DSOLocal,
933 GlobalVariable::ThreadLocalMode TLM,
934 GlobalVariable::UnnamedAddr UnnamedAddr) {
935 bool IsAlias;
936 if (Lex.getKind() == lltok::kw_alias)
937 IsAlias = true;
938 else if (Lex.getKind() == lltok::kw_ifunc)
939 IsAlias = false;
940 else
941 llvm_unreachable("Not an alias or ifunc!")__builtin_unreachable();
942 Lex.Lex();
943
944 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
945
946 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
947 return error(NameLoc, "invalid linkage type for alias");
948
949 if (!isValidVisibilityForLinkage(Visibility, L))
950 return error(NameLoc,
951 "symbol with local linkage must have default visibility");
952
953 Type *Ty;
954 LocTy ExplicitTypeLoc = Lex.getLoc();
955 if (parseType(Ty) ||
956 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
957 return true;
958
959 Constant *Aliasee;
960 LocTy AliaseeLoc = Lex.getLoc();
961 if (Lex.getKind() != lltok::kw_bitcast &&
962 Lex.getKind() != lltok::kw_getelementptr &&
963 Lex.getKind() != lltok::kw_addrspacecast &&
964 Lex.getKind() != lltok::kw_inttoptr) {
965 if (parseGlobalTypeAndValue(Aliasee))
966 return true;
967 } else {
968 // The bitcast dest type is not present, it is implied by the dest type.
969 ValID ID;
970 if (parseValID(ID, /*PFS=*/nullptr))
971 return true;
972 if (ID.Kind != ValID::t_Constant)
973 return error(AliaseeLoc, "invalid aliasee");
974 Aliasee = ID.ConstantVal;
975 }
976
977 Type *AliaseeType = Aliasee->getType();
978 auto *PTy = dyn_cast<PointerType>(AliaseeType);
979 if (!PTy)
980 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
981 unsigned AddrSpace = PTy->getAddressSpace();
982
983 if (IsAlias && !PTy->isOpaqueOrPointeeTypeMatches(Ty)) {
984 return error(
985 ExplicitTypeLoc,
986 typeComparisonErrorMessage(
987 "explicit pointee type doesn't match operand's pointee type", Ty,
988 PTy->getElementType()));
989 }
990
991 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
992 return error(ExplicitTypeLoc,
993 "explicit pointee type should be a function type");
994 }
995
996 GlobalValue *GVal = nullptr;
997
998 // See if the alias was forward referenced, if so, prepare to replace the
999 // forward reference.
1000 if (!Name.empty()) {
1001 auto I = ForwardRefVals.find(Name);
1002 if (I != ForwardRefVals.end()) {
1003 GVal = I->second.first;
1004 ForwardRefVals.erase(Name);
1005 } else if (M->getNamedValue(Name)) {
1006 return error(NameLoc, "redefinition of global '@" + Name + "'");
1007 }
1008 } else {
1009 auto I = ForwardRefValIDs.find(NumberedVals.size());
1010 if (I != ForwardRefValIDs.end()) {
1011 GVal = I->second.first;
1012 ForwardRefValIDs.erase(I);
1013 }
1014 }
1015
1016 // Okay, create the alias but do not insert it into the module yet.
1017 std::unique_ptr<GlobalIndirectSymbol> GA;
1018 if (IsAlias)
1019 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1020 (GlobalValue::LinkageTypes)Linkage, Name,
1021 Aliasee, /*Parent*/ nullptr));
1022 else
1023 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1024 (GlobalValue::LinkageTypes)Linkage, Name,
1025 Aliasee, /*Parent*/ nullptr));
1026 GA->setThreadLocalMode(TLM);
1027 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1028 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1029 GA->setUnnamedAddr(UnnamedAddr);
1030 maybeSetDSOLocal(DSOLocal, *GA);
1031
1032 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1033 // Now parse them if there are any.
1034 while (Lex.getKind() == lltok::comma) {
1035 Lex.Lex();
1036
1037 if (Lex.getKind() == lltok::kw_partition) {
1038 Lex.Lex();
1039 GA->setPartition(Lex.getStrVal());
1040 if (parseToken(lltok::StringConstant, "expected partition string"))
1041 return true;
1042 } else {
1043 return tokError("unknown alias or ifunc property!");
1044 }
1045 }
1046
1047 if (Name.empty())
1048 NumberedVals.push_back(GA.get());
1049
1050 if (GVal) {
1051 // Verify that types agree.
1052 if (GVal->getType() != GA->getType())
1053 return error(
1054 ExplicitTypeLoc,
1055 "forward reference and definition of alias have different types");
1056
1057 // If they agree, just RAUW the old value with the alias and remove the
1058 // forward ref info.
1059 GVal->replaceAllUsesWith(GA.get());
1060 GVal->eraseFromParent();
1061 }
1062
1063 // Insert into the module, we know its name won't collide now.
1064 if (IsAlias)
1065 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1066 else
1067 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1068 assert(GA->getName() == Name && "Should not be a name conflict!")((void)0);
1069
1070 // The module owns this now
1071 GA.release();
1072
1073 return false;
1074}
1075
1076/// parseGlobal
1077/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1078/// OptionalVisibility OptionalDLLStorageClass
1079/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1080/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1081/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1082/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1083/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1084/// Const OptionalAttrs
1085///
1086/// Everything up to and including OptionalUnnamedAddr has been parsed
1087/// already.
1088///
1089bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1090 unsigned Linkage, bool HasLinkage,
1091 unsigned Visibility, unsigned DLLStorageClass,
1092 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1093 GlobalVariable::UnnamedAddr UnnamedAddr) {
1094 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1095 return error(NameLoc,
1096 "symbol with local linkage must have default visibility");
1097
1098 unsigned AddrSpace;
1099 bool IsConstant, IsExternallyInitialized;
1100 LocTy IsExternallyInitializedLoc;
1101 LocTy TyLoc;
1102
1103 Type *Ty = nullptr;
1104 if (parseOptionalAddrSpace(AddrSpace) ||
1105 parseOptionalToken(lltok::kw_externally_initialized,
1106 IsExternallyInitialized,
1107 &IsExternallyInitializedLoc) ||
1108 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1109 return true;
1110
1111 // If the linkage is specified and is external, then no initializer is
1112 // present.
1113 Constant *Init = nullptr;
1114 if (!HasLinkage ||
1115 !GlobalValue::isValidDeclarationLinkage(
1116 (GlobalValue::LinkageTypes)Linkage)) {
1117 if (parseGlobalValue(Ty, Init))
1118 return true;
1119 }
1120
1121 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1122 return error(TyLoc, "invalid type for global variable");
1123
1124 GlobalValue *GVal = nullptr;
1125
1126 // See if the global was forward referenced, if so, use the global.
1127 if (!Name.empty()) {
1128 auto I = ForwardRefVals.find(Name);
1129 if (I != ForwardRefVals.end()) {
1130 GVal = I->second.first;
1131 ForwardRefVals.erase(I);
1132 } else if (M->getNamedValue(Name)) {
1133 return error(NameLoc, "redefinition of global '@" + Name + "'");
1134 }
1135 } else {
1136 auto I = ForwardRefValIDs.find(NumberedVals.size());
1137 if (I != ForwardRefValIDs.end()) {
1138 GVal = I->second.first;
1139 ForwardRefValIDs.erase(I);
1140 }
1141 }
1142
1143 GlobalVariable *GV = new GlobalVariable(
1144 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1145 GlobalVariable::NotThreadLocal, AddrSpace);
1146
1147 if (Name.empty())
1148 NumberedVals.push_back(GV);
1149
1150 // Set the parsed properties on the global.
1151 if (Init)
1152 GV->setInitializer(Init);
1153 GV->setConstant(IsConstant);
1154 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1155 maybeSetDSOLocal(DSOLocal, *GV);
1156 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1157 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1158 GV->setExternallyInitialized(IsExternallyInitialized);
1159 GV->setThreadLocalMode(TLM);
1160 GV->setUnnamedAddr(UnnamedAddr);
1161
1162 if (GVal) {
1163 if (!GVal->getType()->isOpaque() && GVal->getValueType() != Ty)
1164 return error(
1165 TyLoc,
1166 "forward reference and definition of global have different types");
1167
1168 GVal->replaceAllUsesWith(GV);
1169 GVal->eraseFromParent();
1170 }
1171
1172 // parse attributes on the global.
1173 while (Lex.getKind() == lltok::comma) {
1174 Lex.Lex();
1175
1176 if (Lex.getKind() == lltok::kw_section) {
1177 Lex.Lex();
1178 GV->setSection(Lex.getStrVal());
1179 if (parseToken(lltok::StringConstant, "expected global section string"))
1180 return true;
1181 } else if (Lex.getKind() == lltok::kw_partition) {
1182 Lex.Lex();
1183 GV->setPartition(Lex.getStrVal());
1184 if (parseToken(lltok::StringConstant, "expected partition string"))
1185 return true;
1186 } else if (Lex.getKind() == lltok::kw_align) {
1187 MaybeAlign Alignment;
1188 if (parseOptionalAlignment(Alignment))
1189 return true;
1190 GV->setAlignment(Alignment);
1191 } else if (Lex.getKind() == lltok::MetadataVar) {
1192 if (parseGlobalObjectMetadataAttachment(*GV))
1193 return true;
1194 } else {
1195 Comdat *C;
1196 if (parseOptionalComdat(Name, C))
1197 return true;
1198 if (C)
1199 GV->setComdat(C);
1200 else
1201 return tokError("unknown global variable property!");
1202 }
1203 }
1204
1205 AttrBuilder Attrs;
1206 LocTy BuiltinLoc;
1207 std::vector<unsigned> FwdRefAttrGrps;
1208 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1209 return true;
1210 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1211 GV->setAttributes(AttributeSet::get(Context, Attrs));
1212 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1213 }
1214
1215 return false;
1216}
1217
1218/// parseUnnamedAttrGrp
1219/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1220bool LLParser::parseUnnamedAttrGrp() {
1221 assert(Lex.getKind() == lltok::kw_attributes)((void)0);
1222 LocTy AttrGrpLoc = Lex.getLoc();
1223 Lex.Lex();
1224
1225 if (Lex.getKind() != lltok::AttrGrpID)
1226 return tokError("expected attribute group id");
1227
1228 unsigned VarID = Lex.getUIntVal();
1229 std::vector<unsigned> unused;
1230 LocTy BuiltinLoc;
1231 Lex.Lex();
1232
1233 if (parseToken(lltok::equal, "expected '=' here") ||
1234 parseToken(lltok::lbrace, "expected '{' here") ||
1235 parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1236 BuiltinLoc) ||
1237 parseToken(lltok::rbrace, "expected end of attribute group"))
1238 return true;
1239
1240 if (!NumberedAttrBuilders[VarID].hasAttributes())
1241 return error(AttrGrpLoc, "attribute group has no attributes");
1242
1243 return false;
1244}
1245
1246static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1247 switch (Kind) {
1248#define GET_ATTR_NAMES
1249#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1250 case lltok::kw_##DISPLAY_NAME: \
1251 return Attribute::ENUM_NAME;
1252#include "llvm/IR/Attributes.inc"
1253 default:
1254 return Attribute::None;
1255 }
1256}
1257
1258bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1259 bool InAttrGroup) {
1260 if (Attribute::isTypeAttrKind(Attr))
1261 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1262
1263 switch (Attr) {
1264 case Attribute::Alignment: {
1265 MaybeAlign Alignment;
1266 if (InAttrGroup) {
1267 uint32_t Value = 0;
1268 Lex.Lex();
1269 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1270 return true;
1271 Alignment = Align(Value);
1272 } else {
1273 if (parseOptionalAlignment(Alignment, true))
1274 return true;
1275 }
1276 B.addAlignmentAttr(Alignment);
1277 return false;
1278 }
1279 case Attribute::StackAlignment: {
1280 unsigned Alignment;
1281 if (InAttrGroup) {
1282 Lex.Lex();
1283 if (parseToken(lltok::equal, "expected '=' here") ||
1284 parseUInt32(Alignment))
1285 return true;
1286 } else {
1287 if (parseOptionalStackAlignment(Alignment))
1288 return true;
1289 }
1290 B.addStackAlignmentAttr(Alignment);
1291 return false;
1292 }
1293 case Attribute::AllocSize: {
1294 unsigned ElemSizeArg;
1295 Optional<unsigned> NumElemsArg;
1296 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1297 return true;
1298 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1299 return false;
1300 }
1301 case Attribute::VScaleRange: {
1302 unsigned MinValue, MaxValue;
1303 if (parseVScaleRangeArguments(MinValue, MaxValue))
1304 return true;
1305 B.addVScaleRangeAttr(MinValue, MaxValue);
1306 return false;
1307 }
1308 case Attribute::Dereferenceable: {
1309 uint64_t Bytes;
1310 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1311 return true;
1312 B.addDereferenceableAttr(Bytes);
1313 return false;
1314 }
1315 case Attribute::DereferenceableOrNull: {
1316 uint64_t Bytes;
1317 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1318 return true;
1319 B.addDereferenceableOrNullAttr(Bytes);
1320 return false;
1321 }
1322 default:
1323 B.addAttribute(Attr);
1324 Lex.Lex();
1325 return false;
1326 }
1327}
1328
1329/// parseFnAttributeValuePairs
1330/// ::= <attr> | <attr> '=' <value>
1331bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1332 std::vector<unsigned> &FwdRefAttrGrps,
1333 bool InAttrGrp, LocTy &BuiltinLoc) {
1334 bool HaveError = false;
1335
1336 B.clear();
1337
1338 while (true) {
1339 lltok::Kind Token = Lex.getKind();
1340 if (Token == lltok::rbrace)
1341 return HaveError; // Finished.
1342
1343 if (Token == lltok::StringConstant) {
1344 if (parseStringAttribute(B))
1345 return true;
1346 continue;
1347 }
1348
1349 if (Token == lltok::AttrGrpID) {
1350 // Allow a function to reference an attribute group:
1351 //
1352 // define void @foo() #1 { ... }
1353 if (InAttrGrp) {
1354 HaveError |= error(
1355 Lex.getLoc(),
1356 "cannot have an attribute group reference in an attribute group");
1357 } else {
1358 // Save the reference to the attribute group. We'll fill it in later.
1359 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1360 }
1361 Lex.Lex();
1362 continue;
1363 }
1364
1365 SMLoc Loc = Lex.getLoc();
1366 if (Token == lltok::kw_builtin)
1367 BuiltinLoc = Loc;
1368
1369 Attribute::AttrKind Attr = tokenToAttribute(Token);
1370 if (Attr == Attribute::None) {
1371 if (!InAttrGrp)
1372 return HaveError;
1373 return error(Lex.getLoc(), "unterminated attribute group");
1374 }
1375
1376 if (parseEnumAttribute(Attr, B, InAttrGrp))
1377 return true;
1378
1379 // As a hack, we allow function alignment to be initially parsed as an
1380 // attribute on a function declaration/definition or added to an attribute
1381 // group and later moved to the alignment field.
1382 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1383 HaveError |= error(Loc, "this attribute does not apply to functions");
1384 }
1385}
1386
1387//===----------------------------------------------------------------------===//
1388// GlobalValue Reference/Resolution Routines.
1389//===----------------------------------------------------------------------===//
1390
1391static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1392 // For opaque pointers, the used global type does not matter. We will later
1393 // RAUW it with a global/function of the correct type.
1394 if (PTy->isOpaque())
1395 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1396 GlobalValue::ExternalWeakLinkage, nullptr, "",
1397 nullptr, GlobalVariable::NotThreadLocal,
1398 PTy->getAddressSpace());
1399
1400 if (auto *FT = dyn_cast<FunctionType>(PTy->getPointerElementType()))
1401 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1402 PTy->getAddressSpace(), "", M);
1403 else
1404 return new GlobalVariable(*M, PTy->getPointerElementType(), false,
1405 GlobalValue::ExternalWeakLinkage, nullptr, "",
1406 nullptr, GlobalVariable::NotThreadLocal,
1407 PTy->getAddressSpace());
1408}
1409
1410Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1411 Value *Val, bool IsCall) {
1412 Type *ValTy = Val->getType();
1413 if (ValTy == Ty)
1414 return Val;
1415 // For calls, we also allow opaque pointers.
1416 if (IsCall && ValTy == PointerType::get(Ty->getContext(),
1417 Ty->getPointerAddressSpace()))
1418 return Val;
1419 if (Ty->isLabelTy())
1420 error(Loc, "'" + Name + "' is not a basic block");
1421 else
1422 error(Loc, "'" + Name + "' defined with type '" +
1423 getTypeString(Val->getType()) + "' but expected '" +
1424 getTypeString(Ty) + "'");
1425 return nullptr;
1426}
1427
1428/// getGlobalVal - Get a value with the specified name or ID, creating a
1429/// forward reference record if needed. This can return null if the value
1430/// exists but does not have the right type.
1431GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1432 LocTy Loc, bool IsCall) {
1433 PointerType *PTy = dyn_cast<PointerType>(Ty);
1434 if (!PTy) {
1435 error(Loc, "global variable reference must have pointer type");
1436 return nullptr;
1437 }
1438
1439 // Look this name up in the normal function symbol table.
1440 GlobalValue *Val =
1441 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1442
1443 // If this is a forward reference for the value, see if we already created a
1444 // forward ref record.
1445 if (!Val) {
1446 auto I = ForwardRefVals.find(Name);
1447 if (I != ForwardRefVals.end())
1448 Val = I->second.first;
1449 }
1450
1451 // If we have the value in the symbol table or fwd-ref table, return it.
1452 if (Val)
1453 return cast_or_null<GlobalValue>(
1454 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1455
1456 // Otherwise, create a new forward reference for this value and remember it.
1457 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1458 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1459 return FwdVal;
1460}
1461
1462GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1463 bool IsCall) {
1464 PointerType *PTy = dyn_cast<PointerType>(Ty);
1465 if (!PTy) {
1466 error(Loc, "global variable reference must have pointer type");
1467 return nullptr;
1468 }
1469
1470 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1471
1472 // If this is a forward reference for the value, see if we already created a
1473 // forward ref record.
1474 if (!Val) {
1475 auto I = ForwardRefValIDs.find(ID);
1476 if (I != ForwardRefValIDs.end())
1477 Val = I->second.first;
1478 }
1479
1480 // If we have the value in the symbol table or fwd-ref table, return it.
1481 if (Val)
1482 return cast_or_null<GlobalValue>(
1483 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1484
1485 // Otherwise, create a new forward reference for this value and remember it.
1486 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1487 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1488 return FwdVal;
1489}
1490
1491//===----------------------------------------------------------------------===//
1492// Comdat Reference/Resolution Routines.
1493//===----------------------------------------------------------------------===//
1494
1495Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1496 // Look this name up in the comdat symbol table.
1497 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1498 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1499 if (I != ComdatSymTab.end())
1500 return &I->second;
1501
1502 // Otherwise, create a new forward reference for this value and remember it.
1503 Comdat *C = M->getOrInsertComdat(Name);
1504 ForwardRefComdats[Name] = Loc;
1505 return C;
1506}
1507
1508//===----------------------------------------------------------------------===//
1509// Helper Routines.
1510//===----------------------------------------------------------------------===//
1511
1512/// parseToken - If the current token has the specified kind, eat it and return
1513/// success. Otherwise, emit the specified error and return failure.
1514bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1515 if (Lex.getKind() != T)
1516 return tokError(ErrMsg);
1517 Lex.Lex();
1518 return false;
1519}
1520
1521/// parseStringConstant
1522/// ::= StringConstant
1523bool LLParser::parseStringConstant(std::string &Result) {
1524 if (Lex.getKind() != lltok::StringConstant)
1525 return tokError("expected string constant");
1526 Result = Lex.getStrVal();
1527 Lex.Lex();
1528 return false;
1529}
1530
1531/// parseUInt32
1532/// ::= uint32
1533bool LLParser::parseUInt32(uint32_t &Val) {
1534 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1535 return tokError("expected integer");
1536 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1537 if (Val64 != unsigned(Val64))
1538 return tokError("expected 32-bit integer (too large)");
1539 Val = Val64;
1540 Lex.Lex();
1541 return false;
1542}
1543
1544/// parseUInt64
1545/// ::= uint64
1546bool LLParser::parseUInt64(uint64_t &Val) {
1547 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1548 return tokError("expected integer");
1549 Val = Lex.getAPSIntVal().getLimitedValue();
1550 Lex.Lex();
1551 return false;
1552}
1553
1554/// parseTLSModel
1555/// := 'localdynamic'
1556/// := 'initialexec'
1557/// := 'localexec'
1558bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1559 switch (Lex.getKind()) {
1560 default:
1561 return tokError("expected localdynamic, initialexec or localexec");
1562 case lltok::kw_localdynamic:
1563 TLM = GlobalVariable::LocalDynamicTLSModel;
1564 break;
1565 case lltok::kw_initialexec:
1566 TLM = GlobalVariable::InitialExecTLSModel;
1567 break;
1568 case lltok::kw_localexec:
1569 TLM = GlobalVariable::LocalExecTLSModel;
1570 break;
1571 }
1572
1573 Lex.Lex();
1574 return false;
1575}
1576
1577/// parseOptionalThreadLocal
1578/// := /*empty*/
1579/// := 'thread_local'
1580/// := 'thread_local' '(' tlsmodel ')'
1581bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1582 TLM = GlobalVariable::NotThreadLocal;
1583 if (!EatIfPresent(lltok::kw_thread_local))
1584 return false;
1585
1586 TLM = GlobalVariable::GeneralDynamicTLSModel;
1587 if (Lex.getKind() == lltok::lparen) {
1588 Lex.Lex();
1589 return parseTLSModel(TLM) ||
1590 parseToken(lltok::rparen, "expected ')' after thread local model");
1591 }
1592 return false;
1593}
1594
1595/// parseOptionalAddrSpace
1596/// := /*empty*/
1597/// := 'addrspace' '(' uint32 ')'
1598bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1599 AddrSpace = DefaultAS;
1600 if (!EatIfPresent(lltok::kw_addrspace))
1601 return false;
1602 return parseToken(lltok::lparen, "expected '(' in address space") ||
1603 parseUInt32(AddrSpace) ||
1604 parseToken(lltok::rparen, "expected ')' in address space");
1605}
1606
1607/// parseStringAttribute
1608/// := StringConstant
1609/// := StringConstant '=' StringConstant
1610bool LLParser::parseStringAttribute(AttrBuilder &B) {
1611 std::string Attr = Lex.getStrVal();
1612 Lex.Lex();
1613 std::string Val;
1614 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1615 return true;
1616 B.addAttribute(Attr, Val);
1617 return false;
1618}
1619
1620/// Parse a potentially empty list of parameter or return attributes.
1621bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1622 bool HaveError = false;
1623
1624 B.clear();
1625
1626 while (true) {
1627 lltok::Kind Token = Lex.getKind();
1628 if (Token == lltok::StringConstant) {
1629 if (parseStringAttribute(B))
1630 return true;
1631 continue;
1632 }
1633
1634 SMLoc Loc = Lex.getLoc();
1635 Attribute::AttrKind Attr = tokenToAttribute(Token);
1636 if (Attr == Attribute::None)
1637 return HaveError;
1638
1639 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1640 return true;
1641
1642 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1643 HaveError |= error(Loc, "this attribute does not apply to parameters");
1644 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1645 HaveError |= error(Loc, "this attribute does not apply to return values");
1646 }
1647}
1648
1649static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1650 HasLinkage = true;
1651 switch (Kind) {
1652 default:
1653 HasLinkage = false;
1654 return GlobalValue::ExternalLinkage;
1655 case lltok::kw_private:
1656 return GlobalValue::PrivateLinkage;
1657 case lltok::kw_internal:
1658 return GlobalValue::InternalLinkage;
1659 case lltok::kw_weak:
1660 return GlobalValue::WeakAnyLinkage;
1661 case lltok::kw_weak_odr:
1662 return GlobalValue::WeakODRLinkage;
1663 case lltok::kw_linkonce:
1664 return GlobalValue::LinkOnceAnyLinkage;
1665 case lltok::kw_linkonce_odr:
1666 return GlobalValue::LinkOnceODRLinkage;
1667 case lltok::kw_available_externally:
1668 return GlobalValue::AvailableExternallyLinkage;
1669 case lltok::kw_appending:
1670 return GlobalValue::AppendingLinkage;
1671 case lltok::kw_common:
1672 return GlobalValue::CommonLinkage;
1673 case lltok::kw_extern_weak:
1674 return GlobalValue::ExternalWeakLinkage;
1675 case lltok::kw_external:
1676 return GlobalValue::ExternalLinkage;
1677 }
1678}
1679
1680/// parseOptionalLinkage
1681/// ::= /*empty*/
1682/// ::= 'private'
1683/// ::= 'internal'
1684/// ::= 'weak'
1685/// ::= 'weak_odr'
1686/// ::= 'linkonce'
1687/// ::= 'linkonce_odr'
1688/// ::= 'available_externally'
1689/// ::= 'appending'
1690/// ::= 'common'
1691/// ::= 'extern_weak'
1692/// ::= 'external'
1693bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1694 unsigned &Visibility,
1695 unsigned &DLLStorageClass, bool &DSOLocal) {
1696 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1697 if (HasLinkage)
1698 Lex.Lex();
1699 parseOptionalDSOLocal(DSOLocal);
1700 parseOptionalVisibility(Visibility);
1701 parseOptionalDLLStorageClass(DLLStorageClass);
1702
1703 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1704 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1705 }
1706
1707 return false;
1708}
1709
1710void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1711 switch (Lex.getKind()) {
1712 default:
1713 DSOLocal = false;
1714 break;
1715 case lltok::kw_dso_local:
1716 DSOLocal = true;
1717 Lex.Lex();
1718 break;
1719 case lltok::kw_dso_preemptable:
1720 DSOLocal = false;
1721 Lex.Lex();
1722 break;
1723 }
1724}
1725
1726/// parseOptionalVisibility
1727/// ::= /*empty*/
1728/// ::= 'default'
1729/// ::= 'hidden'
1730/// ::= 'protected'
1731///
1732void LLParser::parseOptionalVisibility(unsigned &Res) {
1733 switch (Lex.getKind()) {
1734 default:
1735 Res = GlobalValue::DefaultVisibility;
1736 return;
1737 case lltok::kw_default:
1738 Res = GlobalValue::DefaultVisibility;
1739 break;
1740 case lltok::kw_hidden:
1741 Res = GlobalValue::HiddenVisibility;
1742 break;
1743 case lltok::kw_protected:
1744 Res = GlobalValue::ProtectedVisibility;
1745 break;
1746 }
1747 Lex.Lex();
1748}
1749
1750/// parseOptionalDLLStorageClass
1751/// ::= /*empty*/
1752/// ::= 'dllimport'
1753/// ::= 'dllexport'
1754///
1755void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1756 switch (Lex.getKind()) {
1757 default:
1758 Res = GlobalValue::DefaultStorageClass;
1759 return;
1760 case lltok::kw_dllimport:
1761 Res = GlobalValue::DLLImportStorageClass;
1762 break;
1763 case lltok::kw_dllexport:
1764 Res = GlobalValue::DLLExportStorageClass;
1765 break;
1766 }
1767 Lex.Lex();
1768}
1769
1770/// parseOptionalCallingConv
1771/// ::= /*empty*/
1772/// ::= 'ccc'
1773/// ::= 'fastcc'
1774/// ::= 'intel_ocl_bicc'
1775/// ::= 'coldcc'
1776/// ::= 'cfguard_checkcc'
1777/// ::= 'x86_stdcallcc'
1778/// ::= 'x86_fastcallcc'
1779/// ::= 'x86_thiscallcc'
1780/// ::= 'x86_vectorcallcc'
1781/// ::= 'arm_apcscc'
1782/// ::= 'arm_aapcscc'
1783/// ::= 'arm_aapcs_vfpcc'
1784/// ::= 'aarch64_vector_pcs'
1785/// ::= 'aarch64_sve_vector_pcs'
1786/// ::= 'msp430_intrcc'
1787/// ::= 'avr_intrcc'
1788/// ::= 'avr_signalcc'
1789/// ::= 'ptx_kernel'
1790/// ::= 'ptx_device'
1791/// ::= 'spir_func'
1792/// ::= 'spir_kernel'
1793/// ::= 'x86_64_sysvcc'
1794/// ::= 'win64cc'
1795/// ::= 'webkit_jscc'
1796/// ::= 'anyregcc'
1797/// ::= 'preserve_mostcc'
1798/// ::= 'preserve_allcc'
1799/// ::= 'ghccc'
1800/// ::= 'swiftcc'
1801/// ::= 'swifttailcc'
1802/// ::= 'x86_intrcc'
1803/// ::= 'hhvmcc'
1804/// ::= 'hhvm_ccc'
1805/// ::= 'cxx_fast_tlscc'
1806/// ::= 'amdgpu_vs'
1807/// ::= 'amdgpu_ls'
1808/// ::= 'amdgpu_hs'
1809/// ::= 'amdgpu_es'
1810/// ::= 'amdgpu_gs'
1811/// ::= 'amdgpu_ps'
1812/// ::= 'amdgpu_cs'
1813/// ::= 'amdgpu_kernel'
1814/// ::= 'tailcc'
1815/// ::= 'cc' UINT
1816///
1817bool LLParser::parseOptionalCallingConv(unsigned &CC) {
1818 switch (Lex.getKind()) {
1819 default: CC = CallingConv::C; return false;
1820 case lltok::kw_ccc: CC = CallingConv::C; break;
1821 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1822 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1823 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
1824 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1825 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1826 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1827 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1828 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1829 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1830 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1831 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1832 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1833 case lltok::kw_aarch64_sve_vector_pcs:
1834 CC = CallingConv::AArch64_SVE_VectorCall;
1835 break;
1836 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1837 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1838 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1839 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1840 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1841 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1842 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1843 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1844 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1845 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1846 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1847 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1848 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1849 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1850 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1851 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1852 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
1853 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1854 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1855 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1856 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1857 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1858 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
1859 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1860 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1861 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1862 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1863 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1864 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1865 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1866 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
1867 case lltok::kw_cc: {
1868 Lex.Lex();
1869 return parseUInt32(CC);
1870 }
1871 }
1872
1873 Lex.Lex();
1874 return false;
1875}
1876
1877/// parseMetadataAttachment
1878/// ::= !dbg !42
1879bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1880 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment")((void)0);
1881
1882 std::string Name = Lex.getStrVal();
1883 Kind = M->getMDKindID(Name);
1884 Lex.Lex();
1885
1886 return parseMDNode(MD);
1887}
1888
1889/// parseInstructionMetadata
1890/// ::= !dbg !42 (',' !dbg !57)*
1891bool LLParser::parseInstructionMetadata(Instruction &Inst) {
1892 do {
1893 if (Lex.getKind() != lltok::MetadataVar)
1894 return tokError("expected metadata after comma");
1895
1896 unsigned MDK;
1897 MDNode *N;
1898 if (parseMetadataAttachment(MDK, N))
1899 return true;
1900
1901 Inst.setMetadata(MDK, N);
1902 if (MDK == LLVMContext::MD_tbaa)
1903 InstsWithTBAATag.push_back(&Inst);
1904
1905 // If this is the end of the list, we're done.
1906 } while (EatIfPresent(lltok::comma));
1907 return false;
1908}
1909
1910/// parseGlobalObjectMetadataAttachment
1911/// ::= !dbg !57
1912bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1913 unsigned MDK;
1914 MDNode *N;
1915 if (parseMetadataAttachment(MDK, N))
1916 return true;
1917
1918 GO.addMetadata(MDK, *N);
1919 return false;
1920}
1921
1922/// parseOptionalFunctionMetadata
1923/// ::= (!dbg !57)*
1924bool LLParser::parseOptionalFunctionMetadata(Function &F) {
1925 while (Lex.getKind() == lltok::MetadataVar)
1926 if (parseGlobalObjectMetadataAttachment(F))
1927 return true;
1928 return false;
1929}
1930
1931/// parseOptionalAlignment
1932/// ::= /* empty */
1933/// ::= 'align' 4
1934bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
1935 Alignment = None;
1936 if (!EatIfPresent(lltok::kw_align))
1937 return false;
1938 LocTy AlignLoc = Lex.getLoc();
1939 uint32_t Value = 0;
1940
1941 LocTy ParenLoc = Lex.getLoc();
1942 bool HaveParens = false;
1943 if (AllowParens) {
1944 if (EatIfPresent(lltok::lparen))
1945 HaveParens = true;
1946 }
1947
1948 if (parseUInt32(Value))
1949 return true;
1950
1951 if (HaveParens && !EatIfPresent(lltok::rparen))
1952 return error(ParenLoc, "expected ')'");
1953
1954 if (!isPowerOf2_32(Value))
1955 return error(AlignLoc, "alignment is not a power of two");
1956 if (Value > Value::MaximumAlignment)
1957 return error(AlignLoc, "huge alignments are not supported yet");
1958 Alignment = Align(Value);
1959 return false;
1960}
1961
1962/// parseOptionalDerefAttrBytes
1963/// ::= /* empty */
1964/// ::= AttrKind '(' 4 ')'
1965///
1966/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1967bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1968 uint64_t &Bytes) {
1969 assert((AttrKind == lltok::kw_dereferenceable ||((void)0)
1970 AttrKind == lltok::kw_dereferenceable_or_null) &&((void)0)
1971 "contract!")((void)0);
1972
1973 Bytes = 0;
1974 if (!EatIfPresent(AttrKind))
1975 return false;
1976 LocTy ParenLoc = Lex.getLoc();
1977 if (!EatIfPresent(lltok::lparen))
1978 return error(ParenLoc, "expected '('");
1979 LocTy DerefLoc = Lex.getLoc();
1980 if (parseUInt64(Bytes))
1981 return true;
1982 ParenLoc = Lex.getLoc();
1983 if (!EatIfPresent(lltok::rparen))
1984 return error(ParenLoc, "expected ')'");
1985 if (!Bytes)
1986 return error(DerefLoc, "dereferenceable bytes must be non-zero");
1987 return false;
1988}
1989
1990/// parseOptionalCommaAlign
1991/// ::=
1992/// ::= ',' align 4
1993///
1994/// This returns with AteExtraComma set to true if it ate an excess comma at the
1995/// end.
1996bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
1997 bool &AteExtraComma) {
1998 AteExtraComma = false;
1999 while (EatIfPresent(lltok::comma)) {
2000 // Metadata at the end is an early exit.
2001 if (Lex.getKind() == lltok::MetadataVar) {
2002 AteExtraComma = true;
2003 return false;
2004 }
2005
2006 if (Lex.getKind() != lltok::kw_align)
2007 return error(Lex.getLoc(), "expected metadata or 'align'");
2008
2009 if (parseOptionalAlignment(Alignment))
2010 return true;
2011 }
2012
2013 return false;
2014}
2015
2016/// parseOptionalCommaAddrSpace
2017/// ::=
2018/// ::= ',' addrspace(1)
2019///
2020/// This returns with AteExtraComma set to true if it ate an excess comma at the
2021/// end.
2022bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2023 bool &AteExtraComma) {
2024 AteExtraComma = false;
2025 while (EatIfPresent(lltok::comma)) {
2026 // Metadata at the end is an early exit.
2027 if (Lex.getKind() == lltok::MetadataVar) {
2028 AteExtraComma = true;
2029 return false;
2030 }
2031
2032 Loc = Lex.getLoc();
2033 if (Lex.getKind() != lltok::kw_addrspace)
2034 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2035
2036 if (parseOptionalAddrSpace(AddrSpace))
2037 return true;
2038 }
2039
2040 return false;
2041}
2042
2043bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2044 Optional<unsigned> &HowManyArg) {
2045 Lex.Lex();
2046
2047 auto StartParen = Lex.getLoc();
2048 if (!EatIfPresent(lltok::lparen))
2049 return error(StartParen, "expected '('");
2050
2051 if (parseUInt32(BaseSizeArg))
2052 return true;
2053
2054 if (EatIfPresent(lltok::comma)) {
2055 auto HowManyAt = Lex.getLoc();
2056 unsigned HowMany;
2057 if (parseUInt32(HowMany))
2058 return true;
2059 if (HowMany == BaseSizeArg)
2060 return error(HowManyAt,
2061 "'allocsize' indices can't refer to the same parameter");
2062 HowManyArg = HowMany;
2063 } else
2064 HowManyArg = None;
2065
2066 auto EndParen = Lex.getLoc();
2067 if (!EatIfPresent(lltok::rparen))
2068 return error(EndParen, "expected ')'");
2069 return false;
2070}
2071
2072bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2073 unsigned &MaxValue) {
2074 Lex.Lex();
2075
2076 auto StartParen = Lex.getLoc();
2077 if (!EatIfPresent(lltok::lparen))
2078 return error(StartParen, "expected '('");
2079
2080 if (parseUInt32(MinValue))
2081 return true;
2082
2083 if (EatIfPresent(lltok::comma)) {
2084 if (parseUInt32(MaxValue))
2085 return true;
2086 } else
2087 MaxValue = MinValue;
2088
2089 auto EndParen = Lex.getLoc();
2090 if (!EatIfPresent(lltok::rparen))
2091 return error(EndParen, "expected ')'");
2092 return false;
2093}
2094
2095/// parseScopeAndOrdering
2096/// if isAtomic: ::= SyncScope? AtomicOrdering
2097/// else: ::=
2098///
2099/// This sets Scope and Ordering to the parsed values.
2100bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2101 AtomicOrdering &Ordering) {
2102 if (!IsAtomic)
2103 return false;
2104
2105 return parseScope(SSID) || parseOrdering(Ordering);
2106}
2107
2108/// parseScope
2109/// ::= syncscope("singlethread" | "<target scope>")?
2110///
2111/// This sets synchronization scope ID to the ID of the parsed value.
2112bool LLParser::parseScope(SyncScope::ID &SSID) {
2113 SSID = SyncScope::System;
2114 if (EatIfPresent(lltok::kw_syncscope)) {
2115 auto StartParenAt = Lex.getLoc();
2116 if (!EatIfPresent(lltok::lparen))
2117 return error(StartParenAt, "Expected '(' in syncscope");
2118
2119 std::string SSN;
2120 auto SSNAt = Lex.getLoc();
2121 if (parseStringConstant(SSN))
2122 return error(SSNAt, "Expected synchronization scope name");
2123
2124 auto EndParenAt = Lex.getLoc();
2125 if (!EatIfPresent(lltok::rparen))
2126 return error(EndParenAt, "Expected ')' in syncscope");
2127
2128 SSID = Context.getOrInsertSyncScopeID(SSN);
2129 }
2130
2131 return false;
2132}
2133
2134/// parseOrdering
2135/// ::= AtomicOrdering
2136///
2137/// This sets Ordering to the parsed value.
2138bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2139 switch (Lex.getKind()) {
2140 default:
2141 return tokError("Expected ordering on atomic instruction");
2142 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2143 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2144 // Not specified yet:
2145 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2146 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2147 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2148 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2149 case lltok::kw_seq_cst:
2150 Ordering = AtomicOrdering::SequentiallyConsistent;
2151 break;
2152 }
2153 Lex.Lex();
2154 return false;
2155}
2156
2157/// parseOptionalStackAlignment
2158/// ::= /* empty */
2159/// ::= 'alignstack' '(' 4 ')'
2160bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2161 Alignment = 0;
2162 if (!EatIfPresent(lltok::kw_alignstack))
2163 return false;
2164 LocTy ParenLoc = Lex.getLoc();
2165 if (!EatIfPresent(lltok::lparen))
2166 return error(ParenLoc, "expected '('");
2167 LocTy AlignLoc = Lex.getLoc();
2168 if (parseUInt32(Alignment))
2169 return true;
2170 ParenLoc = Lex.getLoc();
2171 if (!EatIfPresent(lltok::rparen))
2172 return error(ParenLoc, "expected ')'");
2173 if (!isPowerOf2_32(Alignment))
2174 return error(AlignLoc, "stack alignment is not a power of two");
2175 return false;
2176}
2177
2178/// parseIndexList - This parses the index list for an insert/extractvalue
2179/// instruction. This sets AteExtraComma in the case where we eat an extra
2180/// comma at the end of the line and find that it is followed by metadata.
2181/// Clients that don't allow metadata can call the version of this function that
2182/// only takes one argument.
2183///
2184/// parseIndexList
2185/// ::= (',' uint32)+
2186///
2187bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2188 bool &AteExtraComma) {
2189 AteExtraComma = false;
2190
2191 if (Lex.getKind() != lltok::comma)
2192 return tokError("expected ',' as start of index list");
2193
2194 while (EatIfPresent(lltok::comma)) {
2195 if (Lex.getKind() == lltok::MetadataVar) {
2196 if (Indices.empty())
2197 return tokError("expected index");
2198 AteExtraComma = true;
2199 return false;
2200 }
2201 unsigned Idx = 0;
2202 if (parseUInt32(Idx))
2203 return true;
2204 Indices.push_back(Idx);
2205 }
2206
2207 return false;
2208}
2209
2210//===----------------------------------------------------------------------===//
2211// Type Parsing.
2212//===----------------------------------------------------------------------===//
2213
2214/// parseType - parse a type.
2215bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2216 SMLoc TypeLoc = Lex.getLoc();
2217 switch (Lex.getKind()) {
2218 default:
2219 return tokError(Msg);
2220 case lltok::Type:
2221 // Type ::= 'float' | 'void' (etc)
2222 Result = Lex.getTyVal();
2223 Lex.Lex();
2224 break;
2225 case lltok::lbrace:
2226 // Type ::= StructType
2227 if (parseAnonStructType(Result, false))
2228 return true;
2229 break;
2230 case lltok::lsquare:
2231 // Type ::= '[' ... ']'
2232 Lex.Lex(); // eat the lsquare.
2233 if (parseArrayVectorType(Result, false))
2234 return true;
2235 break;
2236 case lltok::less: // Either vector or packed struct.
2237 // Type ::= '<' ... '>'
2238 Lex.Lex();
2239 if (Lex.getKind() == lltok::lbrace) {
2240 if (parseAnonStructType(Result, true) ||
2241 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2242 return true;
2243 } else if (parseArrayVectorType(Result, true))
2244 return true;
2245 break;
2246 case lltok::LocalVar: {
2247 // Type ::= %foo
2248 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2249
2250 // If the type hasn't been defined yet, create a forward definition and
2251 // remember where that forward def'n was seen (in case it never is defined).
2252 if (!Entry.first) {
2253 Entry.first = StructType::create(Context, Lex.getStrVal());
2254 Entry.second = Lex.getLoc();
2255 }
2256 Result = Entry.first;
2257 Lex.Lex();
2258 break;
2259 }
2260
2261 case lltok::LocalVarID: {
2262 // Type ::= %4
2263 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2264
2265 // If the type hasn't been defined yet, create a forward definition and
2266 // remember where that forward def'n was seen (in case it never is defined).
2267 if (!Entry.first) {
2268 Entry.first = StructType::create(Context);
2269 Entry.second = Lex.getLoc();
2270 }
2271 Result = Entry.first;
2272 Lex.Lex();
2273 break;
2274 }
2275 }
2276
2277 // Handle (explicit) opaque pointer types (not --force-opaque-pointers).
2278 //
2279 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2280 if (Result->isOpaquePointerTy()) {
2281 unsigned AddrSpace;
2282 if (parseOptionalAddrSpace(AddrSpace))
2283 return true;
2284 Result = PointerType::get(getContext(), AddrSpace);
2285
2286 // Give a nice error for 'ptr*'.
2287 if (Lex.getKind() == lltok::star)
2288 return tokError("ptr* is invalid - use ptr instead");
2289
2290 // Fall through to parsing the type suffixes only if this 'ptr' is a
2291 // function return. Otherwise, return success, implicitly rejecting other
2292 // suffixes.
2293 if (Lex.getKind() != lltok::lparen)
2294 return false;
2295 }
2296
2297 // parse the type suffixes.
2298 while (true) {
2299 switch (Lex.getKind()) {
2300 // End of type.
2301 default:
2302 if (!AllowVoid && Result->isVoidTy())
2303 return error(TypeLoc, "void type only allowed for function results");
2304 return false;
2305
2306 // Type ::= Type '*'
2307 case lltok::star:
2308 if (Result->isLabelTy())
2309 return tokError("basic block pointers are invalid");
2310 if (Result->isVoidTy())
2311 return tokError("pointers to void are invalid - use i8* instead");
2312 if (!PointerType::isValidElementType(Result))
2313 return tokError("pointer to this type is invalid");
2314 Result = PointerType::getUnqual(Result);
2315 Lex.Lex();
2316 break;
2317
2318 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2319 case lltok::kw_addrspace: {
2320 if (Result->isLabelTy())
2321 return tokError("basic block pointers are invalid");
2322 if (Result->isVoidTy())
2323 return tokError("pointers to void are invalid; use i8* instead");
2324 if (!PointerType::isValidElementType(Result))
2325 return tokError("pointer to this type is invalid");
2326 unsigned AddrSpace;
2327 if (parseOptionalAddrSpace(AddrSpace) ||
2328 parseToken(lltok::star, "expected '*' in address space"))
2329 return true;
2330
2331 Result = PointerType::get(Result, AddrSpace);
2332 break;
2333 }
2334
2335 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2336 case lltok::lparen:
2337 if (parseFunctionType(Result))
2338 return true;
2339 break;
2340 }
2341 }
2342}
2343
2344/// parseParameterList
2345/// ::= '(' ')'
2346/// ::= '(' Arg (',' Arg)* ')'
2347/// Arg
2348/// ::= Type OptionalAttributes Value OptionalAttributes
2349bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2350 PerFunctionState &PFS, bool IsMustTailCall,
2351 bool InVarArgsFunc) {
2352 if (parseToken(lltok::lparen, "expected '(' in call"))
2353 return true;
2354
2355 while (Lex.getKind() != lltok::rparen) {
2356 // If this isn't the first argument, we need a comma.
2357 if (!ArgList.empty() &&
2358 parseToken(lltok::comma, "expected ',' in argument list"))
2359 return true;
2360
2361 // parse an ellipsis if this is a musttail call in a variadic function.
2362 if (Lex.getKind() == lltok::dotdotdot) {
2363 const char *Msg = "unexpected ellipsis in argument list for ";
2364 if (!IsMustTailCall)
2365 return tokError(Twine(Msg) + "non-musttail call");
2366 if (!InVarArgsFunc)
2367 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2368 Lex.Lex(); // Lex the '...', it is purely for readability.
2369 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2370 }
2371
2372 // parse the argument.
2373 LocTy ArgLoc;
2374 Type *ArgTy = nullptr;
2375 AttrBuilder ArgAttrs;
2376 Value *V;
2377 if (parseType(ArgTy, ArgLoc))
2378 return true;
2379
2380 if (ArgTy->isMetadataTy()) {
2381 if (parseMetadataAsValue(V, PFS))
2382 return true;
2383 } else {
2384 // Otherwise, handle normal operands.
2385 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2386 return true;
2387 }
2388 ArgList.push_back(ParamInfo(
2389 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2390 }
2391
2392 if (IsMustTailCall && InVarArgsFunc)
2393 return tokError("expected '...' at end of argument list for musttail call "
2394 "in varargs function");
2395
2396 Lex.Lex(); // Lex the ')'.
2397 return false;
2398}
2399
2400/// parseRequiredTypeAttr
2401/// ::= attrname(<ty>)
2402bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2403 Attribute::AttrKind AttrKind) {
2404 Type *Ty = nullptr;
2405 if (!EatIfPresent(AttrToken))
2406 return true;
2407 if (!EatIfPresent(lltok::lparen))
2408 return error(Lex.getLoc(), "expected '('");
2409 if (parseType(Ty))
2410 return true;
2411 if (!EatIfPresent(lltok::rparen))
2412 return error(Lex.getLoc(), "expected ')'");
2413
2414 B.addTypeAttr(AttrKind, Ty);
2415 return false;
2416}
2417
2418/// parseOptionalOperandBundles
2419/// ::= /*empty*/
2420/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2421///
2422/// OperandBundle
2423/// ::= bundle-tag '(' ')'
2424/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2425///
2426/// bundle-tag ::= String Constant
2427bool LLParser::parseOptionalOperandBundles(
2428 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2429 LocTy BeginLoc = Lex.getLoc();
2430 if (!EatIfPresent(lltok::lsquare))
2431 return false;
2432
2433 while (Lex.getKind() != lltok::rsquare) {
2434 // If this isn't the first operand bundle, we need a comma.
2435 if (!BundleList.empty() &&
2436 parseToken(lltok::comma, "expected ',' in input list"))
2437 return true;
2438
2439 std::string Tag;
2440 if (parseStringConstant(Tag))
2441 return true;
2442
2443 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2444 return true;
2445
2446 std::vector<Value *> Inputs;
2447 while (Lex.getKind() != lltok::rparen) {
2448 // If this isn't the first input, we need a comma.
2449 if (!Inputs.empty() &&
2450 parseToken(lltok::comma, "expected ',' in input list"))
2451 return true;
2452
2453 Type *Ty = nullptr;
2454 Value *Input = nullptr;
2455 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2456 return true;
2457 Inputs.push_back(Input);
2458 }
2459
2460 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2461
2462 Lex.Lex(); // Lex the ')'.
2463 }
2464
2465 if (BundleList.empty())
2466 return error(BeginLoc, "operand bundle set must not be empty");
2467
2468 Lex.Lex(); // Lex the ']'.
2469 return false;
2470}
2471
2472/// parseArgumentList - parse the argument list for a function type or function
2473/// prototype.
2474/// ::= '(' ArgTypeListI ')'
2475/// ArgTypeListI
2476/// ::= /*empty*/
2477/// ::= '...'
2478/// ::= ArgTypeList ',' '...'
2479/// ::= ArgType (',' ArgType)*
2480///
2481bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2482 bool &IsVarArg) {
2483 unsigned CurValID = 0;
2484 IsVarArg = false;
2485 assert(Lex.getKind() == lltok::lparen)((void)0);
2486 Lex.Lex(); // eat the (.
2487
2488 if (Lex.getKind() == lltok::rparen) {
2489 // empty
2490 } else if (Lex.getKind() == lltok::dotdotdot) {
2491 IsVarArg = true;
2492 Lex.Lex();
2493 } else {
2494 LocTy TypeLoc = Lex.getLoc();
2495 Type *ArgTy = nullptr;
2496 AttrBuilder Attrs;
2497 std::string Name;
2498
2499 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2500 return true;
2501
2502 if (ArgTy->isVoidTy())
2503 return error(TypeLoc, "argument can not have void type");
2504
2505 if (Lex.getKind() == lltok::LocalVar) {
2506 Name = Lex.getStrVal();
2507 Lex.Lex();
2508 } else if (Lex.getKind() == lltok::LocalVarID) {
2509 if (Lex.getUIntVal() != CurValID)
2510 return error(TypeLoc, "argument expected to be numbered '%" +
2511 Twine(CurValID) + "'");
2512 ++CurValID;
2513 Lex.Lex();
2514 }
2515
2516 if (!FunctionType::isValidArgumentType(ArgTy))
2517 return error(TypeLoc, "invalid type for function argument");
2518
2519 ArgList.emplace_back(TypeLoc, ArgTy,
2520 AttributeSet::get(ArgTy->getContext(), Attrs),
2521 std::move(Name));
2522
2523 while (EatIfPresent(lltok::comma)) {
2524 // Handle ... at end of arg list.
2525 if (EatIfPresent(lltok::dotdotdot)) {
2526 IsVarArg = true;
2527 break;
2528 }
2529
2530 // Otherwise must be an argument type.
2531 TypeLoc = Lex.getLoc();
2532 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2533 return true;
2534
2535 if (ArgTy->isVoidTy())
2536 return error(TypeLoc, "argument can not have void type");
2537
2538 if (Lex.getKind() == lltok::LocalVar) {
2539 Name = Lex.getStrVal();
2540 Lex.Lex();
2541 } else {
2542 if (Lex.getKind() == lltok::LocalVarID) {
2543 if (Lex.getUIntVal() != CurValID)
2544 return error(TypeLoc, "argument expected to be numbered '%" +
2545 Twine(CurValID) + "'");
2546 Lex.Lex();
2547 }
2548 ++CurValID;
2549 Name = "";
2550 }
2551
2552 if (!ArgTy->isFirstClassType())
2553 return error(TypeLoc, "invalid type for function argument");
2554
2555 ArgList.emplace_back(TypeLoc, ArgTy,
2556 AttributeSet::get(ArgTy->getContext(), Attrs),
2557 std::move(Name));
2558 }
2559 }
2560
2561 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2562}
2563
2564/// parseFunctionType
2565/// ::= Type ArgumentList OptionalAttrs
2566bool LLParser::parseFunctionType(Type *&Result) {
2567 assert(Lex.getKind() == lltok::lparen)((void)0);
2568
2569 if (!FunctionType::isValidReturnType(Result))
2570 return tokError("invalid function return type");
2571
2572 SmallVector<ArgInfo, 8> ArgList;
2573 bool IsVarArg;
2574 if (parseArgumentList(ArgList, IsVarArg))
2575 return true;
2576
2577 // Reject names on the arguments lists.
2578 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2579 if (!ArgList[i].Name.empty())
2580 return error(ArgList[i].Loc, "argument name invalid in function type");
2581 if (ArgList[i].Attrs.hasAttributes())
2582 return error(ArgList[i].Loc,
2583 "argument attributes invalid in function type");
2584 }
2585
2586 SmallVector<Type*, 16> ArgListTy;
2587 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2588 ArgListTy.push_back(ArgList[i].Ty);
2589
2590 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2591 return false;
2592}
2593
2594/// parseAnonStructType - parse an anonymous struct type, which is inlined into
2595/// other structs.
2596bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2597 SmallVector<Type*, 8> Elts;
2598 if (parseStructBody(Elts))
2599 return true;
2600
2601 Result = StructType::get(Context, Elts, Packed);
2602 return false;
2603}
2604
2605/// parseStructDefinition - parse a struct in a 'type' definition.
2606bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2607 std::pair<Type *, LocTy> &Entry,
2608 Type *&ResultTy) {
2609 // If the type was already defined, diagnose the redefinition.
2610 if (Entry.first && !Entry.second.isValid())
2611 return error(TypeLoc, "redefinition of type");
2612
2613 // If we have opaque, just return without filling in the definition for the
2614 // struct. This counts as a definition as far as the .ll file goes.
2615 if (EatIfPresent(lltok::kw_opaque)) {
2616 // This type is being defined, so clear the location to indicate this.
2617 Entry.second = SMLoc();
2618
2619 // If this type number has never been uttered, create it.
2620 if (!Entry.first)
2621 Entry.first = StructType::create(Context, Name);
2622 ResultTy = Entry.first;
2623 return false;
2624 }
2625
2626 // If the type starts with '<', then it is either a packed struct or a vector.
2627 bool isPacked = EatIfPresent(lltok::less);
2628
2629 // If we don't have a struct, then we have a random type alias, which we
2630 // accept for compatibility with old files. These types are not allowed to be
2631 // forward referenced and not allowed to be recursive.
2632 if (Lex.getKind() != lltok::lbrace) {
2633 if (Entry.first)
2634 return error(TypeLoc, "forward references to non-struct type");
2635
2636 ResultTy = nullptr;
2637 if (isPacked)
2638 return parseArrayVectorType(ResultTy, true);
2639 return parseType(ResultTy);
2640 }
2641
2642 // This type is being defined, so clear the location to indicate this.
2643 Entry.second = SMLoc();
2644
2645 // If this type number has never been uttered, create it.
2646 if (!Entry.first)
2647 Entry.first = StructType::create(Context, Name);
2648
2649 StructType *STy = cast<StructType>(Entry.first);
2650
2651 SmallVector<Type*, 8> Body;
2652 if (parseStructBody(Body) ||
2653 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2654 return true;
2655
2656 STy->setBody(Body, isPacked);
2657 ResultTy = STy;
2658 return false;
2659}
2660
2661/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2662/// StructType
2663/// ::= '{' '}'
2664/// ::= '{' Type (',' Type)* '}'
2665/// ::= '<' '{' '}' '>'
2666/// ::= '<' '{' Type (',' Type)* '}' '>'
2667bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2668 assert(Lex.getKind() == lltok::lbrace)((void)0);
2669 Lex.Lex(); // Consume the '{'
2670
2671 // Handle the empty struct.
2672 if (EatIfPresent(lltok::rbrace))
2673 return false;
2674
2675 LocTy EltTyLoc = Lex.getLoc();
2676 Type *Ty = nullptr;
2677 if (parseType(Ty))
2678 return true;
2679 Body.push_back(Ty);
2680
2681 if (!StructType::isValidElementType(Ty))
2682 return error(EltTyLoc, "invalid element type for struct");
2683
2684 while (EatIfPresent(lltok::comma)) {
2685 EltTyLoc = Lex.getLoc();
2686 if (parseType(Ty))
2687 return true;
2688
2689 if (!StructType::isValidElementType(Ty))
2690 return error(EltTyLoc, "invalid element type for struct");
2691
2692 Body.push_back(Ty);
2693 }
2694
2695 return parseToken(lltok::rbrace, "expected '}' at end of struct");
2696}
2697
2698/// parseArrayVectorType - parse an array or vector type, assuming the first
2699/// token has already been consumed.
2700/// Type
2701/// ::= '[' APSINTVAL 'x' Types ']'
2702/// ::= '<' APSINTVAL 'x' Types '>'
2703/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2704bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
2705 bool Scalable = false;
2706
2707 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
2708 Lex.Lex(); // consume the 'vscale'
2709 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
2710 return true;
2711
2712 Scalable = true;
2713 }
2714
2715 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2716 Lex.getAPSIntVal().getBitWidth() > 64)
2717 return tokError("expected number in address space");
2718
2719 LocTy SizeLoc = Lex.getLoc();
2720 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2721 Lex.Lex();
2722
2723 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
2724 return true;
2725
2726 LocTy TypeLoc = Lex.getLoc();
2727 Type *EltTy = nullptr;
2728 if (parseType(EltTy))
2729 return true;
2730
2731 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
2732 "expected end of sequential type"))
2733 return true;
2734
2735 if (IsVector) {
2736 if (Size == 0)
2737 return error(SizeLoc, "zero element vector is illegal");
2738 if ((unsigned)Size != Size)
2739 return error(SizeLoc, "size too large for vector");
2740 if (!VectorType::isValidElementType(EltTy))
2741 return error(TypeLoc, "invalid vector element type");
2742 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2743 } else {
2744 if (!ArrayType::isValidElementType(EltTy))
2745 return error(TypeLoc, "invalid array element type");
2746 Result = ArrayType::get(EltTy, Size);
2747 }
2748 return false;
2749}
2750
2751//===----------------------------------------------------------------------===//
2752// Function Semantic Analysis.
2753//===----------------------------------------------------------------------===//
2754
2755LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2756 int functionNumber)
2757 : P(p), F(f), FunctionNumber(functionNumber) {
2758
2759 // Insert unnamed arguments into the NumberedVals list.
2760 for (Argument &A : F.args())
2761 if (!A.hasName())
2762 NumberedVals.push_back(&A);
2763}
2764
2765LLParser::PerFunctionState::~PerFunctionState() {
2766 // If there were any forward referenced non-basicblock values, delete them.
2767
2768 for (const auto &P : ForwardRefVals) {
2769 if (isa<BasicBlock>(P.second.first))
2770 continue;
2771 P.second.first->replaceAllUsesWith(
2772 UndefValue::get(P.second.first->getType()));
2773 P.second.first->deleteValue();
2774 }
2775
2776 for (const auto &P : ForwardRefValIDs) {
2777 if (isa<BasicBlock>(P.second.first))
2778 continue;
2779 P.second.first->replaceAllUsesWith(
2780 UndefValue::get(P.second.first->getType()));
2781 P.second.first->deleteValue();
2782 }
2783}
2784
2785bool LLParser::PerFunctionState::finishFunction() {
2786 if (!ForwardRefVals.empty())
2787 return P.error(ForwardRefVals.begin()->second.second,
2788 "use of undefined value '%" + ForwardRefVals.begin()->first +
2789 "'");
2790 if (!ForwardRefValIDs.empty())
2791 return P.error(ForwardRefValIDs.begin()->second.second,
2792 "use of undefined value '%" +
2793 Twine(ForwardRefValIDs.begin()->first) + "'");
2794 return false;
2795}
2796
2797/// getVal - Get a value with the specified name or ID, creating a
2798/// forward reference record if needed. This can return null if the value
2799/// exists but does not have the right type.
2800Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
2801 LocTy Loc, bool IsCall) {
2802 // Look this name up in the normal function symbol table.
2803 Value *Val = F.getValueSymbolTable()->lookup(Name);
2804
2805 // If this is a forward reference for the value, see if we already created a
2806 // forward ref record.
2807 if (!Val) {
2808 auto I = ForwardRefVals.find(Name);
2809 if (I != ForwardRefVals.end())
2810 Val = I->second.first;
2811 }
2812
2813 // If we have the value in the symbol table or fwd-ref table, return it.
2814 if (Val)
2815 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2816
2817 // Don't make placeholders with invalid type.
2818 if (!Ty->isFirstClassType()) {
2819 P.error(Loc, "invalid use of a non-first-class type");
2820 return nullptr;
2821 }
2822
2823 // Otherwise, create a new forward reference for this value and remember it.
2824 Value *FwdVal;
2825 if (Ty->isLabelTy()) {
2826 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2827 } else {
2828 FwdVal = new Argument(Ty, Name);
2829 }
2830
2831 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2832 return FwdVal;
2833}
2834
2835Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc,
2836 bool IsCall) {
2837 // Look this name up in the normal function symbol table.
2838 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2839
2840 // If this is a forward reference for the value, see if we already created a
2841 // forward ref record.
2842 if (!Val) {
2843 auto I = ForwardRefValIDs.find(ID);
2844 if (I != ForwardRefValIDs.end())
2845 Val = I->second.first;
2846 }
2847
2848 // If we have the value in the symbol table or fwd-ref table, return it.
2849 if (Val)
2850 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2851
2852 if (!Ty->isFirstClassType()) {
2853 P.error(Loc, "invalid use of a non-first-class type");
2854 return nullptr;
2855 }
2856
2857 // Otherwise, create a new forward reference for this value and remember it.
2858 Value *FwdVal;
2859 if (Ty->isLabelTy()) {
2860 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2861 } else {
2862 FwdVal = new Argument(Ty);
2863 }
2864
2865 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2866 return FwdVal;
2867}
2868
2869/// setInstName - After an instruction is parsed and inserted into its
2870/// basic block, this installs its name.
2871bool LLParser::PerFunctionState::setInstName(int NameID,
2872 const std::string &NameStr,
2873 LocTy NameLoc, Instruction *Inst) {
2874 // If this instruction has void type, it cannot have a name or ID specified.
2875 if (Inst->getType()->isVoidTy()) {
2876 if (NameID != -1 || !NameStr.empty())
2877 return P.error(NameLoc, "instructions returning void cannot have a name");
2878 return false;
2879 }
2880
2881 // If this was a numbered instruction, verify that the instruction is the
2882 // expected value and resolve any forward references.
2883 if (NameStr.empty()) {
2884 // If neither a name nor an ID was specified, just use the next ID.
2885 if (NameID == -1)
2886 NameID = NumberedVals.size();
2887
2888 if (unsigned(NameID) != NumberedVals.size())
2889 return P.error(NameLoc, "instruction expected to be numbered '%" +
2890 Twine(NumberedVals.size()) + "'");
2891
2892 auto FI = ForwardRefValIDs.find(NameID);
2893 if (FI != ForwardRefValIDs.end()) {
2894 Value *Sentinel = FI->second.first;
2895 if (Sentinel->getType() != Inst->getType())
2896 return P.error(NameLoc, "instruction forward referenced with type '" +
2897 getTypeString(FI->second.first->getType()) +
2898 "'");
2899
2900 Sentinel->replaceAllUsesWith(Inst);
2901 Sentinel->deleteValue();
2902 ForwardRefValIDs.erase(FI);
2903 }
2904
2905 NumberedVals.push_back(Inst);
2906 return false;
2907 }
2908
2909 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2910 auto FI = ForwardRefVals.find(NameStr);
2911 if (FI != ForwardRefVals.end()) {
2912 Value *Sentinel = FI->second.first;
2913 if (Sentinel->getType() != Inst->getType())
2914 return P.error(NameLoc, "instruction forward referenced with type '" +
2915 getTypeString(FI->second.first->getType()) +
2916 "'");
2917
2918 Sentinel->replaceAllUsesWith(Inst);
2919 Sentinel->deleteValue();
2920 ForwardRefVals.erase(FI);
2921 }
2922
2923 // Set the name on the instruction.
2924 Inst->setName(NameStr);
2925
2926 if (Inst->getName() != NameStr)
2927 return P.error(NameLoc, "multiple definition of local value named '" +
2928 NameStr + "'");
2929 return false;
2930}
2931
2932/// getBB - Get a basic block with the specified name or ID, creating a
2933/// forward reference record if needed.
2934BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
2935 LocTy Loc) {
2936 return dyn_cast_or_null<BasicBlock>(
2937 getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2938}
2939
2940BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
2941 return dyn_cast_or_null<BasicBlock>(
2942 getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2943}
2944
2945/// defineBB - Define the specified basic block, which is either named or
2946/// unnamed. If there is an error, this returns null otherwise it returns
2947/// the block being defined.
2948BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
2949 int NameID, LocTy Loc) {
2950 BasicBlock *BB;
2951 if (Name.empty()) {
2952 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
2953 P.error(Loc, "label expected to be numbered '" +
2954 Twine(NumberedVals.size()) + "'");
2955 return nullptr;
2956 }
2957 BB = getBB(NumberedVals.size(), Loc);
2958 if (!BB) {
2959 P.error(Loc, "unable to create block numbered '" +
2960 Twine(NumberedVals.size()) + "'");
2961 return nullptr;
2962 }
2963 } else {
2964 BB = getBB(Name, Loc);
2965 if (!BB) {
2966 P.error(Loc, "unable to create block named '" + Name + "'");
2967 return nullptr;
2968 }
2969 }
2970
2971 // Move the block to the end of the function. Forward ref'd blocks are
2972 // inserted wherever they happen to be referenced.
2973 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2974
2975 // Remove the block from forward ref sets.
2976 if (Name.empty()) {
2977 ForwardRefValIDs.erase(NumberedVals.size());
2978 NumberedVals.push_back(BB);
2979 } else {
2980 // BB forward references are already in the function symbol table.
2981 ForwardRefVals.erase(Name);
2982 }
2983
2984 return BB;
2985}
2986
2987//===----------------------------------------------------------------------===//
2988// Constants.
2989//===----------------------------------------------------------------------===//
2990
2991/// parseValID - parse an abstract value that doesn't necessarily have a
2992/// type implied. For example, if we parse "4" we don't know what integer type
2993/// it has. The value will later be combined with its type and checked for
2994/// sanity. PFS is used to convert function-local operands of metadata (since
2995/// metadata operands are not just parsed here but also converted to values).
2996/// PFS can be null when we are not parsing metadata values inside a function.
2997bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
2998 ID.Loc = Lex.getLoc();
2999 switch (Lex.getKind()) {
1
Control jumps to 'case kw_dso_local_equivalent:' at line 3258
3000 default:
3001 return tokError("expected value token");
3002 case lltok::GlobalID: // @42
3003 ID.UIntVal = Lex.getUIntVal();
3004 ID.Kind = ValID::t_GlobalID;
3005 break;
3006 case lltok::GlobalVar: // @foo
3007 ID.StrVal = Lex.getStrVal();
3008 ID.Kind = ValID::t_GlobalName;
3009 break;
3010 case lltok::LocalVarID: // %42
3011 ID.UIntVal = Lex.getUIntVal();
3012 ID.Kind = ValID::t_LocalID;
3013 break;
3014 case lltok::LocalVar: // %foo
3015 ID.StrVal = Lex.getStrVal();
3016 ID.Kind = ValID::t_LocalName;
3017 break;
3018 case lltok::APSInt:
3019 ID.APSIntVal = Lex.getAPSIntVal();
3020 ID.Kind = ValID::t_APSInt;
3021 break;
3022 case lltok::APFloat:
3023 ID.APFloatVal = Lex.getAPFloatVal();
3024 ID.Kind = ValID::t_APFloat;
3025 break;
3026 case lltok::kw_true:
3027 ID.ConstantVal = ConstantInt::getTrue(Context);
3028 ID.Kind = ValID::t_Constant;
3029 break;
3030 case lltok::kw_false:
3031 ID.ConstantVal = ConstantInt::getFalse(Context);
3032 ID.Kind = ValID::t_Constant;
3033 break;
3034 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3035 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3036 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3037 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3038 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3039
3040 case lltok::lbrace: {
3041 // ValID ::= '{' ConstVector '}'
3042 Lex.Lex();
3043 SmallVector<Constant*, 16> Elts;
3044 if (parseGlobalValueVector(Elts) ||
3045 parseToken(lltok::rbrace, "expected end of struct constant"))
3046 return true;
3047
3048 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3049 ID.UIntVal = Elts.size();
3050 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3051 Elts.size() * sizeof(Elts[0]));
3052 ID.Kind = ValID::t_ConstantStruct;
3053 return false;
3054 }
3055 case lltok::less: {
3056 // ValID ::= '<' ConstVector '>' --> Vector.
3057 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3058 Lex.Lex();
3059 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3060
3061 SmallVector<Constant*, 16> Elts;
3062 LocTy FirstEltLoc = Lex.getLoc();
3063 if (parseGlobalValueVector(Elts) ||
3064 (isPackedStruct &&
3065 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3066 parseToken(lltok::greater, "expected end of constant"))
3067 return true;
3068
3069 if (isPackedStruct) {
3070 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3071 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3072 Elts.size() * sizeof(Elts[0]));
3073 ID.UIntVal = Elts.size();
3074 ID.Kind = ValID::t_PackedConstantStruct;
3075 return false;
3076 }
3077
3078 if (Elts.empty())
3079 return error(ID.Loc, "constant vector must not be empty");
3080
3081 if (!Elts[0]->getType()->isIntegerTy() &&
3082 !Elts[0]->getType()->isFloatingPointTy() &&
3083 !Elts[0]->getType()->isPointerTy())
3084 return error(
3085 FirstEltLoc,
3086 "vector elements must have integer, pointer or floating point type");
3087
3088 // Verify that all the vector elements have the same type.
3089 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3090 if (Elts[i]->getType() != Elts[0]->getType())
3091 return error(FirstEltLoc, "vector element #" + Twine(i) +
3092 " is not of type '" +
3093 getTypeString(Elts[0]->getType()));
3094
3095 ID.ConstantVal = ConstantVector::get(Elts);
3096 ID.Kind = ValID::t_Constant;
3097 return false;
3098 }
3099 case lltok::lsquare: { // Array Constant
3100 Lex.Lex();
3101 SmallVector<Constant*, 16> Elts;
3102 LocTy FirstEltLoc = Lex.getLoc();
3103 if (parseGlobalValueVector(Elts) ||
3104 parseToken(lltok::rsquare, "expected end of array constant"))
3105 return true;
3106
3107 // Handle empty element.
3108 if (Elts.empty()) {
3109 // Use undef instead of an array because it's inconvenient to determine
3110 // the element type at this point, there being no elements to examine.
3111 ID.Kind = ValID::t_EmptyArray;
3112 return false;
3113 }
3114
3115 if (!Elts[0]->getType()->isFirstClassType())
3116 return error(FirstEltLoc, "invalid array element type: " +
3117 getTypeString(Elts[0]->getType()));
3118
3119 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3120
3121 // Verify all elements are correct type!
3122 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3123 if (Elts[i]->getType() != Elts[0]->getType())
3124 return error(FirstEltLoc, "array element #" + Twine(i) +
3125 " is not of type '" +
3126 getTypeString(Elts[0]->getType()));
3127 }
3128
3129 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3130 ID.Kind = ValID::t_Constant;
3131 return false;
3132 }
3133 case lltok::kw_c: // c "foo"
3134 Lex.Lex();
3135 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3136 false);
3137 if (parseToken(lltok::StringConstant, "expected string"))
3138 return true;
3139 ID.Kind = ValID::t_Constant;
3140 return false;
3141
3142 case lltok::kw_asm: {
3143 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3144 // STRINGCONSTANT
3145 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3146 Lex.Lex();
3147 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3148 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3149 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3150 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3151 parseStringConstant(ID.StrVal) ||
3152 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3153 parseToken(lltok::StringConstant, "expected constraint string"))
3154 return true;
3155 ID.StrVal2 = Lex.getStrVal();
3156 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3157 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3158 ID.Kind = ValID::t_InlineAsm;
3159 return false;
3160 }
3161
3162 case lltok::kw_blockaddress: {
3163 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3164 Lex.Lex();
3165
3166 ValID Fn, Label;
3167
3168 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3169 parseValID(Fn, PFS) ||
3170 parseToken(lltok::comma,
3171 "expected comma in block address expression") ||
3172 parseValID(Label, PFS) ||
3173 parseToken(lltok::rparen, "expected ')' in block address expression"))
3174 return true;
3175
3176 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3177 return error(Fn.Loc, "expected function name in blockaddress");
3178 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3179 return error(Label.Loc, "expected basic block name in blockaddress");
3180
3181 // Try to find the function (but skip it if it's forward-referenced).
3182 GlobalValue *GV = nullptr;
3183 if (Fn.Kind == ValID::t_GlobalID) {
3184 if (Fn.UIntVal < NumberedVals.size())
3185 GV = NumberedVals[Fn.UIntVal];
3186 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3187 GV = M->getNamedValue(Fn.StrVal);
3188 }
3189 Function *F = nullptr;
3190 if (GV) {
3191 // Confirm that it's actually a function with a definition.
3192 if (!isa<Function>(GV))
3193 return error(Fn.Loc, "expected function name in blockaddress");
3194 F = cast<Function>(GV);
3195 if (F->isDeclaration())
3196 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3197 }
3198
3199 if (!F) {
3200 // Make a global variable as a placeholder for this reference.
3201 GlobalValue *&FwdRef =
3202 ForwardRefBlockAddresses.insert(std::make_pair(
3203 std::move(Fn),
3204 std::map<ValID, GlobalValue *>()))
3205 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3206 .first->second;
3207 if (!FwdRef) {
3208 unsigned FwdDeclAS;
3209 if (ExpectedTy) {
3210 // If we know the type that the blockaddress is being assigned to,
3211 // we can use the address space of that type.
3212 if (!ExpectedTy->isPointerTy())
3213 return error(ID.Loc,
3214 "type of blockaddress must be a pointer and not '" +
3215 getTypeString(ExpectedTy) + "'");
3216 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3217 } else if (PFS) {
3218 // Otherwise, we default the address space of the current function.
3219 FwdDeclAS = PFS->getFunction().getAddressSpace();
3220 } else {
3221 llvm_unreachable("Unknown address space for blockaddress")__builtin_unreachable();
3222 }
3223 FwdRef = new GlobalVariable(
3224 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3225 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3226 }
3227
3228 ID.ConstantVal = FwdRef;
3229 ID.Kind = ValID::t_Constant;
3230 return false;
3231 }
3232
3233 // We found the function; now find the basic block. Don't use PFS, since we
3234 // might be inside a constant expression.
3235 BasicBlock *BB;
3236 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3237 if (Label.Kind == ValID::t_LocalID)
3238 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3239 else
3240 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3241 if (!BB)
3242 return error(Label.Loc, "referenced value is not a basic block");
3243 } else {
3244 if (Label.Kind == ValID::t_LocalID)
3245 return error(Label.Loc, "cannot take address of numeric label after "
3246 "the function is defined");
3247 BB = dyn_cast_or_null<BasicBlock>(
3248 F->getValueSymbolTable()->lookup(Label.StrVal));
3249 if (!BB)
3250 return error(Label.Loc, "referenced value is not a basic block");
3251 }
3252
3253 ID.ConstantVal = BlockAddress::get(F, BB);
3254 ID.Kind = ValID::t_Constant;
3255 return false;
3256 }
3257
3258 case lltok::kw_dso_local_equivalent: {
3259 // ValID ::= 'dso_local_equivalent' @foo
3260 Lex.Lex();
3261
3262 ValID Fn;
3263
3264 if (parseValID(Fn, PFS))
2
Assuming the condition is false
3
Taking false branch
3265 return true;
3266
3267 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
4
Assuming field 'Kind' is equal to t_GlobalID
3268 return error(Fn.Loc,
3269 "expected global value name in dso_local_equivalent");
3270
3271 // Try to find the function (but skip it if it's forward-referenced).
3272 GlobalValue *GV = nullptr;
5
'GV' initialized to a null pointer value
3273 if (Fn.Kind
5.1
Field 'Kind' is equal to t_GlobalID
== ValID::t_GlobalID) {
6
Taking true branch
3274 if (Fn.UIntVal < NumberedVals.size())
7
Assuming the condition is false
8
Taking false branch
3275 GV = NumberedVals[Fn.UIntVal];
3276 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3277 GV = M->getNamedValue(Fn.StrVal);
3278 }
3279
3280 assert(GV && "Could not find a corresponding global variable")((void)0);
3281
3282 if (!GV->getValueType()->isFunctionTy())
9
Called C++ object pointer is null
3283 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3284 "in dso_local_equivalent");
3285
3286 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3287 ID.Kind = ValID::t_Constant;
3288 return false;
3289 }
3290
3291 case lltok::kw_trunc:
3292 case lltok::kw_zext:
3293 case lltok::kw_sext:
3294 case lltok::kw_fptrunc:
3295 case lltok::kw_fpext:
3296 case lltok::kw_bitcast:
3297 case lltok::kw_addrspacecast:
3298 case lltok::kw_uitofp:
3299 case lltok::kw_sitofp:
3300 case lltok::kw_fptoui:
3301 case lltok::kw_fptosi:
3302 case lltok::kw_inttoptr:
3303 case lltok::kw_ptrtoint: {
3304 unsigned Opc = Lex.getUIntVal();
3305 Type *DestTy = nullptr;
3306 Constant *SrcVal;
3307 Lex.Lex();
3308 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3309 parseGlobalTypeAndValue(SrcVal) ||
3310 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3311 parseType(DestTy) ||
3312 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3313 return true;
3314 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3315 return error(ID.Loc, "invalid cast opcode for cast from '" +
3316 getTypeString(SrcVal->getType()) + "' to '" +
3317 getTypeString(DestTy) + "'");
3318 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3319 SrcVal, DestTy);
3320 ID.Kind = ValID::t_Constant;
3321 return false;
3322 }
3323 case lltok::kw_extractvalue: {
3324 Lex.Lex();
3325 Constant *Val;
3326 SmallVector<unsigned, 4> Indices;
3327 if (parseToken(lltok::lparen,
3328 "expected '(' in extractvalue constantexpr") ||
3329 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3330 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3331 return true;
3332
3333 if (!Val->getType()->isAggregateType())
3334 return error(ID.Loc, "extractvalue operand must be aggregate type");
3335 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3336 return error(ID.Loc, "invalid indices for extractvalue");
3337 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3338 ID.Kind = ValID::t_Constant;
3339 return false;
3340 }
3341 case lltok::kw_insertvalue: {
3342 Lex.Lex();
3343 Constant *Val0, *Val1;
3344 SmallVector<unsigned, 4> Indices;
3345 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3346 parseGlobalTypeAndValue(Val0) ||
3347 parseToken(lltok::comma,
3348 "expected comma in insertvalue constantexpr") ||
3349 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3350 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3351 return true;
3352 if (!Val0->getType()->isAggregateType())
3353 return error(ID.Loc, "insertvalue operand must be aggregate type");
3354 Type *IndexedType =
3355 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3356 if (!IndexedType)
3357 return error(ID.Loc, "invalid indices for insertvalue");
3358 if (IndexedType != Val1->getType())
3359 return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3360 getTypeString(Val1->getType()) +
3361 "' instead of '" + getTypeString(IndexedType) +
3362 "'");
3363 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3364 ID.Kind = ValID::t_Constant;
3365 return false;
3366 }
3367 case lltok::kw_icmp:
3368 case lltok::kw_fcmp: {
3369 unsigned PredVal, Opc = Lex.getUIntVal();
3370 Constant *Val0, *Val1;
3371 Lex.Lex();
3372 if (parseCmpPredicate(PredVal, Opc) ||
3373 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3374 parseGlobalTypeAndValue(Val0) ||
3375 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3376 parseGlobalTypeAndValue(Val1) ||
3377 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3378 return true;
3379
3380 if (Val0->getType() != Val1->getType())
3381 return error(ID.Loc, "compare operands must have the same type");
3382
3383 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3384
3385 if (Opc == Instruction::FCmp) {
3386 if (!Val0->getType()->isFPOrFPVectorTy())
3387 return error(ID.Loc, "fcmp requires floating point operands");
3388 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3389 } else {
3390 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!")((void)0);
3391 if (!Val0->getType()->isIntOrIntVectorTy() &&
3392 !Val0->getType()->isPtrOrPtrVectorTy())
3393 return error(ID.Loc, "icmp requires pointer or integer operands");
3394 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3395 }
3396 ID.Kind = ValID::t_Constant;
3397 return false;
3398 }
3399
3400 // Unary Operators.
3401 case lltok::kw_fneg: {
3402 unsigned Opc = Lex.getUIntVal();
3403 Constant *Val;
3404 Lex.Lex();
3405 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3406 parseGlobalTypeAndValue(Val) ||
3407 parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3408 return true;
3409
3410 // Check that the type is valid for the operator.
3411 switch (Opc) {
3412 case Instruction::FNeg:
3413 if (!Val->getType()->isFPOrFPVectorTy())
3414 return error(ID.Loc, "constexpr requires fp operands");
3415 break;
3416 default: llvm_unreachable("Unknown unary operator!")__builtin_unreachable();
3417 }
3418 unsigned Flags = 0;
3419 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3420 ID.ConstantVal = C;
3421 ID.Kind = ValID::t_Constant;
3422 return false;
3423 }
3424 // Binary Operators.
3425 case lltok::kw_add:
3426 case lltok::kw_fadd:
3427 case lltok::kw_sub:
3428 case lltok::kw_fsub:
3429 case lltok::kw_mul:
3430 case lltok::kw_fmul:
3431 case lltok::kw_udiv:
3432 case lltok::kw_sdiv:
3433 case lltok::kw_fdiv:
3434 case lltok::kw_urem:
3435 case lltok::kw_srem:
3436 case lltok::kw_frem:
3437 case lltok::kw_shl:
3438 case lltok::kw_lshr:
3439 case lltok::kw_ashr: {
3440 bool NUW = false;
3441 bool NSW = false;
3442 bool Exact = false;
3443 unsigned Opc = Lex.getUIntVal();
3444 Constant *Val0, *Val1;
3445 Lex.Lex();
3446 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3447 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3448 if (EatIfPresent(lltok::kw_nuw))
3449 NUW = true;
3450 if (EatIfPresent(lltok::kw_nsw)) {
3451 NSW = true;
3452 if (EatIfPresent(lltok::kw_nuw))
3453 NUW = true;
3454 }
3455 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3456 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3457 if (EatIfPresent(lltok::kw_exact))
3458 Exact = true;
3459 }
3460 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3461 parseGlobalTypeAndValue(Val0) ||
3462 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3463 parseGlobalTypeAndValue(Val1) ||
3464 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3465 return true;
3466 if (Val0->getType() != Val1->getType())
3467 return error(ID.Loc, "operands of constexpr must have same type");
3468 // Check that the type is valid for the operator.
3469 switch (Opc) {
3470 case Instruction::Add:
3471 case Instruction::Sub:
3472 case Instruction::Mul:
3473 case Instruction::UDiv:
3474 case Instruction::SDiv:
3475 case Instruction::URem:
3476 case Instruction::SRem:
3477 case Instruction::Shl:
3478 case Instruction::AShr:
3479 case Instruction::LShr:
3480 if (!Val0->getType()->isIntOrIntVectorTy())
3481 return error(ID.Loc, "constexpr requires integer operands");
3482 break;
3483 case Instruction::FAdd:
3484 case Instruction::FSub:
3485 case Instruction::FMul:
3486 case Instruction::FDiv:
3487 case Instruction::FRem:
3488 if (!Val0->getType()->isFPOrFPVectorTy())
3489 return error(ID.Loc, "constexpr requires fp operands");
3490 break;
3491 default: llvm_unreachable("Unknown binary operator!")__builtin_unreachable();
3492 }
3493 unsigned Flags = 0;
3494 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3495 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3496 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3497 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3498 ID.ConstantVal = C;
3499 ID.Kind = ValID::t_Constant;
3500 return false;
3501 }
3502
3503 // Logical Operations
3504 case lltok::kw_and:
3505 case lltok::kw_or:
3506 case lltok::kw_xor: {
3507 unsigned Opc = Lex.getUIntVal();
3508 Constant *Val0, *Val1;
3509 Lex.Lex();
3510 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3511 parseGlobalTypeAndValue(Val0) ||
3512 parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3513 parseGlobalTypeAndValue(Val1) ||
3514 parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3515 return true;
3516 if (Val0->getType() != Val1->getType())
3517 return error(ID.Loc, "operands of constexpr must have same type");
3518 if (!Val0->getType()->isIntOrIntVectorTy())
3519 return error(ID.Loc,
3520 "constexpr requires integer or integer vector operands");
3521 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3522 ID.Kind = ValID::t_Constant;
3523 return false;
3524 }
3525
3526 case lltok::kw_getelementptr:
3527 case lltok::kw_shufflevector:
3528 case lltok::kw_insertelement:
3529 case lltok::kw_extractelement:
3530 case lltok::kw_select: {
3531 unsigned Opc = Lex.getUIntVal();
3532 SmallVector<Constant*, 16> Elts;
3533 bool InBounds = false;
3534 Type *Ty;
3535 Lex.Lex();
3536
3537 if (Opc == Instruction::GetElementPtr)
3538 InBounds = EatIfPresent(lltok::kw_inbounds);
3539
3540 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3541 return true;
3542
3543 LocTy ExplicitTypeLoc = Lex.getLoc();
3544 if (Opc == Instruction::GetElementPtr) {
3545 if (parseType(Ty) ||
3546 parseToken(lltok::comma, "expected comma after getelementptr's type"))
3547 return true;
3548 }
3549
3550 Optional<unsigned> InRangeOp;
3551 if (parseGlobalValueVector(
3552 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3553 parseToken(lltok::rparen, "expected ')' in constantexpr"))
3554 return true;
3555
3556 if (Opc == Instruction::GetElementPtr) {
3557 if (Elts.size() == 0 ||
3558 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3559 return error(ID.Loc, "base of getelementptr must be a pointer");
3560
3561 Type *BaseType = Elts[0]->getType();
3562 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3563 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3564 return error(
3565 ExplicitTypeLoc,
3566 typeComparisonErrorMessage(
3567 "explicit pointee type doesn't match operand's pointee type",
3568 Ty, BasePointerType->getElementType()));
3569 }
3570
3571 unsigned GEPWidth =
3572 BaseType->isVectorTy()
3573 ? cast<FixedVectorType>(BaseType)->getNumElements()
3574 : 0;
3575
3576 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3577 for (Constant *Val : Indices) {
3578 Type *ValTy = Val->getType();
3579 if (!ValTy->isIntOrIntVectorTy())
3580 return error(ID.Loc, "getelementptr index must be an integer");
3581 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3582 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3583 if (GEPWidth && (ValNumEl != GEPWidth))
3584 return error(
3585 ID.Loc,
3586 "getelementptr vector index has a wrong number of elements");
3587 // GEPWidth may have been unknown because the base is a scalar,
3588 // but it is known now.
3589 GEPWidth = ValNumEl;
3590 }
3591 }
3592
3593 SmallPtrSet<Type*, 4> Visited;
3594 if (!Indices.empty() && !Ty->isSized(&Visited))
3595 return error(ID.Loc, "base element of getelementptr must be sized");
3596
3597 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3598 return error(ID.Loc, "invalid getelementptr indices");
3599
3600 if (InRangeOp) {
3601 if (*InRangeOp == 0)
3602 return error(ID.Loc,
3603 "inrange keyword may not appear on pointer operand");
3604 --*InRangeOp;
3605 }
3606
3607 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3608 InBounds, InRangeOp);
3609 } else if (Opc == Instruction::Select) {
3610 if (Elts.size() != 3)
3611 return error(ID.Loc, "expected three operands to select");
3612 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3613 Elts[2]))
3614 return error(ID.Loc, Reason);
3615 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3616 } else if (Opc == Instruction::ShuffleVector) {
3617 if (Elts.size() != 3)
3618 return error(ID.Loc, "expected three operands to shufflevector");
3619 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3620 return error(ID.Loc, "invalid operands to shufflevector");
3621 SmallVector<int, 16> Mask;
3622 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3623 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3624 } else if (Opc == Instruction::ExtractElement) {
3625 if (Elts.size() != 2)
3626 return error(ID.Loc, "expected two operands to extractelement");
3627 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3628 return error(ID.Loc, "invalid extractelement operands");
3629 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3630 } else {
3631 assert(Opc == Instruction::InsertElement && "Unknown opcode")((void)0);
3632 if (Elts.size() != 3)
3633 return error(ID.Loc, "expected three operands to insertelement");
3634 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3635 return error(ID.Loc, "invalid insertelement operands");
3636 ID.ConstantVal =
3637 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3638 }
3639
3640 ID.Kind = ValID::t_Constant;
3641 return false;
3642 }
3643 }
3644
3645 Lex.Lex();
3646 return false;
3647}
3648
3649/// parseGlobalValue - parse a global value with the specified type.
3650bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3651 C = nullptr;
3652 ValID ID;
3653 Value *V = nullptr;
3654 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3655 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3656 if (V && !(C = dyn_cast<Constant>(V)))
3657 return error(ID.Loc, "global values must be constants");
3658 return Parsed;
3659}
3660
3661bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3662 Type *Ty = nullptr;
3663 return parseType(Ty) || parseGlobalValue(Ty, V);
3664}
3665
3666bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3667 C = nullptr;
3668
3669 LocTy KwLoc = Lex.getLoc();
3670 if (!EatIfPresent(lltok::kw_comdat))
3671 return false;
3672
3673 if (EatIfPresent(lltok::lparen)) {
3674 if (Lex.getKind() != lltok::ComdatVar)
3675 return tokError("expected comdat variable");
3676 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3677 Lex.Lex();
3678 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3679 return true;
3680 } else {
3681 if (GlobalName.empty())
3682 return tokError("comdat cannot be unnamed");
3683 C = getComdat(std::string(GlobalName), KwLoc);
3684 }
3685
3686 return false;
3687}
3688
3689/// parseGlobalValueVector
3690/// ::= /*empty*/
3691/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3692bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3693 Optional<unsigned> *InRangeOp) {
3694 // Empty list.
3695 if (Lex.getKind() == lltok::rbrace ||
3696 Lex.getKind() == lltok::rsquare ||
3697 Lex.getKind() == lltok::greater ||
3698 Lex.getKind() == lltok::rparen)
3699 return false;
3700
3701 do {
3702 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3703 *InRangeOp = Elts.size();
3704
3705 Constant *C;
3706 if (parseGlobalTypeAndValue(C))
3707 return true;
3708 Elts.push_back(C);
3709 } while (EatIfPresent(lltok::comma));
3710
3711 return false;
3712}
3713
3714bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3715 SmallVector<Metadata *, 16> Elts;
3716 if (parseMDNodeVector(Elts))
3717 return true;
3718
3719 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3720 return false;
3721}
3722
3723/// MDNode:
3724/// ::= !{ ... }
3725/// ::= !7
3726/// ::= !DILocation(...)
3727bool LLParser::parseMDNode(MDNode *&N) {
3728 if (Lex.getKind() == lltok::MetadataVar)
3729 return parseSpecializedMDNode(N);
3730
3731 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3732}
3733
3734bool LLParser::parseMDNodeTail(MDNode *&N) {
3735 // !{ ... }
3736 if (Lex.getKind() == lltok::lbrace)
3737 return parseMDTuple(N);
3738
3739 // !42
3740 return parseMDNodeID(N);
3741}
3742
3743namespace {
3744
3745/// Structure to represent an optional metadata field.
3746template <class FieldTy> struct MDFieldImpl {
3747 typedef MDFieldImpl ImplTy;
3748 FieldTy Val;
3749 bool Seen;
3750
3751 void assign(FieldTy Val) {
3752 Seen = true;
3753 this->Val = std::move(Val);
3754 }
3755
3756 explicit MDFieldImpl(FieldTy Default)
3757 : Val(std::move(Default)), Seen(false) {}
3758};
3759
3760/// Structure to represent an optional metadata field that
3761/// can be of either type (A or B) and encapsulates the
3762/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3763/// to reimplement the specifics for representing each Field.
3764template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3765 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3766 FieldTypeA A;
3767 FieldTypeB B;
3768 bool Seen;
3769
3770 enum {
3771 IsInvalid = 0,
3772 IsTypeA = 1,
3773 IsTypeB = 2
3774 } WhatIs;
3775
3776 void assign(FieldTypeA A) {
3777 Seen = true;
3778 this->A = std::move(A);
3779 WhatIs = IsTypeA;
3780 }
3781
3782 void assign(FieldTypeB B) {
3783 Seen = true;
3784 this->B = std::move(B);
3785 WhatIs = IsTypeB;
3786 }
3787
3788 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3789 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3790 WhatIs(IsInvalid) {}
3791};
3792
3793struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3794 uint64_t Max;
3795
3796 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX0xffffffffffffffffULL)
3797 : ImplTy(Default), Max(Max) {}
3798};
3799
3800struct LineField : public MDUnsignedField {
3801 LineField() : MDUnsignedField(0, UINT32_MAX0xffffffffU) {}
3802};
3803
3804struct ColumnField : public MDUnsignedField {
3805 ColumnField() : MDUnsignedField(0, UINT16_MAX0xffff) {}
3806};
3807
3808struct DwarfTagField : public MDUnsignedField {
3809 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3810 DwarfTagField(dwarf::Tag DefaultTag)
3811 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3812};
3813
3814struct DwarfMacinfoTypeField : public MDUnsignedField {
3815 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3816 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3817 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3818};
3819
3820struct DwarfAttEncodingField : public MDUnsignedField {
3821 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3822};
3823
3824struct DwarfVirtualityField : public MDUnsignedField {
3825 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3826};
3827
3828struct DwarfLangField : public MDUnsignedField {
3829 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3830};
3831
3832struct DwarfCCField : public MDUnsignedField {
3833 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3834};
3835
3836struct EmissionKindField : public MDUnsignedField {
3837 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3838};
3839
3840struct NameTableKindField : public MDUnsignedField {
3841 NameTableKindField()
3842 : MDUnsignedField(
3843 0, (unsigned)
3844 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3845};
3846
3847struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3848 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3849};
3850
3851struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3852 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3853};
3854
3855struct MDAPSIntField : public MDFieldImpl<APSInt> {
3856 MDAPSIntField() : ImplTy(APSInt()) {}
3857};
3858
3859struct MDSignedField : public MDFieldImpl<int64_t> {
3860 int64_t Min;
3861 int64_t Max;
3862
3863 MDSignedField(int64_t Default = 0)
3864 : ImplTy(Default), Min(INT64_MIN(-0x7fffffffffffffffLL - 1)), Max(INT64_MAX0x7fffffffffffffffLL) {}
3865 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3866 : ImplTy(Default), Min(Min), Max(Max) {}
3867};
3868
3869struct MDBoolField : public MDFieldImpl<bool> {
3870 MDBoolField(bool Default = false) : ImplTy(Default) {}
3871};
3872
3873struct MDField : public MDFieldImpl<Metadata *> {
3874 bool AllowNull;
3875
3876 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3877};
3878
3879struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3880 MDConstant() : ImplTy(nullptr) {}
3881};
3882
3883struct MDStringField : public MDFieldImpl<MDString *> {
3884 bool AllowEmpty;
3885 MDStringField(bool AllowEmpty = true)
3886 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3887};
3888
3889struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3890 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3891};
3892
3893struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3894 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3895};
3896
3897struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3898 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3899 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3900
3901 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3902 bool AllowNull = true)
3903 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3904
3905 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3906 bool isMDField() const { return WhatIs == IsTypeB; }
3907 int64_t getMDSignedValue() const {
3908 assert(isMDSignedField() && "Wrong field type")((void)0);
3909 return A.Val;
3910 }
3911 Metadata *getMDFieldValue() const {
3912 assert(isMDField() && "Wrong field type")((void)0);
3913 return B.Val;
3914 }
3915};
3916
3917struct MDSignedOrUnsignedField
3918 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3919 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3920
3921 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3922 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3923 int64_t getMDSignedValue() const {
3924 assert(isMDSignedField() && "Wrong field type")((void)0);
3925 return A.Val;
3926 }
3927 uint64_t getMDUnsignedValue() const {
3928 assert(isMDUnsignedField() && "Wrong field type")((void)0);
3929 return B.Val;
3930 }
3931};
3932
3933} // end anonymous namespace
3934
3935namespace llvm {
3936
3937template <>
3938bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
3939 if (Lex.getKind() != lltok::APSInt)
3940 return tokError("expected integer");
3941
3942 Result.assign(Lex.getAPSIntVal());
3943 Lex.Lex();
3944 return false;
3945}
3946
3947template <>
3948bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3949 MDUnsignedField &Result) {
3950 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3951 return tokError("expected unsigned integer");
3952
3953 auto &U = Lex.getAPSIntVal();
3954 if (U.ugt(Result.Max))
3955 return tokError("value for '" + Name + "' too large, limit is " +
3956 Twine(Result.Max));
3957 Result.assign(U.getZExtValue());
3958 assert(Result.Val <= Result.Max && "Expected value in range")((void)0);
3959 Lex.Lex();
3960 return false;
3961}
3962
3963template <>
3964bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3965 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3966}
3967template <>
3968bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3969 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3970}
3971
3972template <>
3973bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3974 if (Lex.getKind() == lltok::APSInt)
3975 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3976
3977 if (Lex.getKind() != lltok::DwarfTag)
3978 return tokError("expected DWARF tag");
3979
3980 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3981 if (Tag == dwarf::DW_TAG_invalid)
3982 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3983 assert(Tag <= Result.Max && "Expected valid DWARF tag")((void)0);
3984
3985 Result.assign(Tag);
3986 Lex.Lex();
3987 return false;
3988}
3989
3990template <>
3991bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3992 DwarfMacinfoTypeField &Result) {
3993 if (Lex.getKind() == lltok::APSInt)
3994 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3995
3996 if (Lex.getKind() != lltok::DwarfMacinfo)
3997 return tokError("expected DWARF macinfo type");
3998
3999 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4000 if (Macinfo == dwarf::DW_MACINFO_invalid)
4001 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4002 Lex.getStrVal() + "'");
4003 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type")((void)0);
4004
4005 Result.assign(Macinfo);
4006 Lex.Lex();
4007 return false;
4008}
4009
4010template <>
4011bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4012 DwarfVirtualityField &Result) {
4013 if (Lex.getKind() == lltok::APSInt)
4014 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4015
4016 if (Lex.getKind() != lltok::DwarfVirtuality)
4017 return tokError("expected DWARF virtuality code");
4018
4019 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4020 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4021 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4022 Lex.getStrVal() + "'");
4023 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code")((void)0);
4024 Result.assign(Virtuality);
4025 Lex.Lex();
4026 return false;
4027}
4028
4029template <>
4030bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4031 if (Lex.getKind() == lltok::APSInt)
4032 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4033
4034 if (Lex.getKind() != lltok::DwarfLang)
4035 return tokError("expected DWARF language");
4036
4037 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4038 if (!Lang)
4039 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4040 "'");
4041 assert(Lang <= Result.Max && "Expected valid DWARF language")((void)0);
4042 Result.assign(Lang);
4043 Lex.Lex();
4044 return false;
4045}
4046
4047template <>
4048bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4049 if (Lex.getKind() == lltok::APSInt)
4050 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4051
4052 if (Lex.getKind() != lltok::DwarfCC)
4053 return tokError("expected DWARF calling convention");
4054
4055 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4056 if (!CC)
4057 return tokError("invalid DWARF calling convention" + Twine(" '") +
4058 Lex.getStrVal() + "'");
4059 assert(CC <= Result.Max && "Expected valid DWARF calling convention")((void)0);
4060 Result.assign(CC);
4061 Lex.Lex();
4062 return false;
4063}
4064
4065template <>
4066bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4067 EmissionKindField &Result) {
4068 if (Lex.getKind() == lltok::APSInt)
4069 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4070
4071 if (Lex.getKind() != lltok::EmissionKind)
4072 return tokError("expected emission kind");
4073
4074 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4075 if (!Kind)
4076 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4077 "'");
4078 assert(*Kind <= Result.Max && "Expected valid emission kind")((void)0);
4079 Result.assign(*Kind);
4080 Lex.Lex();
4081 return false;
4082}
4083
4084template <>
4085bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4086 NameTableKindField &Result) {
4087 if (Lex.getKind() == lltok::APSInt)
4088 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4089
4090 if (Lex.getKind() != lltok::NameTableKind)
4091 return tokError("expected nameTable kind");
4092
4093 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4094 if (!Kind)
4095 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4096 "'");
4097 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind")((void)0);
4098 Result.assign((unsigned)*Kind);
4099 Lex.Lex();
4100 return false;
4101}
4102
4103template <>
4104bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4105 DwarfAttEncodingField &Result) {
4106 if (Lex.getKind() == lltok::APSInt)
4107 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4108
4109 if (Lex.getKind() != lltok::DwarfAttEncoding)
4110 return tokError("expected DWARF type attribute encoding");
4111
4112 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4113 if (!Encoding)
4114 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4115 Lex.getStrVal() + "'");
4116 assert(Encoding <= Result.Max && "Expected valid DWARF language")((void)0);
4117 Result.assign(Encoding);
4118 Lex.Lex();
4119 return false;
4120}
4121
4122/// DIFlagField
4123/// ::= uint32
4124/// ::= DIFlagVector
4125/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4126template <>
4127bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4128
4129 // parser for a single flag.
4130 auto parseFlag = [&](DINode::DIFlags &Val) {
4131 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4132 uint32_t TempVal = static_cast<uint32_t>(Val);
4133 bool Res = parseUInt32(TempVal);
4134 Val = static_cast<DINode::DIFlags>(TempVal);
4135 return Res;
4136 }
4137
4138 if (Lex.getKind() != lltok::DIFlag)
4139 return tokError("expected debug info flag");
4140
4141 Val = DINode::getFlag(Lex.getStrVal());
4142 if (!Val)
4143 return tokError(Twine("invalid debug info flag flag '") +
4144 Lex.getStrVal() + "'");
4145 Lex.Lex();
4146 return false;
4147 };
4148
4149 // parse the flags and combine them together.
4150 DINode::DIFlags Combined = DINode::FlagZero;
4151 do {
4152 DINode::DIFlags Val;
4153 if (parseFlag(Val))
4154 return true;
4155 Combined |= Val;
4156 } while (EatIfPresent(lltok::bar));
4157
4158 Result.assign(Combined);
4159 return false;
4160}
4161
4162/// DISPFlagField
4163/// ::= uint32
4164/// ::= DISPFlagVector
4165/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4166template <>
4167bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4168
4169 // parser for a single flag.
4170 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4171 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4172 uint32_t TempVal = static_cast<uint32_t>(Val);
4173 bool Res = parseUInt32(TempVal);
4174 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4175 return Res;
4176 }
4177
4178 if (Lex.getKind() != lltok::DISPFlag)
4179 return tokError("expected debug info flag");
4180
4181 Val = DISubprogram::getFlag(Lex.getStrVal());
4182 if (!Val)
4183 return tokError(Twine("invalid subprogram debug info flag '") +
4184 Lex.getStrVal() + "'");
4185 Lex.Lex();
4186 return false;
4187 };
4188
4189 // parse the flags and combine them together.
4190 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4191 do {
4192 DISubprogram::DISPFlags Val;
4193 if (parseFlag(Val))
4194 return true;
4195 Combined |= Val;
4196 } while (EatIfPresent(lltok::bar));
4197
4198 Result.assign(Combined);
4199 return false;
4200}
4201
4202template <>
4203bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4204 if (Lex.getKind() != lltok::APSInt)
4205 return tokError("expected signed integer");
4206
4207 auto &S = Lex.getAPSIntVal();
4208 if (S < Result.Min)
4209 return tokError("value for '" + Name + "' too small, limit is " +
4210 Twine(Result.Min));
4211 if (S > Result.Max)
4212 return tokError("value for '" + Name + "' too large, limit is " +
4213 Twine(Result.Max));
4214 Result.assign(S.getExtValue());
4215 assert(Result.Val >= Result.Min && "Expected value in range")((void)0);
4216 assert(Result.Val <= Result.Max && "Expected value in range")((void)0);
4217 Lex.Lex();
4218 return false;
4219}
4220
4221template <>
4222bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4223 switch (Lex.getKind()) {
4224 default:
4225 return tokError("expected 'true' or 'false'");
4226 case lltok::kw_true:
4227 Result.assign(true);
4228 break;
4229 case lltok::kw_false:
4230 Result.assign(false);
4231 break;
4232 }
4233 Lex.Lex();
4234 return false;
4235}
4236
4237template <>
4238bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4239 if (Lex.getKind() == lltok::kw_null) {
4240 if (!Result.AllowNull)
4241 return tokError("'" + Name + "' cannot be null");
4242 Lex.Lex();
4243 Result.assign(nullptr);
4244 return false;
4245 }
4246
4247 Metadata *MD;
4248 if (parseMetadata(MD, nullptr))
4249 return true;
4250
4251 Result.assign(MD);
4252 return false;
4253}
4254
4255template <>
4256bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4257 MDSignedOrMDField &Result) {
4258 // Try to parse a signed int.
4259 if (Lex.getKind() == lltok::APSInt) {
4260 MDSignedField Res = Result.A;
4261 if (!parseMDField(Loc, Name, Res)) {
4262 Result.assign(Res);
4263 return false;
4264 }
4265 return true;
4266 }
4267
4268 // Otherwise, try to parse as an MDField.
4269 MDField Res = Result.B;
4270 if (!parseMDField(Loc, Name, Res)) {
4271 Result.assign(Res);
4272 return false;
4273 }
4274
4275 return true;
4276}
4277
4278template <>
4279bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4280 LocTy ValueLoc = Lex.getLoc();
4281 std::string S;
4282 if (parseStringConstant(S))
4283 return true;
4284
4285 if (!Result.AllowEmpty && S.empty())
4286 return error(ValueLoc, "'" + Name + "' cannot be empty");
4287
4288 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4289 return false;
4290}
4291
4292template <>
4293bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4294 SmallVector<Metadata *, 4> MDs;
4295 if (parseMDNodeVector(MDs))
4296 return true;
4297
4298 Result.assign(std::move(MDs));
4299 return false;
4300}
4301
4302template <>
4303bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4304 ChecksumKindField &Result) {
4305 Optional<DIFile::ChecksumKind> CSKind =
4306 DIFile::getChecksumKind(Lex.getStrVal());
4307
4308 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4309 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4310 "'");
4311
4312 Result.assign(*CSKind);
4313 Lex.Lex();
4314 return false;
4315}
4316
4317} // end namespace llvm
4318
4319template <class ParserTy>
4320bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4321 do {
4322 if (Lex.getKind() != lltok::LabelStr)
4323 return tokError("expected field label here");
4324
4325 if (ParseField())
4326 return true;
4327 } while (EatIfPresent(lltok::comma));
4328
4329 return false;
4330}
4331
4332template <class ParserTy>
4333bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4334 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
4335 Lex.Lex();
4336
4337 if (parseToken(lltok::lparen, "expected '(' here"))
4338 return true;
4339 if (Lex.getKind() != lltok::rparen)
4340 if (parseMDFieldsImplBody(ParseField))
4341 return true;
4342
4343 ClosingLoc = Lex.getLoc();
4344 return parseToken(lltok::rparen, "expected ')' here");
4345}
4346
4347template <class FieldTy>
4348bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4349 if (Result.Seen)
4350 return tokError("field '" + Name + "' cannot be specified more than once");
4351
4352 LocTy Loc = Lex.getLoc();
4353 Lex.Lex();
4354 return parseMDField(Loc, Name, Result);
4355}
4356
4357bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4358 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
4359
4360#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4361 if (Lex.getStrVal() == #CLASS) \
4362 return parse##CLASS(N, IsDistinct);
4363#include "llvm/IR/Metadata.def"
4364
4365 return tokError("expected metadata type");
4366}
4367
4368#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4369#define NOP_FIELD(NAME, TYPE, INIT)
4370#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4371 if (!NAME.Seen) \
4372 return error(ClosingLoc, "missing required field '" #NAME "'");
4373#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4374 if (Lex.getStrVal() == #NAME) \
4375 return parseMDField(#NAME, NAME);
4376#define PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
\
4377 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4378 do { \
4379 LocTy ClosingLoc; \
4380 if (parseMDFieldsImpl( \
4381 [&]() -> bool { \
4382 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4383 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4384 "'"); \
4385 }, \
4386 ClosingLoc)) \
4387 return true; \
4388 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4389 } while (false)
4390#define GET_OR_DISTINCT(CLASS, ARGS)(IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) \
4391 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4392
4393/// parseDILocationFields:
4394/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4395/// isImplicitCode: true)
4396bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4397#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4398 OPTIONAL(line, LineField, ); \
4399 OPTIONAL(column, ColumnField, ); \
4400 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4401 OPTIONAL(inlinedAt, MDField, ); \
4402 OPTIONAL(isImplicitCode, MDBoolField, (false));
4403 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4404#undef VISIT_MD_FIELDS
4405
4406 Result =
4407 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
4408 inlinedAt.Val, isImplicitCode.Val))(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
;
4409 return false;
4410}
4411
4412/// parseGenericDINode:
4413/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4414bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4415#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4416 REQUIRED(tag, DwarfTagField, ); \
4417 OPTIONAL(header, MDStringField, ); \
4418 OPTIONAL(operands, MDFieldList, );
4419 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4420#undef VISIT_MD_FIELDS
4421
4422 Result = GET_OR_DISTINCT(GenericDINode,(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
4423 (Context, tag.Val, header.Val, operands.Val))(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
;
4424 return false;
4425}
4426
4427/// parseDISubrange:
4428/// ::= !DISubrange(count: 30, lowerBound: 2)
4429/// ::= !DISubrange(count: !node, lowerBound: 2)
4430/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4431bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4432#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4433 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX0x7fffffffffffffffLL, false)); \
4434 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4435 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4436 OPTIONAL(stride, MDSignedOrMDField, );
4437 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4438#undef VISIT_MD_FIELDS
4439
4440 Metadata *Count = nullptr;
4441 Metadata *LowerBound = nullptr;
4442 Metadata *UpperBound = nullptr;
4443 Metadata *Stride = nullptr;
4444
4445 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4446 if (Bound.isMDSignedField())
4447 return ConstantAsMetadata::get(ConstantInt::getSigned(
4448 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4449 if (Bound.isMDField())
4450 return Bound.getMDFieldValue();
4451 return nullptr;
4452 };
4453
4454 Count = convToMetadata(count);
4455 LowerBound = convToMetadata(lowerBound);
4456 UpperBound = convToMetadata(upperBound);
4457 Stride = convToMetadata(stride);
4458
4459 Result = GET_OR_DISTINCT(DISubrange,(IsDistinct ? DISubrange::getDistinct (Context, Count, LowerBound
, UpperBound, Stride) : DISubrange::get (Context, Count, LowerBound
, UpperBound, Stride))
4460 (Context, Count, LowerBound, UpperBound, Stride))(IsDistinct ? DISubrange::getDistinct (Context, Count, LowerBound
, UpperBound, Stride) : DISubrange::get (Context, Count, LowerBound
, UpperBound, Stride))
;
4461
4462 return false;
4463}
4464
4465/// parseDIGenericSubrange:
4466/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4467/// !node3)
4468bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4469#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4470 OPTIONAL(count, MDSignedOrMDField, ); \
4471 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4472 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4473 OPTIONAL(stride, MDSignedOrMDField, );
4474 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4475#undef VISIT_MD_FIELDS
4476
4477 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4478 if (Bound.isMDSignedField())
4479 return DIExpression::get(
4480 Context, {dwarf::DW_OP_consts,
4481 static_cast<uint64_t>(Bound.getMDSignedValue())});
4482 if (Bound.isMDField())
4483 return Bound.getMDFieldValue();
4484 return nullptr;
4485 };
4486
4487 Metadata *Count = ConvToMetadata(count);
4488 Metadata *LowerBound = ConvToMetadata(lowerBound);
4489 Metadata *UpperBound = ConvToMetadata(upperBound);
4490 Metadata *Stride = ConvToMetadata(stride);
4491
4492 Result = GET_OR_DISTINCT(DIGenericSubrange,(IsDistinct ? DIGenericSubrange::getDistinct (Context, Count,
LowerBound, UpperBound, Stride) : DIGenericSubrange::get (Context
, Count, LowerBound, UpperBound, Stride))
4493 (Context, Count, LowerBound, UpperBound, Stride))(IsDistinct ? DIGenericSubrange::getDistinct (Context, Count,
LowerBound, UpperBound, Stride) : DIGenericSubrange::get (Context
, Count, LowerBound, UpperBound, Stride))
;
4494
4495 return false;
4496}
4497
4498/// parseDIEnumerator:
4499/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4500bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4501#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4502 REQUIRED(name, MDStringField, ); \
4503 REQUIRED(value, MDAPSIntField, ); \
4504 OPTIONAL(isUnsigned, MDBoolField, (false));
4505 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4506#undef VISIT_MD_FIELDS
4507
4508 if (isUnsigned.Val && value.Val.isNegative())
4509 return tokError("unsigned enumerator with negative value");
4510
4511 APSInt Value(value.Val);
4512 // Add a leading zero so that unsigned values with the msb set are not
4513 // mistaken for negative values when used for signed enumerators.
4514 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4515 Value = Value.zext(Value.getBitWidth() + 1);
4516
4517 Result =
4518 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val))(IsDistinct ? DIEnumerator::getDistinct (Context, Value, isUnsigned
.Val, name.Val) : DIEnumerator::get (Context, Value, isUnsigned
.Val, name.Val))
;
4519
4520 return false;
4521}
4522
4523/// parseDIBasicType:
4524/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4525/// encoding: DW_ATE_encoding, flags: 0)
4526bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4527#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4528 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4529 OPTIONAL(name, MDStringField, ); \
4530 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4531 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4532 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4533 OPTIONAL(flags, DIFlagField, );
4534 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4535#undef VISIT_MD_FIELDS
4536
4537 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
4538 align.Val, encoding.Val, flags.Val))(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
;
4539 return false;
4540}
4541
4542/// parseDIStringType:
4543/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4544bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4545#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4546 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4547 OPTIONAL(name, MDStringField, ); \
4548 OPTIONAL(stringLength, MDField, ); \
4549 OPTIONAL(stringLengthExpression, MDField, ); \
4550 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4551 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4552 OPTIONAL(encoding, DwarfAttEncodingField, );
4553 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4554#undef VISIT_MD_FIELDS
4555
4556 Result = GET_OR_DISTINCT(DIStringType,(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
4557 (Context, tag.Val, name.Val, stringLength.Val,(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
4558 stringLengthExpression.Val, size.Val, align.Val,(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
4559 encoding.Val))(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
;
4560 return false;
4561}
4562
4563/// parseDIDerivedType:
4564/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4565/// line: 7, scope: !1, baseType: !2, size: 32,
4566/// align: 32, offset: 0, flags: 0, extraData: !3,
4567/// dwarfAddressSpace: 3)
4568bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4569#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4570 REQUIRED(tag, DwarfTagField, ); \
4571 OPTIONAL(name, MDStringField, ); \
4572 OPTIONAL(file, MDField, ); \
4573 OPTIONAL(line, LineField, ); \
4574 OPTIONAL(scope, MDField, ); \
4575 REQUIRED(baseType, MDField, ); \
4576 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4577 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4578 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4579 OPTIONAL(flags, DIFlagField, ); \
4580 OPTIONAL(extraData, MDField, ); \
4581 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX0xffffffffU, UINT32_MAX0xffffffffU));
4582 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4583#undef VISIT_MD_FIELDS
4584
4585 Optional<unsigned> DWARFAddressSpace;
4586 if (dwarfAddressSpace.Val != UINT32_MAX0xffffffffU)
4587 DWARFAddressSpace = dwarfAddressSpace.Val;
4588
4589 Result = GET_OR_DISTINCT(DIDerivedType,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4590 (Context, tag.Val, name.Val, file.Val, line.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4591 scope.Val, baseType.Val, size.Val, align.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4592 offset.Val, DWARFAddressSpace, flags.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4593 extraData.Val))(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
;
4594 return false;
4595}
4596
4597bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4598#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4599 REQUIRED(tag, DwarfTagField, ); \
4600 OPTIONAL(name, MDStringField, ); \
4601 OPTIONAL(file, MDField, ); \
4602 OPTIONAL(line, LineField, ); \
4603 OPTIONAL(scope, MDField, ); \
4604 OPTIONAL(baseType, MDField, ); \
4605 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4606 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4607 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4608 OPTIONAL(flags, DIFlagField, ); \
4609 OPTIONAL(elements, MDField, ); \
4610 OPTIONAL(runtimeLang, DwarfLangField, ); \
4611 OPTIONAL(vtableHolder, MDField, ); \
4612 OPTIONAL(templateParams, MDField, ); \
4613 OPTIONAL(identifier, MDStringField, ); \
4614 OPTIONAL(discriminator, MDField, ); \
4615 OPTIONAL(dataLocation, MDField, ); \
4616 OPTIONAL(associated, MDField, ); \
4617 OPTIONAL(allocated, MDField, ); \
4618 OPTIONAL(rank, MDSignedOrMDField, );
4619 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4620#undef VISIT_MD_FIELDS
4621
4622 Metadata *Rank = nullptr;
4623 if (rank.isMDSignedField())
4624 Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4625 Type::getInt64Ty(Context), rank.getMDSignedValue()));
4626 else if (rank.isMDField())
4627 Rank = rank.getMDFieldValue();
4628
4629 // If this has an identifier try to build an ODR type.
4630 if (identifier.Val)
4631 if (auto *CT = DICompositeType::buildODRType(
4632 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4633 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4634 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4635 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4636 Rank)) {
4637 Result = CT;
4638 return false;
4639 }
4640
4641 // Create a new node, and save it in the context if it belongs in the type
4642 // map.
4643 Result = GET_OR_DISTINCT((IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4644 DICompositeType,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4645 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4646 size.Val, align.Val, offset.Val, flags.Val, elements.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4647 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4648 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4649 Rank))(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
;
4650 return false;
4651}
4652
4653bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4654#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4655 OPTIONAL(flags, DIFlagField, ); \
4656 OPTIONAL(cc, DwarfCCField, ); \
4657 REQUIRED(types, MDField, );
4658 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4659#undef VISIT_MD_FIELDS
4660
4661 Result = GET_OR_DISTINCT(DISubroutineType,(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
4662 (Context, flags.Val, cc.Val, types.Val))(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
;
4663 return false;
4664}
4665
4666/// parseDIFileType:
4667/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4668/// checksumkind: CSK_MD5,
4669/// checksum: "000102030405060708090a0b0c0d0e0f",
4670/// source: "source file contents")
4671bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4672 // The default constructed value for checksumkind is required, but will never
4673 // be used, as the parser checks if the field was actually Seen before using
4674 // the Val.
4675#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4676 REQUIRED(filename, MDStringField, ); \
4677 REQUIRED(directory, MDStringField, ); \
4678 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4679 OPTIONAL(checksum, MDStringField, ); \
4680 OPTIONAL(source, MDStringField, );
4681 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4682#undef VISIT_MD_FIELDS
4683
4684 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4685 if (checksumkind.Seen && checksum.Seen)
4686 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4687 else if (checksumkind.Seen || checksum.Seen)
4688 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4689
4690 Optional<MDString *> OptSource;
4691 if (source.Seen)
4692 OptSource = source.Val;
4693 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
4694 OptChecksum, OptSource))(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
;
4695 return false;
4696}
4697
4698/// parseDICompileUnit:
4699/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4700/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4701/// splitDebugFilename: "abc.debug",
4702/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4703/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4704/// sysroot: "/", sdk: "MacOSX.sdk")
4705bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4706 if (!IsDistinct)
4707 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4708
4709#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4710 REQUIRED(language, DwarfLangField, ); \
4711 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4712 OPTIONAL(producer, MDStringField, ); \
4713 OPTIONAL(isOptimized, MDBoolField, ); \
4714 OPTIONAL(flags, MDStringField, ); \
4715 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4716 OPTIONAL(splitDebugFilename, MDStringField, ); \
4717 OPTIONAL(emissionKind, EmissionKindField, ); \
4718 OPTIONAL(enums, MDField, ); \
4719 OPTIONAL(retainedTypes, MDField, ); \
4720 OPTIONAL(globals, MDField, ); \
4721 OPTIONAL(imports, MDField, ); \
4722 OPTIONAL(macros, MDField, ); \
4723 OPTIONAL(dwoId, MDUnsignedField, ); \
4724 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4725 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4726 OPTIONAL(nameTableKind, NameTableKindField, ); \
4727 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
4728 OPTIONAL(sysroot, MDStringField, ); \
4729 OPTIONAL(sdk, MDStringField, );
4730 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4731#undef VISIT_MD_FIELDS
4732
4733 Result = DICompileUnit::getDistinct(
4734 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4735 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4736 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4737 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4738 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4739 return false;
4740}
4741
4742/// parseDISubprogram:
4743/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4744/// file: !1, line: 7, type: !2, isLocal: false,
4745/// isDefinition: true, scopeLine: 8, containingType: !3,
4746/// virtuality: DW_VIRTUALTIY_pure_virtual,
4747/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4748/// spFlags: 10, isOptimized: false, templateParams: !4,
4749/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4750bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4751 auto Loc = Lex.getLoc();
4752#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4753 OPTIONAL(scope, MDField, ); \
4754 OPTIONAL(name, MDStringField, ); \
4755 OPTIONAL(linkageName, MDStringField, ); \
4756 OPTIONAL(file, MDField, ); \
4757 OPTIONAL(line, LineField, ); \
4758 OPTIONAL(type, MDField, ); \
4759 OPTIONAL(isLocal, MDBoolField, ); \
4760 OPTIONAL(isDefinition, MDBoolField, (true)); \
4761 OPTIONAL(scopeLine, LineField, ); \
4762 OPTIONAL(containingType, MDField, ); \
4763 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4764 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4765 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN(-0x7fffffff - 1), INT32_MAX0x7fffffff)); \
4766 OPTIONAL(flags, DIFlagField, ); \
4767 OPTIONAL(spFlags, DISPFlagField, ); \
4768 OPTIONAL(isOptimized, MDBoolField, ); \
4769 OPTIONAL(unit, MDField, ); \
4770 OPTIONAL(templateParams, MDField, ); \
4771 OPTIONAL(declaration, MDField, ); \
4772 OPTIONAL(retainedNodes, MDField, ); \
4773 OPTIONAL(thrownTypes, MDField, );
4774 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4775#undef VISIT_MD_FIELDS
4776
4777 // An explicit spFlags field takes precedence over individual fields in
4778 // older IR versions.
4779 DISubprogram::DISPFlags SPFlags =
4780 spFlags.Seen ? spFlags.Val
4781 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4782 isOptimized.Val, virtuality.Val);
4783 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4784 return Lex.Error(
4785 Loc,
4786 "missing 'distinct', required for !DISubprogram that is a Definition");
4787 Result = GET_OR_DISTINCT((IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4788 DISubprogram,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4789 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4790 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4791 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4792 declaration.Val, retainedNodes.Val, thrownTypes.Val))(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
;
4793 return false;
4794}
4795
4796/// parseDILexicalBlock:
4797/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4798bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4799#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4800 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4801 OPTIONAL(file, MDField, ); \
4802 OPTIONAL(line, LineField, ); \
4803 OPTIONAL(column, ColumnField, );
4804 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4805#undef VISIT_MD_FIELDS
4806
4807 Result = GET_OR_DISTINCT((IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
4808 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val))(IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
;
4809 return false;
4810}
4811
4812/// parseDILexicalBlockFile:
4813/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4814bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4815#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4816 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4817 OPTIONAL(file, MDField, ); \
4818 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX0xffffffffU));
4819 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4820#undef VISIT_MD_FIELDS
4821
4822 Result = GET_OR_DISTINCT(DILexicalBlockFile,(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
4823 (Context, scope.Val, file.Val, discriminator.Val))(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
;
4824 return false;
4825}
4826
4827/// parseDICommonBlock:
4828/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4829bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4831 REQUIRED(scope, MDField, ); \
4832 OPTIONAL(declaration, MDField, ); \
4833 OPTIONAL(name, MDStringField, ); \
4834 OPTIONAL(file, MDField, ); \
4835 OPTIONAL(line, LineField, );
4836 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4837#undef VISIT_MD_FIELDS
4838
4839 Result = GET_OR_DISTINCT(DICommonBlock,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4840 (Context, scope.Val, declaration.Val, name.Val,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4841 file.Val, line.Val))(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
;
4842 return false;
4843}
4844
4845/// parseDINamespace:
4846/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4847bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
4848#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4849 REQUIRED(scope, MDField, ); \
4850 OPTIONAL(name, MDStringField, ); \
4851 OPTIONAL(exportSymbols, MDBoolField, );
4852 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4853#undef VISIT_MD_FIELDS
4854
4855 Result = GET_OR_DISTINCT(DINamespace,(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
4856 (Context, scope.Val, name.Val, exportSymbols.Val))(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
;
4857 return false;
4858}
4859
4860/// parseDIMacro:
4861/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4862/// "SomeValue")
4863bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
4864#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4865 REQUIRED(type, DwarfMacinfoTypeField, ); \
4866 OPTIONAL(line, LineField, ); \
4867 REQUIRED(name, MDStringField, ); \
4868 OPTIONAL(value, MDStringField, );
4869 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4870#undef VISIT_MD_FIELDS
4871
4872 Result = GET_OR_DISTINCT(DIMacro,(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
4873 (Context, type.Val, line.Val, name.Val, value.Val))(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
;
4874 return false;
4875}
4876
4877/// parseDIMacroFile:
4878/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4879bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4881 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4882 OPTIONAL(line, LineField, ); \
4883 REQUIRED(file, MDField, ); \
4884 OPTIONAL(nodes, MDField, );
4885 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4886#undef VISIT_MD_FIELDS
4887
4888 Result = GET_OR_DISTINCT(DIMacroFile,(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
4889 (Context, type.Val, line.Val, file.Val, nodes.Val))(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
;
4890 return false;
4891}
4892
4893/// parseDIModule:
4894/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
4895/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
4896/// file: !1, line: 4, isDecl: false)
4897bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
4898#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4899 REQUIRED(scope, MDField, ); \
4900 REQUIRED(name, MDStringField, ); \
4901 OPTIONAL(configMacros, MDStringField, ); \
4902 OPTIONAL(includePath, MDStringField, ); \
4903 OPTIONAL(apinotes, MDStringField, ); \
4904 OPTIONAL(file, MDField, ); \
4905 OPTIONAL(line, LineField, ); \
4906 OPTIONAL(isDecl, MDBoolField, );
4907 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4908#undef VISIT_MD_FIELDS
4909
4910 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,(IsDistinct ? DIModule::getDistinct (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val) : DIModule::get (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val))
4911 configMacros.Val, includePath.Val,(IsDistinct ? DIModule::getDistinct (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val) : DIModule::get (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val))
4912 apinotes.Val, line.Val, isDecl.Val))(IsDistinct ? DIModule::getDistinct (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val) : DIModule::get (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val))
;
4913 return false;
4914}
4915
4916/// parseDITemplateTypeParameter:
4917/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
4918bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4919#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4920 OPTIONAL(name, MDStringField, ); \
4921 REQUIRED(type, MDField, ); \
4922 OPTIONAL(defaulted, MDBoolField, );
4923 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4924#undef VISIT_MD_FIELDS
4925
4926 Result = GET_OR_DISTINCT(DITemplateTypeParameter,(IsDistinct ? DITemplateTypeParameter::getDistinct (Context, name
.Val, type.Val, defaulted.Val) : DITemplateTypeParameter::get
(Context, name.Val, type.Val, defaulted.Val))
4927 (Context, name.Val, type.Val, defaulted.Val))(IsDistinct ? DITemplateTypeParameter::getDistinct (Context, name
.Val, type.Val, defaulted.Val) : DITemplateTypeParameter::get
(Context, name.Val, type.Val, defaulted.Val))
;
4928 return false;
4929}
4930
4931/// parseDITemplateValueParameter:
4932/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4933/// name: "V", type: !1, defaulted: false,
4934/// value: i32 7)
4935bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4937 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4938 OPTIONAL(name, MDStringField, ); \
4939 OPTIONAL(type, MDField, ); \
4940 OPTIONAL(defaulted, MDBoolField, ); \
4941 REQUIRED(value, MDField, );
4942
4943 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4944#undef VISIT_MD_FIELDS
4945
4946 Result = GET_OR_DISTINCT((IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, defaulted.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, defaulted.Val, value
.Val))
4947 DITemplateValueParameter,(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, defaulted.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, defaulted.Val, value
.Val))
4948 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val))(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, defaulted.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, defaulted.Val, value
.Val))
;
4949 return false;
4950}
4951
4952/// parseDIGlobalVariable:
4953/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4954/// file: !1, line: 7, type: !2, isLocal: false,
4955/// isDefinition: true, templateParams: !3,
4956/// declaration: !4, align: 8)
4957bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4958#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4959 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4960 OPTIONAL(scope, MDField, ); \
4961 OPTIONAL(linkageName, MDStringField, ); \
4962 OPTIONAL(file, MDField, ); \
4963 OPTIONAL(line, LineField, ); \
4964 OPTIONAL(type, MDField, ); \
4965 OPTIONAL(isLocal, MDBoolField, ); \
4966 OPTIONAL(isDefinition, MDBoolField, (true)); \
4967 OPTIONAL(templateParams, MDField, ); \
4968 OPTIONAL(declaration, MDField, ); \
4969 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU));
4970 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4971#undef VISIT_MD_FIELDS
4972
4973 Result =
4974 GET_OR_DISTINCT(DIGlobalVariable,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4975 (Context, scope.Val, name.Val, linkageName.Val, file.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4976 line.Val, type.Val, isLocal.Val, isDefinition.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4977 declaration.Val, templateParams.Val, align.Val))(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
;
4978 return false;
4979}
4980
4981/// parseDILocalVariable:
4982/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4983/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4984/// align: 8)
4985/// ::= !DILocalVariable(scope: !0, name: "foo",
4986/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4987/// align: 8)
4988bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4989#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4990 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4991 OPTIONAL(name, MDStringField, ); \
4992 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX0xffff)); \
4993 OPTIONAL(file, MDField, ); \
4994 OPTIONAL(line, LineField, ); \
4995 OPTIONAL(type, MDField, ); \
4996 OPTIONAL(flags, DIFlagField, ); \
4997 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU));
4998 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4999#undef VISIT_MD_FIELDS
5000
5001 Result = GET_OR_DISTINCT(DILocalVariable,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
5002 (Context, scope.Val, name.Val, file.Val, line.Val,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
5003 type.Val, arg.Val, flags.Val, align.Val))(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
;
5004 return false;
5005}
5006
5007/// parseDILabel:
5008/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5009bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5010#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5011 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5012 REQUIRED(name, MDStringField, ); \
5013 REQUIRED(file, MDField, ); \
5014 REQUIRED(line, LineField, );
5015 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5016#undef VISIT_MD_FIELDS
5017
5018 Result = GET_OR_DISTINCT(DILabel,(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
5019 (Context, scope.Val, name.Val, file.Val, line.Val))(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
;
5020 return false;
5021}
5022
5023/// parseDIExpression:
5024/// ::= !DIExpression(0, 7, -1)
5025bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5026 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
5027 Lex.Lex();
5028
5029 if (parseToken(lltok::lparen, "expected '(' here"))
5030 return true;
5031
5032 SmallVector<uint64_t, 8> Elements;
5033 if (Lex.getKind() != lltok::rparen)
5034 do {
5035 if (Lex.getKind() == lltok::DwarfOp) {
5036 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5037 Lex.Lex();
5038 Elements.push_back(Op);
5039 continue;
5040 }
5041 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5042 }
5043
5044 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5045 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5046 Lex.Lex();
5047 Elements.push_back(Op);
5048 continue;
5049 }
5050 return tokError(Twine("invalid DWARF attribute encoding '") +
5051 Lex.getStrVal() + "'");
5052 }
5053
5054 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5055 return tokError("expected unsigned integer");
5056
5057 auto &U = Lex.getAPSIntVal();
5058 if (U.ugt(UINT64_MAX0xffffffffffffffffULL))
5059 return tokError("element too large, limit is " + Twine(UINT64_MAX0xffffffffffffffffULL));
5060 Elements.push_back(U.getZExtValue());
5061 Lex.Lex();
5062 } while (EatIfPresent(lltok::comma));
5063
5064 if (parseToken(lltok::rparen, "expected ')' here"))
5065 return true;
5066
5067 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements))(IsDistinct ? DIExpression::getDistinct (Context, Elements) :
DIExpression::get (Context, Elements))
;
5068 return false;
5069}
5070
5071bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5072 return parseDIArgList(Result, IsDistinct, nullptr);
5073}
5074/// ParseDIArgList:
5075/// ::= !DIArgList(i32 7, i64 %0)
5076bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5077 PerFunctionState *PFS) {
5078 assert(PFS && "Expected valid function state")((void)0);
5079 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
5080 Lex.Lex();
5081
5082 if (parseToken(lltok::lparen, "expected '(' here"))
5083 return true;
5084
5085 SmallVector<ValueAsMetadata *, 4> Args;
5086 if (Lex.getKind() != lltok::rparen)
5087 do {
5088 Metadata *MD;
5089 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5090 return true;
5091 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5092 } while (EatIfPresent(lltok::comma));
5093
5094 if (parseToken(lltok::rparen, "expected ')' here"))
5095 return true;
5096
5097 Result = GET_OR_DISTINCT(DIArgList, (Context, Args))(IsDistinct ? DIArgList::getDistinct (Context, Args) : DIArgList
::get (Context, Args))
;
5098 return false;
5099}
5100
5101/// parseDIGlobalVariableExpression:
5102/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5103bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5104 bool IsDistinct) {
5105#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5106 REQUIRED(var, MDField, ); \
5107 REQUIRED(expr, MDField, );
5108 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5109#undef VISIT_MD_FIELDS
5110
5111 Result =
5112 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val))(IsDistinct ? DIGlobalVariableExpression::getDistinct (Context
, var.Val, expr.Val) : DIGlobalVariableExpression::get (Context
, var.Val, expr.Val))
;
5113 return false;
5114}
5115
5116/// parseDIObjCProperty:
5117/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5118/// getter: "getFoo", attributes: 7, type: !2)
5119bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5120#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5121 OPTIONAL(name, MDStringField, ); \
5122 OPTIONAL(file, MDField, ); \
5123 OPTIONAL(line, LineField, ); \
5124 OPTIONAL(setter, MDStringField, ); \
5125 OPTIONAL(getter, MDStringField, ); \
5126 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
5127 OPTIONAL(type, MDField, );
5128 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5129#undef VISIT_MD_FIELDS
5130
5131 Result = GET_OR_DISTINCT(DIObjCProperty,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
5132 (Context, name.Val, file.Val, line.Val, setter.Val,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
5133 getter.Val, attributes.Val, type.Val))(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
;
5134 return false;
5135}
5136
5137/// parseDIImportedEntity:
5138/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5139/// line: 7, name: "foo")
5140bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5141#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5142 REQUIRED(tag, DwarfTagField, ); \
5143 REQUIRED(scope, MDField, ); \
5144 OPTIONAL(entity, MDField, ); \
5145 OPTIONAL(file, MDField, ); \
5146 OPTIONAL(line, LineField, ); \
5147 OPTIONAL(name, MDStringField, );
5148 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5149#undef VISIT_MD_FIELDS
5150
5151 Result = GET_OR_DISTINCT((IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
5152 DIImportedEntity,(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
5153 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val))(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
;
5154 return false;
5155}
5156
5157#undef PARSE_MD_FIELD
5158#undef NOP_FIELD
5159#undef REQUIRE_FIELD
5160#undef DECLARE_FIELD
5161
5162/// parseMetadataAsValue
5163/// ::= metadata i32 %local
5164/// ::= metadata i32 @global
5165/// ::= metadata i32 7
5166/// ::= metadata !0
5167/// ::= metadata !{...}
5168/// ::= metadata !"string"
5169bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5170 // Note: the type 'metadata' has already been parsed.
5171 Metadata *MD;
5172 if (parseMetadata(MD, &PFS))
5173 return true;
5174
5175 V = MetadataAsValue::get(Context, MD);
5176 return false;
5177}
5178
5179/// parseValueAsMetadata
5180/// ::= i32 %local
5181/// ::= i32 @global
5182/// ::= i32 7
5183bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5184 PerFunctionState *PFS) {
5185 Type *Ty;
5186 LocTy Loc;
5187 if (parseType(Ty, TypeMsg, Loc))
5188 return true;
5189 if (Ty->isMetadataTy())
5190 return error(Loc, "invalid metadata-value-metadata roundtrip");
5191
5192 Value *V;
5193 if (parseValue(Ty, V, PFS))
5194 return true;
5195
5196 MD = ValueAsMetadata::get(V);
5197 return false;
5198}
5199
5200/// parseMetadata
5201/// ::= i32 %local
5202/// ::= i32 @global
5203/// ::= i32 7
5204/// ::= !42
5205/// ::= !{...}
5206/// ::= !"string"
5207/// ::= !DILocation(...)
5208bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5209 if (Lex.getKind() == lltok::MetadataVar) {
5210 MDNode *N;
5211 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5212 // so parsing this requires a Function State.
5213 if (Lex.getStrVal() == "DIArgList") {
5214 if (parseDIArgList(N, false, PFS))
5215 return true;
5216 } else if (parseSpecializedMDNode(N)) {
5217 return true;
5218 }
5219 MD = N;
5220 return false;
5221 }
5222
5223 // ValueAsMetadata:
5224 // <type> <value>
5225 if (Lex.getKind() != lltok::exclaim)
5226 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5227
5228 // '!'.
5229 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here")((void)0);
5230 Lex.Lex();
5231
5232 // MDString:
5233 // ::= '!' STRINGCONSTANT
5234 if (Lex.getKind() == lltok::StringConstant) {
5235 MDString *S;
5236 if (parseMDString(S))
5237 return true;
5238 MD = S;
5239 return false;
5240 }
5241
5242 // MDNode:
5243 // !{ ... }
5244 // !7
5245 MDNode *N;
5246 if (parseMDNodeTail(N))
5247 return true;
5248 MD = N;
5249 return false;
5250}
5251
5252//===----------------------------------------------------------------------===//
5253// Function Parsing.
5254//===----------------------------------------------------------------------===//
5255
5256bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5257 PerFunctionState *PFS, bool IsCall) {
5258 if (Ty->isFunctionTy())
5259 return error(ID.Loc, "functions are not values, refer to them as pointers");
5260
5261 switch (ID.Kind) {
5262 case ValID::t_LocalID:
5263 if (!PFS)
5264 return error(ID.Loc, "invalid use of function-local name");
5265 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5266 return V == nullptr;
5267 case ValID::t_LocalName:
5268 if (!PFS)
5269 return error(ID.Loc, "invalid use of function-local name");
5270 V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall);
5271 return V == nullptr;
5272 case ValID::t_InlineAsm: {
5273 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5274 return error(ID.Loc, "invalid type for inline asm constraint string");
5275 V = InlineAsm::get(
5276 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5277 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5278 return false;
5279 }
5280 case ValID::t_GlobalName:
5281 V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5282 return V == nullptr;
5283 case ValID::t_GlobalID:
5284 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5285 return V == nullptr;
5286 case ValID::t_APSInt:
5287 if (!Ty->isIntegerTy())
5288 return error(ID.Loc, "integer constant must have integer type");
5289 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5290 V = ConstantInt::get(Context, ID.APSIntVal);
5291 return false;
5292 case ValID::t_APFloat:
5293 if (!Ty->isFloatingPointTy() ||
5294 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5295 return error(ID.Loc, "floating point constant invalid for type");
5296
5297 // The lexer has no type info, so builds all half, bfloat, float, and double
5298 // FP constants as double. Fix this here. Long double does not need this.
5299 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5300 // Check for signaling before potentially converting and losing that info.
5301 bool IsSNAN = ID.APFloatVal.isSignaling();
5302 bool Ignored;
5303 if (Ty->isHalfTy())
5304 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5305 &Ignored);
5306 else if (Ty->isBFloatTy())
5307 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5308 &Ignored);
5309 else if (Ty->isFloatTy())
5310 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5311 &Ignored);
5312 if (IsSNAN) {
5313 // The convert call above may quiet an SNaN, so manufacture another
5314 // SNaN. The bitcast works because the payload (significand) parameter
5315 // is truncated to fit.
5316 APInt Payload = ID.APFloatVal.bitcastToAPInt();
5317 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5318 ID.APFloatVal.isNegative(), &Payload);
5319 }
5320 }
5321 V = ConstantFP::get(Context, ID.APFloatVal);
5322
5323 if (V->getType() != Ty)
5324 return error(ID.Loc, "floating point constant does not have type '" +
5325 getTypeString(Ty) + "'");
5326
5327 return false;
5328 case ValID::t_Null:
5329 if (!Ty->isPointerTy())
5330 return error(ID.Loc, "null must be a pointer type");
5331 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5332 return false;
5333 case ValID::t_Undef:
5334 // FIXME: LabelTy should not be a first-class type.
5335 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5336 return error(ID.Loc, "invalid type for undef constant");
5337 V = UndefValue::get(Ty);
5338 return false;
5339 case ValID::t_EmptyArray:
5340 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5341 return error(ID.Loc, "invalid empty array initializer");
5342 V = UndefValue::get(Ty);
5343 return false;
5344 case ValID::t_Zero:
5345 // FIXME: LabelTy should not be a first-class type.
5346 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5347 return error(ID.Loc, "invalid type for null constant");
5348 V = Constant::getNullValue(Ty);
5349 return false;
5350 case ValID::t_None:
5351 if (!Ty->isTokenTy())
5352 return error(ID.Loc, "invalid type for none constant");
5353 V = Constant::getNullValue(Ty);
5354 return false;
5355 case ValID::t_Poison:
5356 // FIXME: LabelTy should not be a first-class type.
5357 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5358 return error(ID.Loc, "invalid type for poison constant");
5359 V = PoisonValue::get(Ty);
5360 return false;
5361 case ValID::t_Constant:
5362 if (ID.ConstantVal->getType() != Ty)
5363 return error(ID.Loc, "constant expression type mismatch: got type '" +
5364 getTypeString(ID.ConstantVal->getType()) +
5365 "' but expected '" + getTypeString(Ty) + "'");
5366 V = ID.ConstantVal;
5367 return false;
5368 case ValID::t_ConstantStruct:
5369 case ValID::t_PackedConstantStruct:
5370 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5371 if (ST->getNumElements() != ID.UIntVal)
5372 return error(ID.Loc,
5373 "initializer with struct type has wrong # elements");
5374 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5375 return error(ID.Loc, "packed'ness of initializer and type don't match");
5376
5377 // Verify that the elements are compatible with the structtype.
5378 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5379 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5380 return error(
5381 ID.Loc,
5382 "element " + Twine(i) +
5383 " of struct initializer doesn't match struct element type");
5384
5385 V = ConstantStruct::get(
5386 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5387 } else
5388 return error(ID.Loc, "constant expression type mismatch");
5389 return false;
5390 }
5391 llvm_unreachable("Invalid ValID")__builtin_unreachable();
5392}
5393
5394bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5395 C = nullptr;
5396 ValID ID;
5397 auto Loc = Lex.getLoc();
5398 if (parseValID(ID, /*PFS=*/nullptr))
5399 return true;
5400 switch (ID.Kind) {
5401 case ValID::t_APSInt:
5402 case ValID::t_APFloat:
5403 case ValID::t_Undef:
5404 case ValID::t_Constant:
5405 case ValID::t_ConstantStruct:
5406 case ValID::t_PackedConstantStruct: {
5407 Value *V;
5408 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5409 return true;
5410 assert(isa<Constant>(V) && "Expected a constant value")((void)0);
5411 C = cast<Constant>(V);
5412 return false;
5413 }
5414 case ValID::t_Null:
5415 C = Constant::getNullValue(Ty);
5416 return false;
5417 default:
5418 return error(Loc, "expected a constant value");
5419 }
5420}
5421
5422bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5423 V = nullptr;
5424 ValID ID;
5425 return parseValID(ID, PFS, Ty) ||
5426 convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5427}
5428
5429bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5430 Type *Ty = nullptr;
5431 return parseType(Ty) || parseValue(Ty, V, PFS);
5432}
5433
5434bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5435 PerFunctionState &PFS) {
5436 Value *V;
5437 Loc = Lex.getLoc();
5438 if (parseTypeAndValue(V, PFS))
5439 return true;
5440 if (!isa<BasicBlock>(V))
5441 return error(Loc, "expected a basic block");
5442 BB = cast<BasicBlock>(V);
5443 return false;
5444}
5445
5446/// FunctionHeader
5447/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5448/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5449/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5450/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5451bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5452 // parse the linkage.
5453 LocTy LinkageLoc = Lex.getLoc();
5454 unsigned Linkage;
5455 unsigned Visibility;
5456 unsigned DLLStorageClass;
5457 bool DSOLocal;
5458 AttrBuilder RetAttrs;
5459 unsigned CC;
5460 bool HasLinkage;
5461 Type *RetType = nullptr;
5462 LocTy RetTypeLoc = Lex.getLoc();
5463 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5464 DSOLocal) ||
5465 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5466 parseType(RetType, RetTypeLoc, true /*void allowed*/))
5467 return true;
5468
5469 // Verify that the linkage is ok.
5470 switch ((GlobalValue::LinkageTypes)Linkage) {
5471 case GlobalValue::ExternalLinkage:
5472 break; // always ok.
5473 case GlobalValue::ExternalWeakLinkage:
5474 if (IsDefine)
5475 return error(LinkageLoc, "invalid linkage for function definition");
5476 break;
5477 case GlobalValue::PrivateLinkage:
5478 case GlobalValue::InternalLinkage:
5479 case GlobalValue::AvailableExternallyLinkage:
5480 case GlobalValue::LinkOnceAnyLinkage:
5481 case GlobalValue::LinkOnceODRLinkage:
5482 case GlobalValue::WeakAnyLinkage:
5483 case GlobalValue::WeakODRLinkage:
5484 if (!IsDefine)
5485 return error(LinkageLoc, "invalid linkage for function declaration");
5486 break;
5487 case GlobalValue::AppendingLinkage:
5488 case GlobalValue::CommonLinkage:
5489 return error(LinkageLoc, "invalid function linkage type");
5490 }
5491
5492 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5493 return error(LinkageLoc,
5494 "symbol with local linkage must have default visibility");
5495
5496 if (!FunctionType::isValidReturnType(RetType))
5497 return error(RetTypeLoc, "invalid function return type");
5498
5499 LocTy NameLoc = Lex.getLoc();
5500
5501 std::string FunctionName;
5502 if (Lex.getKind() == lltok::GlobalVar) {
5503 FunctionName = Lex.getStrVal();
5504 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5505 unsigned NameID = Lex.getUIntVal();
5506
5507 if (NameID != NumberedVals.size())
5508 return tokError("function expected to be numbered '%" +
5509 Twine(NumberedVals.size()) + "'");
5510 } else {
5511 return tokError("expected function name");
5512 }
5513
5514 Lex.Lex();
5515
5516 if (Lex.getKind() != lltok::lparen)
5517 return tokError("expected '(' in function argument list");
5518
5519 SmallVector<ArgInfo, 8> ArgList;
5520 bool IsVarArg;
5521 AttrBuilder FuncAttrs;
5522 std::vector<unsigned> FwdRefAttrGrps;
5523 LocTy BuiltinLoc;
5524 std::string Section;
5525 std::string Partition;
5526 MaybeAlign Alignment;
5527 std::string GC;
5528 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5529 unsigned AddrSpace = 0;
5530 Constant *Prefix = nullptr;
5531 Constant *Prologue = nullptr;
5532 Constant *PersonalityFn = nullptr;
5533 Comdat *C;
5534
5535 if (parseArgumentList(ArgList, IsVarArg) ||
5536 parseOptionalUnnamedAddr(UnnamedAddr) ||
5537 parseOptionalProgramAddrSpace(AddrSpace) ||
5538 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5539 BuiltinLoc) ||
5540 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5541 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5542 parseOptionalComdat(FunctionName, C) ||
5543 parseOptionalAlignment(Alignment) ||
5544 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5545 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5546 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5547 (EatIfPresent(lltok::kw_personality) &&
5548 parseGlobalTypeAndValue(PersonalityFn)))
5549 return true;
5550
5551 if (FuncAttrs.contains(Attribute::Builtin))
5552 return error(BuiltinLoc, "'builtin' attribute not valid on function");
5553
5554 // If the alignment was parsed as an attribute, move to the alignment field.
5555 if (FuncAttrs.hasAlignmentAttr()) {
5556 Alignment = FuncAttrs.getAlignment();
5557 FuncAttrs.removeAttribute(Attribute::Alignment);
5558 }
5559
5560 // Okay, if we got here, the function is syntactically valid. Convert types
5561 // and do semantic checks.
5562 std::vector<Type*> ParamTypeList;
5563 SmallVector<AttributeSet, 8> Attrs;
5564
5565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5566 ParamTypeList.push_back(ArgList[i].Ty);
5567 Attrs.push_back(ArgList[i].Attrs);
5568 }
5569
5570 AttributeList PAL =
5571 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5572 AttributeSet::get(Context, RetAttrs), Attrs);
5573
5574 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5575 return error(RetTypeLoc, "functions with 'sret' argument must return void");
5576
5577 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5578 PointerType *PFT = PointerType::get(FT, AddrSpace);
5579
5580 Fn = nullptr;
5581 GlobalValue *FwdFn = nullptr;
5582 if (!FunctionName.empty()) {
5583 // If this was a definition of a forward reference, remove the definition
5584 // from the forward reference table and fill in the forward ref.
5585 auto FRVI = ForwardRefVals.find(FunctionName);
5586 if (FRVI != ForwardRefVals.end()) {
5587 FwdFn = FRVI->second.first;
5588 if (!FwdFn->getType()->isOpaque()) {
5589 if (!FwdFn->getType()->getPointerElementType()->isFunctionTy())
5590 return error(FRVI->second.second, "invalid forward reference to "
5591 "function as global value!");
5592 if (FwdFn->getType() != PFT)
5593 return error(FRVI->second.second,
5594 "invalid forward reference to "
5595 "function '" +
5596 FunctionName +
5597 "' with wrong type: "
5598 "expected '" +
5599 getTypeString(PFT) + "' but was '" +
5600 getTypeString(FwdFn->getType()) + "'");
5601 }
5602 ForwardRefVals.erase(FRVI);
5603 } else if ((Fn = M->getFunction(FunctionName))) {
5604 // Reject redefinitions.
5605 return error(NameLoc,
5606 "invalid redefinition of function '" + FunctionName + "'");
5607 } else if (M->getNamedValue(FunctionName)) {
5608 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5609 }
5610
5611 } else {
5612 // If this is a definition of a forward referenced function, make sure the
5613 // types agree.
5614 auto I = ForwardRefValIDs.find(NumberedVals.size());
5615 if (I != ForwardRefValIDs.end()) {
5616 FwdFn = cast<Function>(I->second.first);
5617 if (!FwdFn->getType()->isOpaque() && FwdFn->getType() != PFT)
5618 return error(NameLoc, "type of definition and forward reference of '@" +
5619 Twine(NumberedVals.size()) +
5620 "' disagree: "
5621 "expected '" +
5622 getTypeString(PFT) + "' but was '" +
5623 getTypeString(FwdFn->getType()) + "'");
5624 ForwardRefValIDs.erase(I);
5625 }
5626 }
5627
5628 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5629 FunctionName, M);
5630
5631 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS")((void)0);
5632
5633 if (FunctionName.empty())
5634 NumberedVals.push_back(Fn);
5635
5636 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5637 maybeSetDSOLocal(DSOLocal, *Fn);
5638 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5639 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5640 Fn->setCallingConv(CC);
5641 Fn->setAttributes(PAL);
5642 Fn->setUnnamedAddr(UnnamedAddr);
5643 Fn->setAlignment(MaybeAlign(Alignment));
5644 Fn->setSection(Section);
5645 Fn->setPartition(Partition);
5646 Fn->setComdat(C);
5647 Fn->setPersonalityFn(PersonalityFn);
5648 if (!GC.empty()) Fn->setGC(GC);
5649 Fn->setPrefixData(Prefix);
5650 Fn->setPrologueData(Prologue);
5651 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5652
5653 // Add all of the arguments we parsed to the function.
5654 Function::arg_iterator ArgIt = Fn->arg_begin();
5655 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5656 // If the argument has a name, insert it into the argument symbol table.
5657 if (ArgList[i].Name.empty()) continue;
5658
5659 // Set the name, if it conflicted, it will be auto-renamed.
5660 ArgIt->setName(ArgList[i].Name);
5661
5662 if (ArgIt->getName() != ArgList[i].Name)
5663 return error(ArgList[i].Loc,
5664 "redefinition of argument '%" + ArgList[i].Name + "'");
5665 }
5666
5667 if (FwdFn) {
5668 FwdFn->replaceAllUsesWith(Fn);
5669 FwdFn->eraseFromParent();
5670 }
5671
5672 if (IsDefine)
5673 return false;
5674
5675 // Check the declaration has no block address forward references.
5676 ValID ID;
5677 if (FunctionName.empty()) {
5678 ID.Kind = ValID::t_GlobalID;
5679 ID.UIntVal = NumberedVals.size() - 1;
5680 } else {
5681 ID.Kind = ValID::t_GlobalName;
5682 ID.StrVal = FunctionName;
5683 }
5684 auto Blocks = ForwardRefBlockAddresses.find(ID);
5685 if (Blocks != ForwardRefBlockAddresses.end())
5686 return error(Blocks->first.Loc,
5687 "cannot take blockaddress inside a declaration");
5688 return false;
5689}
5690
5691bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5692 ValID ID;
5693 if (FunctionNumber == -1) {
5694 ID.Kind = ValID::t_GlobalName;
5695 ID.StrVal = std::string(F.getName());
5696 } else {
5697 ID.Kind = ValID::t_GlobalID;
5698 ID.UIntVal = FunctionNumber;
5699 }
5700
5701 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5702 if (Blocks == P.ForwardRefBlockAddresses.end())
5703 return false;
5704
5705 for (const auto &I : Blocks->second) {
5706 const ValID &BBID = I.first;
5707 GlobalValue *GV = I.second;
5708
5709 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&((void)0)
5710 "Expected local id or name")((void)0);
5711 BasicBlock *BB;
5712 if (BBID.Kind == ValID::t_LocalName)
5713 BB = getBB(BBID.StrVal, BBID.Loc);
5714 else
5715 BB = getBB(BBID.UIntVal, BBID.Loc);
5716 if (!BB)
5717 return P.error(BBID.Loc, "referenced value is not a basic block");
5718
5719 Value *ResolvedVal = BlockAddress::get(&F, BB);
5720 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
5721 ResolvedVal, false);
5722 if (!ResolvedVal)
5723 return true;
5724 GV->replaceAllUsesWith(ResolvedVal);
5725 GV->eraseFromParent();
5726 }
5727
5728 P.ForwardRefBlockAddresses.erase(Blocks);
5729 return false;
5730}
5731
5732/// parseFunctionBody
5733/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5734bool LLParser::parseFunctionBody(Function &Fn) {
5735 if (Lex.getKind() != lltok::lbrace)
5736 return tokError("expected '{' in function body");
5737 Lex.Lex(); // eat the {.
5738
5739 int FunctionNumber = -1;
5740 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5741
5742 PerFunctionState PFS(*this, Fn, FunctionNumber);
5743
5744 // Resolve block addresses and allow basic blocks to be forward-declared
5745 // within this function.
5746 if (PFS.resolveForwardRefBlockAddresses())
5747 return true;
5748 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5749
5750 // We need at least one basic block.
5751 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5752 return tokError("function body requires at least one basic block");
5753
5754 while (Lex.getKind() != lltok::rbrace &&
5755 Lex.getKind() != lltok::kw_uselistorder)
5756 if (parseBasicBlock(PFS))
5757 return true;
5758
5759 while (Lex.getKind() != lltok::rbrace)
5760 if (parseUseListOrder(&PFS))
5761 return true;
5762
5763 // Eat the }.
5764 Lex.Lex();
5765
5766 // Verify function is ok.
5767 return PFS.finishFunction();
5768}
5769
5770/// parseBasicBlock
5771/// ::= (LabelStr|LabelID)? Instruction*
5772bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5773 // If this basic block starts out with a name, remember it.
5774 std::string Name;
5775 int NameID = -1;
5776 LocTy NameLoc = Lex.getLoc();
5777 if (Lex.getKind() == lltok::LabelStr) {
5778 Name = Lex.getStrVal();
5779 Lex.Lex();
5780 } else if (Lex.getKind() == lltok::LabelID) {
5781 NameID = Lex.getUIntVal();
5782 Lex.Lex();
5783 }
5784
5785 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5786 if (!BB)
5787 return true;
5788
5789 std::string NameStr;
5790
5791 // parse the instructions in this block until we get a terminator.
5792 Instruction *Inst;
5793 do {
5794 // This instruction may have three possibilities for a name: a) none
5795 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5796 LocTy NameLoc = Lex.getLoc();
5797 int NameID = -1;
5798 NameStr = "";
5799
5800 if (Lex.getKind() == lltok::LocalVarID) {
5801 NameID = Lex.getUIntVal();
5802 Lex.Lex();
5803 if (parseToken(lltok::equal, "expected '=' after instruction id"))
5804 return true;
5805 } else if (Lex.getKind() == lltok::LocalVar) {
5806 NameStr = Lex.getStrVal();
5807 Lex.Lex();
5808 if (parseToken(lltok::equal, "expected '=' after instruction name"))
5809 return true;
5810 }
5811
5812 switch (parseInstruction(Inst, BB, PFS)) {
5813 default:
5814 llvm_unreachable("Unknown parseInstruction result!")__builtin_unreachable();
5815 case InstError: return true;
5816 case InstNormal:
5817 BB->getInstList().push_back(Inst);
5818
5819 // With a normal result, we check to see if the instruction is followed by
5820 // a comma and metadata.
5821 if (EatIfPresent(lltok::comma))
5822 if (parseInstructionMetadata(*Inst))
5823 return true;
5824 break;
5825 case InstExtraComma:
5826 BB->getInstList().push_back(Inst);
5827
5828 // If the instruction parser ate an extra comma at the end of it, it
5829 // *must* be followed by metadata.
5830 if (parseInstructionMetadata(*Inst))
5831 return true;
5832 break;
5833 }
5834
5835 // Set the name on the instruction.
5836 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
5837 return true;
5838 } while (!Inst->isTerminator());
5839
5840 return false;
5841}
5842
5843//===----------------------------------------------------------------------===//
5844// Instruction Parsing.
5845//===----------------------------------------------------------------------===//
5846
5847/// parseInstruction - parse one of the many different instructions.
5848///
5849int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
5850 PerFunctionState &PFS) {
5851 lltok::Kind Token = Lex.getKind();
5852 if (Token == lltok::Eof)
5853 return tokError("found end of file when expecting more instructions");
5854 LocTy Loc = Lex.getLoc();
5855 unsigned KeywordVal = Lex.getUIntVal();
5856 Lex.Lex(); // Eat the keyword.
5857
5858 switch (Token) {
5859 default:
5860 return error(Loc, "expected instruction opcode");
5861 // Terminator Instructions.
5862 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5863 case lltok::kw_ret:
5864 return parseRet(Inst, BB, PFS);
5865 case lltok::kw_br:
5866 return parseBr(Inst, PFS);
5867 case lltok::kw_switch:
5868 return parseSwitch(Inst, PFS);
5869 case lltok::kw_indirectbr:
5870 return parseIndirectBr(Inst, PFS);
5871 case lltok::kw_invoke:
5872 return parseInvoke(Inst, PFS);
5873 case lltok::kw_resume:
5874 return parseResume(Inst, PFS);
5875 case lltok::kw_cleanupret:
5876 return parseCleanupRet(Inst, PFS);
5877 case lltok::kw_catchret:
5878 return parseCatchRet(Inst, PFS);
5879 case lltok::kw_catchswitch:
5880 return parseCatchSwitch(Inst, PFS);
5881 case lltok::kw_catchpad:
5882 return parseCatchPad(Inst, PFS);
5883 case lltok::kw_cleanuppad:
5884 return parseCleanupPad(Inst, PFS);
5885 case lltok::kw_callbr:
5886 return parseCallBr(Inst, PFS);
5887 // Unary Operators.
5888 case lltok::kw_fneg: {
5889 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5890 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/