| 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/STLExtras.h" |
| 17 | #include "llvm/ADT/ScopeExit.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/Attributes.h" |
| 24 | #include "llvm/IR/AutoUpgrade.h" |
| 25 | #include "llvm/IR/BasicBlock.h" |
| 26 | #include "llvm/IR/CallingConv.h" |
| 27 | #include "llvm/IR/Comdat.h" |
| 28 | #include "llvm/IR/ConstantRange.h" |
| 29 | #include "llvm/IR/ConstantRangeList.h" |
| 30 | #include "llvm/IR/Constants.h" |
| 31 | #include "llvm/IR/DebugInfoMetadata.h" |
| 32 | #include "llvm/IR/DerivedTypes.h" |
| 33 | #include "llvm/IR/Function.h" |
| 34 | #include "llvm/IR/GlobalIFunc.h" |
| 35 | #include "llvm/IR/GlobalObject.h" |
| 36 | #include "llvm/IR/InlineAsm.h" |
| 37 | #include "llvm/IR/InstIterator.h" |
| 38 | #include "llvm/IR/Instructions.h" |
| 39 | #include "llvm/IR/IntrinsicInst.h" |
| 40 | #include "llvm/IR/Intrinsics.h" |
| 41 | #include "llvm/IR/LLVMContext.h" |
| 42 | #include "llvm/IR/Metadata.h" |
| 43 | #include "llvm/IR/Module.h" |
| 44 | #include "llvm/IR/Operator.h" |
| 45 | #include "llvm/IR/Value.h" |
| 46 | #include "llvm/IR/ValueSymbolTable.h" |
| 47 | #include "llvm/Support/Casting.h" |
| 48 | #include "llvm/Support/Compiler.h" |
| 49 | #include "llvm/Support/ErrorHandling.h" |
| 50 | #include "llvm/Support/MathExtras.h" |
| 51 | #include "llvm/Support/ModRef.h" |
| 52 | #include "llvm/Support/SaveAndRestore.h" |
| 53 | #include "llvm/Support/raw_ostream.h" |
| 54 | #include <algorithm> |
| 55 | #include <cassert> |
| 56 | #include <cstring> |
| 57 | #include <optional> |
| 58 | #include <vector> |
| 59 | |
| 60 | using namespace llvm; |
| 61 | |
| 62 | static cl::opt<bool> AllowIncompleteIR( |
| 63 | "allow-incomplete-ir" , cl::init(Val: false), cl::Hidden, |
| 64 | cl::desc( |
| 65 | "Allow incomplete IR on a best effort basis (references to unknown " |
| 66 | "metadata will be dropped)" )); |
| 67 | |
| 68 | static std::string getTypeString(Type *T) { |
| 69 | std::string Result; |
| 70 | raw_string_ostream Tmp(Result); |
| 71 | Tmp << *T; |
| 72 | return Tmp.str(); |
| 73 | } |
| 74 | |
| 75 | /// Run: module ::= toplevelentity* |
| 76 | bool LLParser::Run(bool UpgradeDebugInfo, |
| 77 | DataLayoutCallbackTy DataLayoutCallback) { |
| 78 | // Prime the lexer. |
| 79 | Lex.Lex(); |
| 80 | |
| 81 | if (Context.shouldDiscardValueNames()) |
| 82 | return error( |
| 83 | L: Lex.getLoc(), |
| 84 | Msg: "Can't read textual IR with a Context that discards named Values" ); |
| 85 | |
| 86 | if (M) { |
| 87 | if (parseTargetDefinitions(DataLayoutCallback)) |
| 88 | return true; |
| 89 | } |
| 90 | |
| 91 | return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) || |
| 92 | validateEndOfIndex(); |
| 93 | } |
| 94 | |
| 95 | bool LLParser::parseStandaloneConstantValue(Constant *&C, |
| 96 | const SlotMapping *Slots) { |
| 97 | restoreParsingState(Slots); |
| 98 | Lex.Lex(); |
| 99 | |
| 100 | Type *Ty = nullptr; |
| 101 | if (parseType(Result&: Ty) || parseConstantValue(Ty, C)) |
| 102 | return true; |
| 103 | if (Lex.getKind() != lltok::Eof) |
| 104 | return error(L: Lex.getLoc(), Msg: "expected end of string" ); |
| 105 | return false; |
| 106 | } |
| 107 | |
| 108 | bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read, |
| 109 | const SlotMapping *Slots) { |
| 110 | restoreParsingState(Slots); |
| 111 | Lex.Lex(); |
| 112 | |
| 113 | Read = 0; |
| 114 | SMLoc Start = Lex.getLoc(); |
| 115 | Ty = nullptr; |
| 116 | if (parseType(Result&: Ty)) |
| 117 | return true; |
| 118 | SMLoc End = Lex.getLoc(); |
| 119 | Read = End.getPointer() - Start.getPointer(); |
| 120 | |
| 121 | return false; |
| 122 | } |
| 123 | |
| 124 | bool LLParser::parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, |
| 125 | const SlotMapping *Slots) { |
| 126 | restoreParsingState(Slots); |
| 127 | Lex.Lex(); |
| 128 | |
| 129 | Read = 0; |
| 130 | SMLoc Start = Lex.getLoc(); |
| 131 | Result = nullptr; |
| 132 | bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false); |
| 133 | SMLoc End = Lex.getLoc(); |
| 134 | Read = End.getPointer() - Start.getPointer(); |
| 135 | |
| 136 | return Status; |
| 137 | } |
| 138 | |
| 139 | void LLParser::restoreParsingState(const SlotMapping *Slots) { |
| 140 | if (!Slots) |
| 141 | return; |
| 142 | NumberedVals = Slots->GlobalValues; |
| 143 | NumberedMetadata = Slots->MetadataNodes; |
| 144 | for (const auto &I : Slots->NamedTypes) |
| 145 | NamedTypes.insert( |
| 146 | KV: std::make_pair(x: I.getKey(), y: std::make_pair(x: I.second, y: LocTy()))); |
| 147 | for (const auto &I : Slots->Types) |
| 148 | NumberedTypes.insert( |
| 149 | x: std::make_pair(x: I.first, y: std::make_pair(x: I.second, y: LocTy()))); |
| 150 | } |
| 151 | |
| 152 | static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II) { |
| 153 | // White-list intrinsics that are safe to drop. |
| 154 | if (!isa<DbgInfoIntrinsic>(Val: II) && |
| 155 | II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl) |
| 156 | return; |
| 157 | |
| 158 | SmallVector<MetadataAsValue *> MVs; |
| 159 | for (Value *V : II->args()) |
| 160 | if (auto *MV = dyn_cast<MetadataAsValue>(Val: V)) |
| 161 | if (auto *MD = dyn_cast<MDNode>(Val: MV->getMetadata())) |
| 162 | if (MD->isTemporary()) |
| 163 | MVs.push_back(Elt: MV); |
| 164 | |
| 165 | if (!MVs.empty()) { |
| 166 | assert(II->use_empty() && "Cannot have uses" ); |
| 167 | II->eraseFromParent(); |
| 168 | |
| 169 | // Also remove no longer used MetadataAsValue wrappers. |
| 170 | for (MetadataAsValue *MV : MVs) |
| 171 | if (MV->use_empty()) |
| 172 | delete MV; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | void LLParser::dropUnknownMetadataReferences() { |
| 177 | auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); }; |
| 178 | for (Function &F : *M) { |
| 179 | F.eraseMetadataIf(Pred); |
| 180 | for (Instruction &I : make_early_inc_range(Range: instructions(F))) { |
| 181 | I.eraseMetadataIf(Pred); |
| 182 | |
| 183 | if (auto *II = dyn_cast<IntrinsicInst>(Val: &I)) |
| 184 | dropIntrinsicWithUnknownMetadataArgument(II); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | for (GlobalVariable &GV : M->globals()) |
| 189 | GV.eraseMetadataIf(Pred); |
| 190 | |
| 191 | for (const auto &[ID, Info] : make_early_inc_range(Range&: ForwardRefMDNodes)) { |
| 192 | // Check whether there is only a single use left, which would be in our |
| 193 | // own NumberedMetadata. |
| 194 | if (Info.first->getNumTemporaryUses() == 1) { |
| 195 | NumberedMetadata.erase(x: ID); |
| 196 | ForwardRefMDNodes.erase(x: ID); |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /// validateEndOfModule - Do final validity and basic correctness checks at the |
| 202 | /// end of the module. |
| 203 | bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) { |
| 204 | if (!M) |
| 205 | return false; |
| 206 | |
| 207 | // We should have already returned an error if we observed both intrinsics and |
| 208 | // records in this IR. |
| 209 | assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) && |
| 210 | "Mixed debug intrinsics/records seen without a parsing error?" ); |
| 211 | |
| 212 | // Handle any function attribute group forward references. |
| 213 | for (const auto &RAG : ForwardRefAttrGroups) { |
| 214 | Value *V = RAG.first; |
| 215 | const std::vector<unsigned> &Attrs = RAG.second; |
| 216 | AttrBuilder B(Context); |
| 217 | |
| 218 | for (const auto &Attr : Attrs) { |
| 219 | auto R = NumberedAttrBuilders.find(x: Attr); |
| 220 | if (R != NumberedAttrBuilders.end()) |
| 221 | B.merge(B: R->second); |
| 222 | } |
| 223 | |
| 224 | if (Function *Fn = dyn_cast<Function>(Val: V)) { |
| 225 | AttributeList AS = Fn->getAttributes(); |
| 226 | AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); |
| 227 | AS = AS.removeFnAttributes(C&: Context); |
| 228 | |
| 229 | FnAttrs.merge(B); |
| 230 | |
| 231 | // If the alignment was parsed as an attribute, move to the alignment |
| 232 | // field. |
| 233 | if (MaybeAlign A = FnAttrs.getAlignment()) { |
| 234 | Fn->setAlignment(*A); |
| 235 | FnAttrs.removeAttribute(Val: Attribute::Alignment); |
| 236 | } |
| 237 | |
| 238 | AS = AS.addFnAttributes(C&: Context, B: FnAttrs); |
| 239 | Fn->setAttributes(AS); |
| 240 | } else if (CallInst *CI = dyn_cast<CallInst>(Val: V)) { |
| 241 | AttributeList AS = CI->getAttributes(); |
| 242 | AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); |
| 243 | AS = AS.removeFnAttributes(C&: Context); |
| 244 | FnAttrs.merge(B); |
| 245 | AS = AS.addFnAttributes(C&: Context, B: FnAttrs); |
| 246 | CI->setAttributes(AS); |
| 247 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(Val: V)) { |
| 248 | AttributeList AS = II->getAttributes(); |
| 249 | AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); |
| 250 | AS = AS.removeFnAttributes(C&: Context); |
| 251 | FnAttrs.merge(B); |
| 252 | AS = AS.addFnAttributes(C&: Context, B: FnAttrs); |
| 253 | II->setAttributes(AS); |
| 254 | } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Val: V)) { |
| 255 | AttributeList AS = CBI->getAttributes(); |
| 256 | AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); |
| 257 | AS = AS.removeFnAttributes(C&: Context); |
| 258 | FnAttrs.merge(B); |
| 259 | AS = AS.addFnAttributes(C&: Context, B: FnAttrs); |
| 260 | CBI->setAttributes(AS); |
| 261 | } else if (auto *GV = dyn_cast<GlobalVariable>(Val: V)) { |
| 262 | AttrBuilder Attrs(M->getContext(), GV->getAttributes()); |
| 263 | Attrs.merge(B); |
| 264 | GV->setAttributes(AttributeSet::get(C&: Context,B: Attrs)); |
| 265 | } else { |
| 266 | llvm_unreachable("invalid object with forward attribute group reference" ); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // If there are entries in ForwardRefBlockAddresses at this point, the |
| 271 | // function was never defined. |
| 272 | if (!ForwardRefBlockAddresses.empty()) |
| 273 | return error(L: ForwardRefBlockAddresses.begin()->first.Loc, |
| 274 | Msg: "expected function name in blockaddress" ); |
| 275 | |
| 276 | auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef, |
| 277 | GlobalValue *FwdRef) { |
| 278 | GlobalValue *GV = nullptr; |
| 279 | if (GVRef.Kind == ValID::t_GlobalName) { |
| 280 | GV = M->getNamedValue(Name: GVRef.StrVal); |
| 281 | } else { |
| 282 | GV = NumberedVals.get(ID: GVRef.UIntVal); |
| 283 | } |
| 284 | |
| 285 | if (!GV) |
| 286 | return error(L: GVRef.Loc, Msg: "unknown function '" + GVRef.StrVal + |
| 287 | "' referenced by dso_local_equivalent" ); |
| 288 | |
| 289 | if (!GV->getValueType()->isFunctionTy()) |
| 290 | return error(L: GVRef.Loc, |
| 291 | Msg: "expected a function, alias to function, or ifunc " |
| 292 | "in dso_local_equivalent" ); |
| 293 | |
| 294 | auto *Equiv = DSOLocalEquivalent::get(GV); |
| 295 | FwdRef->replaceAllUsesWith(V: Equiv); |
| 296 | FwdRef->eraseFromParent(); |
| 297 | return false; |
| 298 | }; |
| 299 | |
| 300 | // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this |
| 301 | // point, they are references after the function was defined. Resolve those |
| 302 | // now. |
| 303 | for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) { |
| 304 | if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second)) |
| 305 | return true; |
| 306 | } |
| 307 | for (auto &Iter : ForwardRefDSOLocalEquivalentNames) { |
| 308 | if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second)) |
| 309 | return true; |
| 310 | } |
| 311 | ForwardRefDSOLocalEquivalentIDs.clear(); |
| 312 | ForwardRefDSOLocalEquivalentNames.clear(); |
| 313 | |
| 314 | for (const auto &NT : NumberedTypes) |
| 315 | if (NT.second.second.isValid()) |
| 316 | return error(L: NT.second.second, |
| 317 | Msg: "use of undefined type '%" + Twine(NT.first) + "'" ); |
| 318 | |
| 319 | for (const auto &[Name, TypeInfo] : NamedTypes) |
| 320 | if (TypeInfo.second.isValid()) |
| 321 | return error(L: TypeInfo.second, |
| 322 | Msg: "use of undefined type named '" + Name + "'" ); |
| 323 | |
| 324 | if (!ForwardRefComdats.empty()) |
| 325 | return error(L: ForwardRefComdats.begin()->second, |
| 326 | Msg: "use of undefined comdat '$" + |
| 327 | ForwardRefComdats.begin()->first + "'" ); |
| 328 | |
| 329 | for (const auto &[Name, Info] : make_early_inc_range(Range&: ForwardRefVals)) { |
| 330 | if (StringRef(Name).starts_with(Prefix: "llvm." )) { |
| 331 | Intrinsic::ID IID = Intrinsic::lookupIntrinsicID(Name); |
| 332 | // Automatically create declarations for intrinsics. Intrinsics can only |
| 333 | // be called directly, so the call function type directly determines the |
| 334 | // declaration function type. |
| 335 | // |
| 336 | // Additionally, automatically add the required mangling suffix to the |
| 337 | // intrinsic name. This means that we may replace a single forward |
| 338 | // declaration with multiple functions here. |
| 339 | for (Use &U : make_early_inc_range(Range: Info.first->uses())) { |
| 340 | auto *CB = dyn_cast<CallBase>(Val: U.getUser()); |
| 341 | if (!CB || !CB->isCallee(U: &U)) |
| 342 | return error(L: Info.second, Msg: "intrinsic can only be used as callee" ); |
| 343 | |
| 344 | SmallVector<Type *> OverloadTys; |
| 345 | if (IID != Intrinsic::not_intrinsic && |
| 346 | Intrinsic::getIntrinsicSignature(IID, FT: CB->getFunctionType(), |
| 347 | ArgTys&: OverloadTys)) { |
| 348 | U.set(Intrinsic::getOrInsertDeclaration(M, id: IID, Tys: OverloadTys)); |
| 349 | } else { |
| 350 | // Try to upgrade the intrinsic. |
| 351 | Function *TmpF = Function::Create(Ty: CB->getFunctionType(), |
| 352 | Linkage: Function::ExternalLinkage, N: Name, M); |
| 353 | Function *NewF = nullptr; |
| 354 | if (!UpgradeIntrinsicFunction(F: TmpF, NewFn&: NewF)) { |
| 355 | if (IID == Intrinsic::not_intrinsic) |
| 356 | return error(L: Info.second, Msg: "unknown intrinsic '" + Name + "'" ); |
| 357 | return error(L: Info.second, Msg: "invalid intrinsic signature" ); |
| 358 | } |
| 359 | |
| 360 | U.set(TmpF); |
| 361 | UpgradeIntrinsicCall(CB, NewFn: NewF); |
| 362 | if (TmpF->use_empty()) |
| 363 | TmpF->eraseFromParent(); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | Info.first->eraseFromParent(); |
| 368 | ForwardRefVals.erase(x: Name); |
| 369 | continue; |
| 370 | } |
| 371 | |
| 372 | // If incomplete IR is allowed, also add declarations for |
| 373 | // non-intrinsics. |
| 374 | if (!AllowIncompleteIR) |
| 375 | continue; |
| 376 | |
| 377 | auto GetCommonFunctionType = [](Value *V) -> FunctionType * { |
| 378 | FunctionType *FTy = nullptr; |
| 379 | for (Use &U : V->uses()) { |
| 380 | auto *CB = dyn_cast<CallBase>(Val: U.getUser()); |
| 381 | if (!CB || !CB->isCallee(U: &U) || (FTy && FTy != CB->getFunctionType())) |
| 382 | return nullptr; |
| 383 | FTy = CB->getFunctionType(); |
| 384 | } |
| 385 | return FTy; |
| 386 | }; |
| 387 | |
| 388 | // First check whether this global is only used in calls with the same |
| 389 | // type, in which case we'll insert a function. Otherwise, fall back to |
| 390 | // using a dummy i8 type. |
| 391 | Type *Ty = GetCommonFunctionType(Info.first); |
| 392 | if (!Ty) |
| 393 | Ty = Type::getInt8Ty(C&: Context); |
| 394 | |
| 395 | GlobalValue *GV; |
| 396 | if (auto *FTy = dyn_cast<FunctionType>(Val: Ty)) |
| 397 | GV = Function::Create(Ty: FTy, Linkage: GlobalValue::ExternalLinkage, N: Name, M); |
| 398 | else |
| 399 | GV = new GlobalVariable(*M, Ty, /*isConstant*/ false, |
| 400 | GlobalValue::ExternalLinkage, |
| 401 | /*Initializer*/ nullptr, Name); |
| 402 | Info.first->replaceAllUsesWith(V: GV); |
| 403 | Info.first->eraseFromParent(); |
| 404 | ForwardRefVals.erase(x: Name); |
| 405 | } |
| 406 | |
| 407 | if (!ForwardRefVals.empty()) |
| 408 | return error(L: ForwardRefVals.begin()->second.second, |
| 409 | Msg: "use of undefined value '@" + ForwardRefVals.begin()->first + |
| 410 | "'" ); |
| 411 | |
| 412 | if (!ForwardRefValIDs.empty()) |
| 413 | return error(L: ForwardRefValIDs.begin()->second.second, |
| 414 | Msg: "use of undefined value '@" + |
| 415 | Twine(ForwardRefValIDs.begin()->first) + "'" ); |
| 416 | |
| 417 | if (AllowIncompleteIR && !ForwardRefMDNodes.empty()) |
| 418 | dropUnknownMetadataReferences(); |
| 419 | |
| 420 | if (!ForwardRefMDNodes.empty()) |
| 421 | return error(L: ForwardRefMDNodes.begin()->second.second, |
| 422 | Msg: "use of undefined metadata '!" + |
| 423 | Twine(ForwardRefMDNodes.begin()->first) + "'" ); |
| 424 | |
| 425 | // Resolve metadata cycles. |
| 426 | for (auto &N : NumberedMetadata) { |
| 427 | if (N.second && !N.second->isResolved()) |
| 428 | N.second->resolveCycles(); |
| 429 | } |
| 430 | |
| 431 | for (auto *Inst : InstsWithTBAATag) { |
| 432 | MDNode *MD = Inst->getMetadata(KindID: LLVMContext::MD_tbaa); |
| 433 | // With incomplete IR, the tbaa metadata may have been dropped. |
| 434 | if (!AllowIncompleteIR) |
| 435 | assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag" ); |
| 436 | if (MD) { |
| 437 | auto *UpgradedMD = UpgradeTBAANode(TBAANode&: *MD); |
| 438 | if (MD != UpgradedMD) |
| 439 | Inst->setMetadata(KindID: LLVMContext::MD_tbaa, Node: UpgradedMD); |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | // Look for intrinsic functions and CallInst that need to be upgraded. We use |
| 444 | // make_early_inc_range here because we may remove some functions. |
| 445 | for (Function &F : llvm::make_early_inc_range(Range&: *M)) |
| 446 | UpgradeCallsToIntrinsic(F: &F); |
| 447 | |
| 448 | if (UpgradeDebugInfo) |
| 449 | llvm::UpgradeDebugInfo(M&: *M); |
| 450 | |
| 451 | UpgradeModuleFlags(M&: *M); |
| 452 | UpgradeNVVMAnnotations(M&: *M); |
| 453 | UpgradeSectionAttributes(M&: *M); |
| 454 | copyModuleAttrToFunctions(M&: *M); |
| 455 | |
| 456 | if (!Slots) |
| 457 | return false; |
| 458 | // Initialize the slot mapping. |
| 459 | // Because by this point we've parsed and validated everything, we can "steal" |
| 460 | // the mapping from LLParser as it doesn't need it anymore. |
| 461 | Slots->GlobalValues = std::move(NumberedVals); |
| 462 | Slots->MetadataNodes = std::move(NumberedMetadata); |
| 463 | for (const auto &I : NamedTypes) |
| 464 | Slots->NamedTypes.insert(KV: std::make_pair(x: I.getKey(), y: I.second.first)); |
| 465 | for (const auto &I : NumberedTypes) |
| 466 | Slots->Types.insert(x: std::make_pair(x: I.first, y: I.second.first)); |
| 467 | |
| 468 | return false; |
| 469 | } |
| 470 | |
| 471 | /// Do final validity and basic correctness checks at the end of the index. |
| 472 | bool LLParser::validateEndOfIndex() { |
| 473 | if (!Index) |
| 474 | return false; |
| 475 | |
| 476 | if (!ForwardRefValueInfos.empty()) |
| 477 | return error(L: ForwardRefValueInfos.begin()->second.front().second, |
| 478 | Msg: "use of undefined summary '^" + |
| 479 | Twine(ForwardRefValueInfos.begin()->first) + "'" ); |
| 480 | |
| 481 | if (!ForwardRefAliasees.empty()) |
| 482 | return error(L: ForwardRefAliasees.begin()->second.front().second, |
| 483 | Msg: "use of undefined summary '^" + |
| 484 | Twine(ForwardRefAliasees.begin()->first) + "'" ); |
| 485 | |
| 486 | if (!ForwardRefTypeIds.empty()) |
| 487 | return error(L: ForwardRefTypeIds.begin()->second.front().second, |
| 488 | Msg: "use of undefined type id summary '^" + |
| 489 | Twine(ForwardRefTypeIds.begin()->first) + "'" ); |
| 490 | |
| 491 | return false; |
| 492 | } |
| 493 | |
| 494 | //===----------------------------------------------------------------------===// |
| 495 | // Top-Level Entities |
| 496 | //===----------------------------------------------------------------------===// |
| 497 | |
| 498 | bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) { |
| 499 | // Delay parsing of the data layout string until the target triple is known. |
| 500 | // Then, pass both the the target triple and the tentative data layout string |
| 501 | // to DataLayoutCallback, allowing to override the DL string. |
| 502 | // This enables importing modules with invalid DL strings. |
| 503 | std::string TentativeDLStr = M->getDataLayoutStr(); |
| 504 | LocTy DLStrLoc; |
| 505 | |
| 506 | bool Done = false; |
| 507 | while (!Done) { |
| 508 | switch (Lex.getKind()) { |
| 509 | case lltok::kw_target: |
| 510 | if (parseTargetDefinition(TentativeDLStr, DLStrLoc)) |
| 511 | return true; |
| 512 | break; |
| 513 | case lltok::kw_source_filename: |
| 514 | if (parseSourceFileName()) |
| 515 | return true; |
| 516 | break; |
| 517 | default: |
| 518 | Done = true; |
| 519 | } |
| 520 | } |
| 521 | // Run the override callback to potentially change the data layout string, and |
| 522 | // parse the data layout string. |
| 523 | if (auto LayoutOverride = |
| 524 | DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) { |
| 525 | TentativeDLStr = *LayoutOverride; |
| 526 | DLStrLoc = {}; |
| 527 | } |
| 528 | Expected<DataLayout> MaybeDL = DataLayout::parse(LayoutString: TentativeDLStr); |
| 529 | if (!MaybeDL) |
| 530 | return error(L: DLStrLoc, Msg: toString(E: MaybeDL.takeError())); |
| 531 | M->setDataLayout(MaybeDL.get()); |
| 532 | return false; |
| 533 | } |
| 534 | |
| 535 | bool LLParser::parseTopLevelEntities() { |
| 536 | // If there is no Module, then parse just the summary index entries. |
| 537 | if (!M) { |
| 538 | while (true) { |
| 539 | switch (Lex.getKind()) { |
| 540 | case lltok::Eof: |
| 541 | return false; |
| 542 | case lltok::SummaryID: |
| 543 | if (parseSummaryEntry()) |
| 544 | return true; |
| 545 | break; |
| 546 | case lltok::kw_source_filename: |
| 547 | if (parseSourceFileName()) |
| 548 | return true; |
| 549 | break; |
| 550 | default: |
| 551 | // Skip everything else |
| 552 | Lex.Lex(); |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | while (true) { |
| 557 | switch (Lex.getKind()) { |
| 558 | default: |
| 559 | return tokError(Msg: "expected top-level entity" ); |
| 560 | case lltok::Eof: return false; |
| 561 | case lltok::kw_declare: |
| 562 | if (parseDeclare()) |
| 563 | return true; |
| 564 | break; |
| 565 | case lltok::kw_define: |
| 566 | if (parseDefine()) |
| 567 | return true; |
| 568 | break; |
| 569 | case lltok::kw_module: |
| 570 | if (parseModuleAsm()) |
| 571 | return true; |
| 572 | break; |
| 573 | case lltok::LocalVarID: |
| 574 | if (parseUnnamedType()) |
| 575 | return true; |
| 576 | break; |
| 577 | case lltok::LocalVar: |
| 578 | if (parseNamedType()) |
| 579 | return true; |
| 580 | break; |
| 581 | case lltok::GlobalID: |
| 582 | if (parseUnnamedGlobal()) |
| 583 | return true; |
| 584 | break; |
| 585 | case lltok::GlobalVar: |
| 586 | if (parseNamedGlobal()) |
| 587 | return true; |
| 588 | break; |
| 589 | case lltok::ComdatVar: if (parseComdat()) return true; break; |
| 590 | case lltok::exclaim: |
| 591 | if (parseStandaloneMetadata()) |
| 592 | return true; |
| 593 | break; |
| 594 | case lltok::SummaryID: |
| 595 | if (parseSummaryEntry()) |
| 596 | return true; |
| 597 | break; |
| 598 | case lltok::MetadataVar: |
| 599 | if (parseNamedMetadata()) |
| 600 | return true; |
| 601 | break; |
| 602 | case lltok::kw_attributes: |
| 603 | if (parseUnnamedAttrGrp()) |
| 604 | return true; |
| 605 | break; |
| 606 | case lltok::kw_uselistorder: |
| 607 | if (parseUseListOrder()) |
| 608 | return true; |
| 609 | break; |
| 610 | case lltok::kw_uselistorder_bb: |
| 611 | if (parseUseListOrderBB()) |
| 612 | return true; |
| 613 | break; |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | /// toplevelentity |
| 619 | /// ::= 'module' 'asm' STRINGCONSTANT |
| 620 | bool LLParser::parseModuleAsm() { |
| 621 | assert(Lex.getKind() == lltok::kw_module); |
| 622 | Lex.Lex(); |
| 623 | |
| 624 | std::string AsmStr; |
| 625 | if (parseToken(T: lltok::kw_asm, ErrMsg: "expected 'module asm'" ) || |
| 626 | parseStringConstant(Result&: AsmStr)) |
| 627 | return true; |
| 628 | |
| 629 | M->appendModuleInlineAsm(Asm: AsmStr); |
| 630 | return false; |
| 631 | } |
| 632 | |
| 633 | /// toplevelentity |
| 634 | /// ::= 'target' 'triple' '=' STRINGCONSTANT |
| 635 | /// ::= 'target' 'datalayout' '=' STRINGCONSTANT |
| 636 | bool LLParser::parseTargetDefinition(std::string &TentativeDLStr, |
| 637 | LocTy &DLStrLoc) { |
| 638 | assert(Lex.getKind() == lltok::kw_target); |
| 639 | std::string Str; |
| 640 | switch (Lex.Lex()) { |
| 641 | default: |
| 642 | return tokError(Msg: "unknown target property" ); |
| 643 | case lltok::kw_triple: |
| 644 | Lex.Lex(); |
| 645 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after target triple" ) || |
| 646 | parseStringConstant(Result&: Str)) |
| 647 | return true; |
| 648 | M->setTargetTriple(Triple(std::move(Str))); |
| 649 | return false; |
| 650 | case lltok::kw_datalayout: |
| 651 | Lex.Lex(); |
| 652 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after target datalayout" )) |
| 653 | return true; |
| 654 | DLStrLoc = Lex.getLoc(); |
| 655 | if (parseStringConstant(Result&: TentativeDLStr)) |
| 656 | return true; |
| 657 | return false; |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | /// toplevelentity |
| 662 | /// ::= 'source_filename' '=' STRINGCONSTANT |
| 663 | bool LLParser::parseSourceFileName() { |
| 664 | assert(Lex.getKind() == lltok::kw_source_filename); |
| 665 | Lex.Lex(); |
| 666 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after source_filename" ) || |
| 667 | parseStringConstant(Result&: SourceFileName)) |
| 668 | return true; |
| 669 | if (M) |
| 670 | M->setSourceFileName(SourceFileName); |
| 671 | return false; |
| 672 | } |
| 673 | |
| 674 | /// parseUnnamedType: |
| 675 | /// ::= LocalVarID '=' 'type' type |
| 676 | bool LLParser::parseUnnamedType() { |
| 677 | LocTy TypeLoc = Lex.getLoc(); |
| 678 | unsigned TypeID = Lex.getUIntVal(); |
| 679 | Lex.Lex(); // eat LocalVarID; |
| 680 | |
| 681 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after name" ) || |
| 682 | parseToken(T: lltok::kw_type, ErrMsg: "expected 'type' after '='" )) |
| 683 | return true; |
| 684 | |
| 685 | Type *Result = nullptr; |
| 686 | if (parseStructDefinition(TypeLoc, Name: "" , Entry&: NumberedTypes[TypeID], ResultTy&: Result)) |
| 687 | return true; |
| 688 | |
| 689 | if (!isa<StructType>(Val: Result)) { |
| 690 | std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; |
| 691 | if (Entry.first) |
| 692 | return error(L: TypeLoc, Msg: "non-struct types may not be recursive" ); |
| 693 | Entry.first = Result; |
| 694 | Entry.second = SMLoc(); |
| 695 | } |
| 696 | |
| 697 | return false; |
| 698 | } |
| 699 | |
| 700 | /// toplevelentity |
| 701 | /// ::= LocalVar '=' 'type' type |
| 702 | bool LLParser::parseNamedType() { |
| 703 | std::string Name = Lex.getStrVal(); |
| 704 | LocTy NameLoc = Lex.getLoc(); |
| 705 | Lex.Lex(); // eat LocalVar. |
| 706 | |
| 707 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after name" ) || |
| 708 | parseToken(T: lltok::kw_type, ErrMsg: "expected 'type' after name" )) |
| 709 | return true; |
| 710 | |
| 711 | Type *Result = nullptr; |
| 712 | if (parseStructDefinition(TypeLoc: NameLoc, Name, Entry&: NamedTypes[Name], ResultTy&: Result)) |
| 713 | return true; |
| 714 | |
| 715 | if (!isa<StructType>(Val: Result)) { |
| 716 | std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; |
| 717 | if (Entry.first) |
| 718 | return error(L: NameLoc, Msg: "non-struct types may not be recursive" ); |
| 719 | Entry.first = Result; |
| 720 | Entry.second = SMLoc(); |
| 721 | } |
| 722 | |
| 723 | return false; |
| 724 | } |
| 725 | |
| 726 | /// toplevelentity |
| 727 | /// ::= 'declare' FunctionHeader |
| 728 | bool LLParser::parseDeclare() { |
| 729 | assert(Lex.getKind() == lltok::kw_declare); |
| 730 | Lex.Lex(); |
| 731 | |
| 732 | std::vector<std::pair<unsigned, MDNode *>> MDs; |
| 733 | while (Lex.getKind() == lltok::MetadataVar) { |
| 734 | unsigned MDK; |
| 735 | MDNode *N; |
| 736 | if (parseMetadataAttachment(Kind&: MDK, MD&: N)) |
| 737 | return true; |
| 738 | MDs.push_back(x: {MDK, N}); |
| 739 | } |
| 740 | |
| 741 | Function *F; |
| 742 | unsigned FunctionNumber = -1; |
| 743 | SmallVector<unsigned> UnnamedArgNums; |
| 744 | if (parseFunctionHeader(Fn&: F, IsDefine: false, FunctionNumber, UnnamedArgNums)) |
| 745 | return true; |
| 746 | for (auto &MD : MDs) |
| 747 | F->addMetadata(KindID: MD.first, MD&: *MD.second); |
| 748 | return false; |
| 749 | } |
| 750 | |
| 751 | /// toplevelentity |
| 752 | /// ::= 'define' FunctionHeader (!dbg !56)* '{' ... |
| 753 | bool LLParser::parseDefine() { |
| 754 | assert(Lex.getKind() == lltok::kw_define); |
| 755 | FileLoc FunctionStart(Lex.getTokLineColumnPos()); |
| 756 | Lex.Lex(); |
| 757 | |
| 758 | Function *F; |
| 759 | unsigned FunctionNumber = -1; |
| 760 | SmallVector<unsigned> UnnamedArgNums; |
| 761 | bool RetValue = |
| 762 | parseFunctionHeader(Fn&: F, IsDefine: true, FunctionNumber, UnnamedArgNums) || |
| 763 | parseOptionalFunctionMetadata(F&: *F) || |
| 764 | parseFunctionBody(Fn&: *F, FunctionNumber, UnnamedArgNums); |
| 765 | if (ParserContext) |
| 766 | ParserContext->addFunctionLocation( |
| 767 | F, FileLocRange(FunctionStart, Lex.getPrevTokEndLineColumnPos())); |
| 768 | |
| 769 | return RetValue; |
| 770 | } |
| 771 | |
| 772 | /// parseGlobalType |
| 773 | /// ::= 'constant' |
| 774 | /// ::= 'global' |
| 775 | bool LLParser::parseGlobalType(bool &IsConstant) { |
| 776 | if (Lex.getKind() == lltok::kw_constant) |
| 777 | IsConstant = true; |
| 778 | else if (Lex.getKind() == lltok::kw_global) |
| 779 | IsConstant = false; |
| 780 | else { |
| 781 | IsConstant = false; |
| 782 | return tokError(Msg: "expected 'global' or 'constant'" ); |
| 783 | } |
| 784 | Lex.Lex(); |
| 785 | return false; |
| 786 | } |
| 787 | |
| 788 | bool LLParser::parseOptionalUnnamedAddr( |
| 789 | GlobalVariable::UnnamedAddr &UnnamedAddr) { |
| 790 | if (EatIfPresent(T: lltok::kw_unnamed_addr)) |
| 791 | UnnamedAddr = GlobalValue::UnnamedAddr::Global; |
| 792 | else if (EatIfPresent(T: lltok::kw_local_unnamed_addr)) |
| 793 | UnnamedAddr = GlobalValue::UnnamedAddr::Local; |
| 794 | else |
| 795 | UnnamedAddr = GlobalValue::UnnamedAddr::None; |
| 796 | return false; |
| 797 | } |
| 798 | |
| 799 | /// parseUnnamedGlobal: |
| 800 | /// OptionalVisibility (ALIAS | IFUNC) ... |
| 801 | /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility |
| 802 | /// OptionalDLLStorageClass |
| 803 | /// ... -> global variable |
| 804 | /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ... |
| 805 | /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier |
| 806 | /// OptionalVisibility |
| 807 | /// OptionalDLLStorageClass |
| 808 | /// ... -> global variable |
| 809 | bool LLParser::parseUnnamedGlobal() { |
| 810 | unsigned VarID; |
| 811 | std::string Name; |
| 812 | LocTy NameLoc = Lex.getLoc(); |
| 813 | |
| 814 | // Handle the GlobalID form. |
| 815 | if (Lex.getKind() == lltok::GlobalID) { |
| 816 | VarID = Lex.getUIntVal(); |
| 817 | if (checkValueID(L: NameLoc, Kind: "global" , Prefix: "@" , NextID: NumberedVals.getNext(), ID: VarID)) |
| 818 | return true; |
| 819 | |
| 820 | Lex.Lex(); // eat GlobalID; |
| 821 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after name" )) |
| 822 | return true; |
| 823 | } else { |
| 824 | VarID = NumberedVals.getNext(); |
| 825 | } |
| 826 | |
| 827 | bool HasLinkage; |
| 828 | unsigned Linkage, Visibility, DLLStorageClass; |
| 829 | bool DSOLocal; |
| 830 | GlobalVariable::ThreadLocalMode TLM; |
| 831 | GlobalVariable::UnnamedAddr UnnamedAddr; |
| 832 | if (parseOptionalLinkage(Res&: Linkage, HasLinkage, Visibility, DLLStorageClass, |
| 833 | DSOLocal) || |
| 834 | parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) |
| 835 | return true; |
| 836 | |
| 837 | switch (Lex.getKind()) { |
| 838 | default: |
| 839 | return parseGlobal(Name, NameID: VarID, NameLoc, Linkage, HasLinkage, Visibility, |
| 840 | DLLStorageClass, DSOLocal, TLM, UnnamedAddr); |
| 841 | case lltok::kw_alias: |
| 842 | case lltok::kw_ifunc: |
| 843 | return parseAliasOrIFunc(Name, NameID: VarID, NameLoc, L: Linkage, Visibility, |
| 844 | DLLStorageClass, DSOLocal, TLM, UnnamedAddr); |
| 845 | } |
| 846 | } |
| 847 | |
| 848 | /// parseNamedGlobal: |
| 849 | /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ... |
| 850 | /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier |
| 851 | /// OptionalVisibility OptionalDLLStorageClass |
| 852 | /// ... -> global variable |
| 853 | bool LLParser::parseNamedGlobal() { |
| 854 | assert(Lex.getKind() == lltok::GlobalVar); |
| 855 | LocTy NameLoc = Lex.getLoc(); |
| 856 | std::string Name = Lex.getStrVal(); |
| 857 | Lex.Lex(); |
| 858 | |
| 859 | bool HasLinkage; |
| 860 | unsigned Linkage, Visibility, DLLStorageClass; |
| 861 | bool DSOLocal; |
| 862 | GlobalVariable::ThreadLocalMode TLM; |
| 863 | GlobalVariable::UnnamedAddr UnnamedAddr; |
| 864 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' in global variable" ) || |
| 865 | parseOptionalLinkage(Res&: Linkage, HasLinkage, Visibility, DLLStorageClass, |
| 866 | DSOLocal) || |
| 867 | parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) |
| 868 | return true; |
| 869 | |
| 870 | switch (Lex.getKind()) { |
| 871 | default: |
| 872 | return parseGlobal(Name, NameID: -1, NameLoc, Linkage, HasLinkage, Visibility, |
| 873 | DLLStorageClass, DSOLocal, TLM, UnnamedAddr); |
| 874 | case lltok::kw_alias: |
| 875 | case lltok::kw_ifunc: |
| 876 | return parseAliasOrIFunc(Name, NameID: -1, NameLoc, L: Linkage, Visibility, |
| 877 | DLLStorageClass, DSOLocal, TLM, UnnamedAddr); |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | bool LLParser::parseComdat() { |
| 882 | assert(Lex.getKind() == lltok::ComdatVar); |
| 883 | std::string Name = Lex.getStrVal(); |
| 884 | LocTy NameLoc = Lex.getLoc(); |
| 885 | Lex.Lex(); |
| 886 | |
| 887 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here" )) |
| 888 | return true; |
| 889 | |
| 890 | if (parseToken(T: lltok::kw_comdat, ErrMsg: "expected comdat keyword" )) |
| 891 | return tokError(Msg: "expected comdat type" ); |
| 892 | |
| 893 | Comdat::SelectionKind SK; |
| 894 | switch (Lex.getKind()) { |
| 895 | default: |
| 896 | return tokError(Msg: "unknown selection kind" ); |
| 897 | case lltok::kw_any: |
| 898 | SK = Comdat::Any; |
| 899 | break; |
| 900 | case lltok::kw_exactmatch: |
| 901 | SK = Comdat::ExactMatch; |
| 902 | break; |
| 903 | case lltok::kw_largest: |
| 904 | SK = Comdat::Largest; |
| 905 | break; |
| 906 | case lltok::kw_nodeduplicate: |
| 907 | SK = Comdat::NoDeduplicate; |
| 908 | break; |
| 909 | case lltok::kw_samesize: |
| 910 | SK = Comdat::SameSize; |
| 911 | break; |
| 912 | } |
| 913 | Lex.Lex(); |
| 914 | |
| 915 | // See if the comdat was forward referenced, if so, use the comdat. |
| 916 | Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); |
| 917 | Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Key: Name); |
| 918 | if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(x: Name)) |
| 919 | return error(L: NameLoc, Msg: "redefinition of comdat '$" + Name + "'" ); |
| 920 | |
| 921 | Comdat *C; |
| 922 | if (I != ComdatSymTab.end()) |
| 923 | C = &I->second; |
| 924 | else |
| 925 | C = M->getOrInsertComdat(Name); |
| 926 | C->setSelectionKind(SK); |
| 927 | |
| 928 | return false; |
| 929 | } |
| 930 | |
| 931 | // MDString: |
| 932 | // ::= '!' STRINGCONSTANT |
| 933 | bool LLParser::parseMDString(MDString *&Result) { |
| 934 | std::string Str; |
| 935 | if (parseStringConstant(Result&: Str)) |
| 936 | return true; |
| 937 | Result = MDString::get(Context, Str); |
| 938 | return false; |
| 939 | } |
| 940 | |
| 941 | // MDNode: |
| 942 | // ::= '!' MDNodeNumber |
| 943 | bool LLParser::parseMDNodeID(MDNode *&Result) { |
| 944 | // !{ ..., !42, ... } |
| 945 | LocTy IDLoc = Lex.getLoc(); |
| 946 | unsigned MID = 0; |
| 947 | if (parseUInt32(Val&: MID)) |
| 948 | return true; |
| 949 | |
| 950 | // If not a forward reference, just return it now. |
| 951 | auto [It, Inserted] = NumberedMetadata.try_emplace(k: MID); |
| 952 | if (!Inserted) { |
| 953 | Result = It->second; |
| 954 | return false; |
| 955 | } |
| 956 | |
| 957 | // Otherwise, create MDNode forward reference. |
| 958 | auto &FwdRef = ForwardRefMDNodes[MID]; |
| 959 | FwdRef = std::make_pair(x: MDTuple::getTemporary(Context, MDs: {}), y&: IDLoc); |
| 960 | |
| 961 | Result = FwdRef.first.get(); |
| 962 | It->second.reset(MD: Result); |
| 963 | return false; |
| 964 | } |
| 965 | |
| 966 | /// parseNamedMetadata: |
| 967 | /// !foo = !{ !1, !2 } |
| 968 | bool LLParser::parseNamedMetadata() { |
| 969 | assert(Lex.getKind() == lltok::MetadataVar); |
| 970 | std::string Name = Lex.getStrVal(); |
| 971 | Lex.Lex(); |
| 972 | |
| 973 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here" ) || |
| 974 | parseToken(T: lltok::exclaim, ErrMsg: "Expected '!' here" ) || |
| 975 | parseToken(T: lltok::lbrace, ErrMsg: "Expected '{' here" )) |
| 976 | return true; |
| 977 | |
| 978 | NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); |
| 979 | if (Lex.getKind() != lltok::rbrace) |
| 980 | do { |
| 981 | MDNode *N = nullptr; |
| 982 | // parse DIExpressions inline as a special case. They are still MDNodes, |
| 983 | // so they can still appear in named metadata. Remove this logic if they |
| 984 | // become plain Metadata. |
| 985 | if (Lex.getKind() == lltok::MetadataVar && |
| 986 | Lex.getStrVal() == "DIExpression" ) { |
| 987 | if (parseDIExpression(Result&: N, /*IsDistinct=*/false)) |
| 988 | return true; |
| 989 | // DIArgLists should only appear inline in a function, as they may |
| 990 | // contain LocalAsMetadata arguments which require a function context. |
| 991 | } else if (Lex.getKind() == lltok::MetadataVar && |
| 992 | Lex.getStrVal() == "DIArgList" ) { |
| 993 | return tokError(Msg: "found DIArgList outside of function" ); |
| 994 | } else if (parseToken(T: lltok::exclaim, ErrMsg: "Expected '!' here" ) || |
| 995 | parseMDNodeID(Result&: N)) { |
| 996 | return true; |
| 997 | } |
| 998 | NMD->addOperand(M: N); |
| 999 | } while (EatIfPresent(T: lltok::comma)); |
| 1000 | |
| 1001 | return parseToken(T: lltok::rbrace, ErrMsg: "expected end of metadata node" ); |
| 1002 | } |
| 1003 | |
| 1004 | /// parseStandaloneMetadata: |
| 1005 | /// !42 = !{...} |
| 1006 | bool LLParser::parseStandaloneMetadata() { |
| 1007 | assert(Lex.getKind() == lltok::exclaim); |
| 1008 | Lex.Lex(); |
| 1009 | unsigned MetadataID = 0; |
| 1010 | |
| 1011 | MDNode *Init; |
| 1012 | if (parseUInt32(Val&: MetadataID) || parseToken(T: lltok::equal, ErrMsg: "expected '=' here" )) |
| 1013 | return true; |
| 1014 | |
| 1015 | // Detect common error, from old metadata syntax. |
| 1016 | if (Lex.getKind() == lltok::Type) |
| 1017 | return tokError(Msg: "unexpected type in metadata definition" ); |
| 1018 | |
| 1019 | bool IsDistinct = EatIfPresent(T: lltok::kw_distinct); |
| 1020 | if (Lex.getKind() == lltok::MetadataVar) { |
| 1021 | if (parseSpecializedMDNode(N&: Init, IsDistinct)) |
| 1022 | return true; |
| 1023 | } else if (parseToken(T: lltok::exclaim, ErrMsg: "Expected '!' here" ) || |
| 1024 | parseMDTuple(MD&: Init, IsDistinct)) |
| 1025 | return true; |
| 1026 | |
| 1027 | // See if this was forward referenced, if so, handle it. |
| 1028 | auto FI = ForwardRefMDNodes.find(x: MetadataID); |
| 1029 | if (FI != ForwardRefMDNodes.end()) { |
| 1030 | auto *ToReplace = FI->second.first.get(); |
| 1031 | // DIAssignID has its own special forward-reference "replacement" for |
| 1032 | // attachments (the temporary attachments are never actually attached). |
| 1033 | if (isa<DIAssignID>(Val: Init)) { |
| 1034 | for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) { |
| 1035 | assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) && |
| 1036 | "Inst unexpectedly already has DIAssignID attachment" ); |
| 1037 | Inst->setMetadata(KindID: LLVMContext::MD_DIAssignID, Node: Init); |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | ToReplace->replaceAllUsesWith(MD: Init); |
| 1042 | ForwardRefMDNodes.erase(position: FI); |
| 1043 | |
| 1044 | assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work" ); |
| 1045 | } else { |
| 1046 | auto [It, Inserted] = NumberedMetadata.try_emplace(k: MetadataID); |
| 1047 | if (!Inserted) |
| 1048 | return tokError(Msg: "Metadata id is already used" ); |
| 1049 | It->second.reset(MD: Init); |
| 1050 | } |
| 1051 | |
| 1052 | return false; |
| 1053 | } |
| 1054 | |
| 1055 | // Skips a single module summary entry. |
| 1056 | bool LLParser::skipModuleSummaryEntry() { |
| 1057 | // Each module summary entry consists of a tag for the entry |
| 1058 | // type, followed by a colon, then the fields which may be surrounded by |
| 1059 | // nested sets of parentheses. The "tag:" looks like a Label. Once parsing |
| 1060 | // support is in place we will look for the tokens corresponding to the |
| 1061 | // expected tags. |
| 1062 | if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module && |
| 1063 | Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags && |
| 1064 | Lex.getKind() != lltok::kw_blockcount) |
| 1065 | return tokError( |
| 1066 | Msg: "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the " |
| 1067 | "start of summary entry" ); |
| 1068 | if (Lex.getKind() == lltok::kw_flags) |
| 1069 | return parseSummaryIndexFlags(); |
| 1070 | if (Lex.getKind() == lltok::kw_blockcount) |
| 1071 | return parseBlockCount(); |
| 1072 | Lex.Lex(); |
| 1073 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' at start of summary entry" ) || |
| 1074 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' at start of summary entry" )) |
| 1075 | return true; |
| 1076 | // Now walk through the parenthesized entry, until the number of open |
| 1077 | // parentheses goes back down to 0 (the first '(' was parsed above). |
| 1078 | unsigned NumOpenParen = 1; |
| 1079 | do { |
| 1080 | switch (Lex.getKind()) { |
| 1081 | case lltok::lparen: |
| 1082 | NumOpenParen++; |
| 1083 | break; |
| 1084 | case lltok::rparen: |
| 1085 | NumOpenParen--; |
| 1086 | break; |
| 1087 | case lltok::Eof: |
| 1088 | return tokError(Msg: "found end of file while parsing summary entry" ); |
| 1089 | default: |
| 1090 | // Skip everything in between parentheses. |
| 1091 | break; |
| 1092 | } |
| 1093 | Lex.Lex(); |
| 1094 | } while (NumOpenParen > 0); |
| 1095 | return false; |
| 1096 | } |
| 1097 | |
| 1098 | /// SummaryEntry |
| 1099 | /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry |
| 1100 | bool LLParser::parseSummaryEntry() { |
| 1101 | assert(Lex.getKind() == lltok::SummaryID); |
| 1102 | unsigned SummaryID = Lex.getUIntVal(); |
| 1103 | |
| 1104 | // For summary entries, colons should be treated as distinct tokens, |
| 1105 | // not an indication of the end of a label token. |
| 1106 | Lex.setIgnoreColonInIdentifiers(true); |
| 1107 | |
| 1108 | Lex.Lex(); |
| 1109 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here" )) |
| 1110 | return true; |
| 1111 | |
| 1112 | // If we don't have an index object, skip the summary entry. |
| 1113 | if (!Index) |
| 1114 | return skipModuleSummaryEntry(); |
| 1115 | |
| 1116 | bool result = false; |
| 1117 | switch (Lex.getKind()) { |
| 1118 | case lltok::kw_gv: |
| 1119 | result = parseGVEntry(ID: SummaryID); |
| 1120 | break; |
| 1121 | case lltok::kw_module: |
| 1122 | result = parseModuleEntry(ID: SummaryID); |
| 1123 | break; |
| 1124 | case lltok::kw_typeid: |
| 1125 | result = parseTypeIdEntry(ID: SummaryID); |
| 1126 | break; |
| 1127 | case lltok::kw_typeidCompatibleVTable: |
| 1128 | result = parseTypeIdCompatibleVtableEntry(ID: SummaryID); |
| 1129 | break; |
| 1130 | case lltok::kw_flags: |
| 1131 | result = parseSummaryIndexFlags(); |
| 1132 | break; |
| 1133 | case lltok::kw_blockcount: |
| 1134 | result = parseBlockCount(); |
| 1135 | break; |
| 1136 | default: |
| 1137 | result = error(L: Lex.getLoc(), Msg: "unexpected summary kind" ); |
| 1138 | break; |
| 1139 | } |
| 1140 | Lex.setIgnoreColonInIdentifiers(false); |
| 1141 | return result; |
| 1142 | } |
| 1143 | |
| 1144 | static bool isValidVisibilityForLinkage(unsigned V, unsigned L) { |
| 1145 | return !GlobalValue::isLocalLinkage(Linkage: (GlobalValue::LinkageTypes)L) || |
| 1146 | (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility; |
| 1147 | } |
| 1148 | static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) { |
| 1149 | return !GlobalValue::isLocalLinkage(Linkage: (GlobalValue::LinkageTypes)L) || |
| 1150 | (GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass; |
| 1151 | } |
| 1152 | |
| 1153 | // If there was an explicit dso_local, update GV. In the absence of an explicit |
| 1154 | // dso_local we keep the default value. |
| 1155 | static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) { |
| 1156 | if (DSOLocal) |
| 1157 | GV.setDSOLocal(true); |
| 1158 | } |
| 1159 | |
| 1160 | /// parseAliasOrIFunc: |
| 1161 | /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier |
| 1162 | /// OptionalVisibility OptionalDLLStorageClass |
| 1163 | /// OptionalThreadLocal OptionalUnnamedAddr |
| 1164 | /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs* |
| 1165 | /// |
| 1166 | /// AliaseeOrResolver |
| 1167 | /// ::= TypeAndValue |
| 1168 | /// |
| 1169 | /// SymbolAttrs |
| 1170 | /// ::= ',' 'partition' StringConstant |
| 1171 | /// |
| 1172 | /// Everything through OptionalUnnamedAddr has already been parsed. |
| 1173 | /// |
| 1174 | bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID, |
| 1175 | LocTy NameLoc, unsigned L, unsigned Visibility, |
| 1176 | unsigned DLLStorageClass, bool DSOLocal, |
| 1177 | GlobalVariable::ThreadLocalMode TLM, |
| 1178 | GlobalVariable::UnnamedAddr UnnamedAddr) { |
| 1179 | bool IsAlias; |
| 1180 | if (Lex.getKind() == lltok::kw_alias) |
| 1181 | IsAlias = true; |
| 1182 | else if (Lex.getKind() == lltok::kw_ifunc) |
| 1183 | IsAlias = false; |
| 1184 | else |
| 1185 | llvm_unreachable("Not an alias or ifunc!" ); |
| 1186 | Lex.Lex(); |
| 1187 | |
| 1188 | GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L; |
| 1189 | |
| 1190 | if(IsAlias && !GlobalAlias::isValidLinkage(L: Linkage)) |
| 1191 | return error(L: NameLoc, Msg: "invalid linkage type for alias" ); |
| 1192 | |
| 1193 | if (!isValidVisibilityForLinkage(V: Visibility, L)) |
| 1194 | return error(L: NameLoc, |
| 1195 | Msg: "symbol with local linkage must have default visibility" ); |
| 1196 | |
| 1197 | if (!isValidDLLStorageClassForLinkage(S: DLLStorageClass, L)) |
| 1198 | return error(L: NameLoc, |
| 1199 | Msg: "symbol with local linkage cannot have a DLL storage class" ); |
| 1200 | |
| 1201 | Type *Ty; |
| 1202 | LocTy ExplicitTypeLoc = Lex.getLoc(); |
| 1203 | if (parseType(Result&: Ty) || |
| 1204 | parseToken(T: lltok::comma, ErrMsg: "expected comma after alias or ifunc's type" )) |
| 1205 | return true; |
| 1206 | |
| 1207 | Constant *Aliasee; |
| 1208 | LocTy AliaseeLoc = Lex.getLoc(); |
| 1209 | if (Lex.getKind() != lltok::kw_bitcast && |
| 1210 | Lex.getKind() != lltok::kw_getelementptr && |
| 1211 | Lex.getKind() != lltok::kw_addrspacecast && |
| 1212 | Lex.getKind() != lltok::kw_inttoptr) { |
| 1213 | if (parseGlobalTypeAndValue(V&: Aliasee)) |
| 1214 | return true; |
| 1215 | } else { |
| 1216 | // The bitcast dest type is not present, it is implied by the dest type. |
| 1217 | ValID ID; |
| 1218 | if (parseValID(ID, /*PFS=*/nullptr)) |
| 1219 | return true; |
| 1220 | if (ID.Kind != ValID::t_Constant) |
| 1221 | return error(L: AliaseeLoc, Msg: "invalid aliasee" ); |
| 1222 | Aliasee = ID.ConstantVal; |
| 1223 | } |
| 1224 | |
| 1225 | Type *AliaseeType = Aliasee->getType(); |
| 1226 | auto *PTy = dyn_cast<PointerType>(Val: AliaseeType); |
| 1227 | if (!PTy) |
| 1228 | return error(L: AliaseeLoc, Msg: "An alias or ifunc must have pointer type" ); |
| 1229 | unsigned AddrSpace = PTy->getAddressSpace(); |
| 1230 | |
| 1231 | GlobalValue *GVal = nullptr; |
| 1232 | |
| 1233 | // See if the alias was forward referenced, if so, prepare to replace the |
| 1234 | // forward reference. |
| 1235 | if (!Name.empty()) { |
| 1236 | auto I = ForwardRefVals.find(x: Name); |
| 1237 | if (I != ForwardRefVals.end()) { |
| 1238 | GVal = I->second.first; |
| 1239 | ForwardRefVals.erase(x: Name); |
| 1240 | } else if (M->getNamedValue(Name)) { |
| 1241 | return error(L: NameLoc, Msg: "redefinition of global '@" + Name + "'" ); |
| 1242 | } |
| 1243 | } else { |
| 1244 | auto I = ForwardRefValIDs.find(x: NameID); |
| 1245 | if (I != ForwardRefValIDs.end()) { |
| 1246 | GVal = I->second.first; |
| 1247 | ForwardRefValIDs.erase(position: I); |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | // Okay, create the alias/ifunc but do not insert it into the module yet. |
| 1252 | std::unique_ptr<GlobalAlias> GA; |
| 1253 | std::unique_ptr<GlobalIFunc> GI; |
| 1254 | GlobalValue *GV; |
| 1255 | if (IsAlias) { |
| 1256 | GA.reset(p: GlobalAlias::create(Ty, AddressSpace: AddrSpace, Linkage, Name, Aliasee, |
| 1257 | /*Parent=*/nullptr)); |
| 1258 | GV = GA.get(); |
| 1259 | } else { |
| 1260 | GI.reset(p: GlobalIFunc::create(Ty, AddressSpace: AddrSpace, Linkage, Name, Resolver: Aliasee, |
| 1261 | /*Parent=*/nullptr)); |
| 1262 | GV = GI.get(); |
| 1263 | } |
| 1264 | GV->setThreadLocalMode(TLM); |
| 1265 | GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); |
| 1266 | GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); |
| 1267 | GV->setUnnamedAddr(UnnamedAddr); |
| 1268 | maybeSetDSOLocal(DSOLocal, GV&: *GV); |
| 1269 | |
| 1270 | // At this point we've parsed everything except for the IndirectSymbolAttrs. |
| 1271 | // Now parse them if there are any. |
| 1272 | while (Lex.getKind() == lltok::comma) { |
| 1273 | Lex.Lex(); |
| 1274 | |
| 1275 | if (Lex.getKind() == lltok::kw_partition) { |
| 1276 | Lex.Lex(); |
| 1277 | GV->setPartition(Lex.getStrVal()); |
| 1278 | if (parseToken(T: lltok::StringConstant, ErrMsg: "expected partition string" )) |
| 1279 | return true; |
| 1280 | } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) { |
| 1281 | if (parseGlobalObjectMetadataAttachment(GO&: *GI)) |
| 1282 | return true; |
| 1283 | } else { |
| 1284 | return tokError(Msg: "unknown alias or ifunc property!" ); |
| 1285 | } |
| 1286 | } |
| 1287 | |
| 1288 | if (Name.empty()) |
| 1289 | NumberedVals.add(ID: NameID, V: GV); |
| 1290 | |
| 1291 | if (GVal) { |
| 1292 | // Verify that types agree. |
| 1293 | if (GVal->getType() != GV->getType()) |
| 1294 | return error( |
| 1295 | L: ExplicitTypeLoc, |
| 1296 | Msg: "forward reference and definition of alias have different types" ); |
| 1297 | |
| 1298 | // If they agree, just RAUW the old value with the alias and remove the |
| 1299 | // forward ref info. |
| 1300 | GVal->replaceAllUsesWith(V: GV); |
| 1301 | GVal->eraseFromParent(); |
| 1302 | } |
| 1303 | |
| 1304 | // Insert into the module, we know its name won't collide now. |
| 1305 | if (IsAlias) |
| 1306 | M->insertAlias(Alias: GA.release()); |
| 1307 | else |
| 1308 | M->insertIFunc(IFunc: GI.release()); |
| 1309 | assert(GV->getName() == Name && "Should not be a name conflict!" ); |
| 1310 | |
| 1311 | return false; |
| 1312 | } |
| 1313 | |
| 1314 | static bool isSanitizer(lltok::Kind Kind) { |
| 1315 | switch (Kind) { |
| 1316 | case lltok::kw_no_sanitize_address: |
| 1317 | case lltok::kw_no_sanitize_hwaddress: |
| 1318 | case lltok::kw_sanitize_memtag: |
| 1319 | case lltok::kw_sanitize_address_dyninit: |
| 1320 | return true; |
| 1321 | default: |
| 1322 | return false; |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | bool LLParser::parseSanitizer(GlobalVariable *GV) { |
| 1327 | using SanitizerMetadata = GlobalValue::SanitizerMetadata; |
| 1328 | SanitizerMetadata Meta; |
| 1329 | if (GV->hasSanitizerMetadata()) |
| 1330 | Meta = GV->getSanitizerMetadata(); |
| 1331 | |
| 1332 | switch (Lex.getKind()) { |
| 1333 | case lltok::kw_no_sanitize_address: |
| 1334 | Meta.NoAddress = true; |
| 1335 | break; |
| 1336 | case lltok::kw_no_sanitize_hwaddress: |
| 1337 | Meta.NoHWAddress = true; |
| 1338 | break; |
| 1339 | case lltok::kw_sanitize_memtag: |
| 1340 | Meta.Memtag = true; |
| 1341 | break; |
| 1342 | case lltok::kw_sanitize_address_dyninit: |
| 1343 | Meta.IsDynInit = true; |
| 1344 | break; |
| 1345 | default: |
| 1346 | return tokError(Msg: "non-sanitizer token passed to LLParser::parseSanitizer()" ); |
| 1347 | } |
| 1348 | GV->setSanitizerMetadata(Meta); |
| 1349 | Lex.Lex(); |
| 1350 | return false; |
| 1351 | } |
| 1352 | |
| 1353 | /// parseGlobal |
| 1354 | /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier |
| 1355 | /// OptionalVisibility OptionalDLLStorageClass |
| 1356 | /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace |
| 1357 | /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs |
| 1358 | /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility |
| 1359 | /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr |
| 1360 | /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type |
| 1361 | /// Const OptionalAttrs |
| 1362 | /// |
| 1363 | /// Everything up to and including OptionalUnnamedAddr has been parsed |
| 1364 | /// already. |
| 1365 | /// |
| 1366 | bool LLParser::parseGlobal(const std::string &Name, unsigned NameID, |
| 1367 | LocTy NameLoc, unsigned Linkage, bool HasLinkage, |
| 1368 | unsigned Visibility, unsigned DLLStorageClass, |
| 1369 | bool DSOLocal, GlobalVariable::ThreadLocalMode TLM, |
| 1370 | GlobalVariable::UnnamedAddr UnnamedAddr) { |
| 1371 | if (!isValidVisibilityForLinkage(V: Visibility, L: Linkage)) |
| 1372 | return error(L: NameLoc, |
| 1373 | Msg: "symbol with local linkage must have default visibility" ); |
| 1374 | |
| 1375 | if (!isValidDLLStorageClassForLinkage(S: DLLStorageClass, L: Linkage)) |
| 1376 | return error(L: NameLoc, |
| 1377 | Msg: "symbol with local linkage cannot have a DLL storage class" ); |
| 1378 | |
| 1379 | unsigned AddrSpace; |
| 1380 | bool IsConstant, IsExternallyInitialized; |
| 1381 | LocTy IsExternallyInitializedLoc; |
| 1382 | LocTy TyLoc; |
| 1383 | |
| 1384 | Type *Ty = nullptr; |
| 1385 | if (parseOptionalAddrSpace(AddrSpace) || |
| 1386 | parseOptionalToken(T: lltok::kw_externally_initialized, |
| 1387 | Present&: IsExternallyInitialized, |
| 1388 | Loc: &IsExternallyInitializedLoc) || |
| 1389 | parseGlobalType(IsConstant) || parseType(Result&: Ty, Loc&: TyLoc)) |
| 1390 | return true; |
| 1391 | |
| 1392 | // If the linkage is specified and is external, then no initializer is |
| 1393 | // present. |
| 1394 | Constant *Init = nullptr; |
| 1395 | if (!HasLinkage || |
| 1396 | !GlobalValue::isValidDeclarationLinkage( |
| 1397 | Linkage: (GlobalValue::LinkageTypes)Linkage)) { |
| 1398 | if (parseGlobalValue(Ty, C&: Init)) |
| 1399 | return true; |
| 1400 | } |
| 1401 | |
| 1402 | if (Ty->isFunctionTy() || !PointerType::isValidElementType(ElemTy: Ty)) |
| 1403 | return error(L: TyLoc, Msg: "invalid type for global variable" ); |
| 1404 | |
| 1405 | GlobalValue *GVal = nullptr; |
| 1406 | |
| 1407 | // See if the global was forward referenced, if so, use the global. |
| 1408 | if (!Name.empty()) { |
| 1409 | auto I = ForwardRefVals.find(x: Name); |
| 1410 | if (I != ForwardRefVals.end()) { |
| 1411 | GVal = I->second.first; |
| 1412 | ForwardRefVals.erase(position: I); |
| 1413 | } else if (M->getNamedValue(Name)) { |
| 1414 | return error(L: NameLoc, Msg: "redefinition of global '@" + Name + "'" ); |
| 1415 | } |
| 1416 | } else { |
| 1417 | // Handle @"", where a name is syntactically specified, but semantically |
| 1418 | // missing. |
| 1419 | if (NameID == (unsigned)-1) |
| 1420 | NameID = NumberedVals.getNext(); |
| 1421 | |
| 1422 | auto I = ForwardRefValIDs.find(x: NameID); |
| 1423 | if (I != ForwardRefValIDs.end()) { |
| 1424 | GVal = I->second.first; |
| 1425 | ForwardRefValIDs.erase(position: I); |
| 1426 | } |
| 1427 | } |
| 1428 | |
| 1429 | GlobalVariable *GV = new GlobalVariable( |
| 1430 | *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr, |
| 1431 | GlobalVariable::NotThreadLocal, AddrSpace); |
| 1432 | |
| 1433 | if (Name.empty()) |
| 1434 | NumberedVals.add(ID: NameID, V: GV); |
| 1435 | |
| 1436 | // Set the parsed properties on the global. |
| 1437 | if (Init) |
| 1438 | GV->setInitializer(Init); |
| 1439 | GV->setConstant(IsConstant); |
| 1440 | GV->setLinkage((GlobalValue::LinkageTypes)Linkage); |
| 1441 | maybeSetDSOLocal(DSOLocal, GV&: *GV); |
| 1442 | GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); |
| 1443 | GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); |
| 1444 | GV->setExternallyInitialized(IsExternallyInitialized); |
| 1445 | GV->setThreadLocalMode(TLM); |
| 1446 | GV->setUnnamedAddr(UnnamedAddr); |
| 1447 | |
| 1448 | if (GVal) { |
| 1449 | if (GVal->getAddressSpace() != AddrSpace) |
| 1450 | return error( |
| 1451 | L: TyLoc, |
| 1452 | Msg: "forward reference and definition of global have different types" ); |
| 1453 | |
| 1454 | GVal->replaceAllUsesWith(V: GV); |
| 1455 | GVal->eraseFromParent(); |
| 1456 | } |
| 1457 | |
| 1458 | // parse attributes on the global. |
| 1459 | while (Lex.getKind() == lltok::comma) { |
| 1460 | Lex.Lex(); |
| 1461 | |
| 1462 | if (Lex.getKind() == lltok::kw_section) { |
| 1463 | Lex.Lex(); |
| 1464 | GV->setSection(Lex.getStrVal()); |
| 1465 | if (parseToken(T: lltok::StringConstant, ErrMsg: "expected global section string" )) |
| 1466 | return true; |
| 1467 | } else if (Lex.getKind() == lltok::kw_partition) { |
| 1468 | Lex.Lex(); |
| 1469 | GV->setPartition(Lex.getStrVal()); |
| 1470 | if (parseToken(T: lltok::StringConstant, ErrMsg: "expected partition string" )) |
| 1471 | return true; |
| 1472 | } else if (Lex.getKind() == lltok::kw_align) { |
| 1473 | MaybeAlign Alignment; |
| 1474 | if (parseOptionalAlignment(Alignment)) |
| 1475 | return true; |
| 1476 | if (Alignment) |
| 1477 | GV->setAlignment(*Alignment); |
| 1478 | } else if (Lex.getKind() == lltok::kw_code_model) { |
| 1479 | CodeModel::Model CodeModel; |
| 1480 | if (parseOptionalCodeModel(model&: CodeModel)) |
| 1481 | return true; |
| 1482 | GV->setCodeModel(CodeModel); |
| 1483 | } else if (Lex.getKind() == lltok::MetadataVar) { |
| 1484 | if (parseGlobalObjectMetadataAttachment(GO&: *GV)) |
| 1485 | return true; |
| 1486 | } else if (isSanitizer(Kind: Lex.getKind())) { |
| 1487 | if (parseSanitizer(GV)) |
| 1488 | return true; |
| 1489 | } else { |
| 1490 | Comdat *C; |
| 1491 | if (parseOptionalComdat(GlobalName: Name, C)) |
| 1492 | return true; |
| 1493 | if (C) |
| 1494 | GV->setComdat(C); |
| 1495 | else |
| 1496 | return tokError(Msg: "unknown global variable property!" ); |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | AttrBuilder Attrs(M->getContext()); |
| 1501 | LocTy BuiltinLoc; |
| 1502 | std::vector<unsigned> FwdRefAttrGrps; |
| 1503 | if (parseFnAttributeValuePairs(B&: Attrs, FwdRefAttrGrps, inAttrGrp: false, BuiltinLoc)) |
| 1504 | return true; |
| 1505 | if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) { |
| 1506 | GV->setAttributes(AttributeSet::get(C&: Context, B: Attrs)); |
| 1507 | ForwardRefAttrGroups[GV] = FwdRefAttrGrps; |
| 1508 | } |
| 1509 | |
| 1510 | return false; |
| 1511 | } |
| 1512 | |
| 1513 | /// parseUnnamedAttrGrp |
| 1514 | /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' |
| 1515 | bool LLParser::parseUnnamedAttrGrp() { |
| 1516 | assert(Lex.getKind() == lltok::kw_attributes); |
| 1517 | LocTy AttrGrpLoc = Lex.getLoc(); |
| 1518 | Lex.Lex(); |
| 1519 | |
| 1520 | if (Lex.getKind() != lltok::AttrGrpID) |
| 1521 | return tokError(Msg: "expected attribute group id" ); |
| 1522 | |
| 1523 | unsigned VarID = Lex.getUIntVal(); |
| 1524 | std::vector<unsigned> unused; |
| 1525 | LocTy BuiltinLoc; |
| 1526 | Lex.Lex(); |
| 1527 | |
| 1528 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here" ) || |
| 1529 | parseToken(T: lltok::lbrace, ErrMsg: "expected '{' here" )) |
| 1530 | return true; |
| 1531 | |
| 1532 | auto R = NumberedAttrBuilders.find(x: VarID); |
| 1533 | if (R == NumberedAttrBuilders.end()) |
| 1534 | R = NumberedAttrBuilders.emplace(args&: VarID, args: AttrBuilder(M->getContext())).first; |
| 1535 | |
| 1536 | if (parseFnAttributeValuePairs(B&: R->second, FwdRefAttrGrps&: unused, inAttrGrp: true, BuiltinLoc) || |
| 1537 | parseToken(T: lltok::rbrace, ErrMsg: "expected end of attribute group" )) |
| 1538 | return true; |
| 1539 | |
| 1540 | if (!R->second.hasAttributes()) |
| 1541 | return error(L: AttrGrpLoc, Msg: "attribute group has no attributes" ); |
| 1542 | |
| 1543 | return false; |
| 1544 | } |
| 1545 | |
| 1546 | static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) { |
| 1547 | switch (Kind) { |
| 1548 | #define GET_ATTR_NAMES |
| 1549 | #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ |
| 1550 | case lltok::kw_##DISPLAY_NAME: \ |
| 1551 | return Attribute::ENUM_NAME; |
| 1552 | #include "llvm/IR/Attributes.inc" |
| 1553 | default: |
| 1554 | return Attribute::None; |
| 1555 | } |
| 1556 | } |
| 1557 | |
| 1558 | bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B, |
| 1559 | bool InAttrGroup) { |
| 1560 | if (Attribute::isTypeAttrKind(Kind: Attr)) |
| 1561 | return parseRequiredTypeAttr(B, AttrToken: Lex.getKind(), AttrKind: Attr); |
| 1562 | |
| 1563 | switch (Attr) { |
| 1564 | case Attribute::Alignment: { |
| 1565 | MaybeAlign Alignment; |
| 1566 | if (InAttrGroup) { |
| 1567 | uint32_t Value = 0; |
| 1568 | Lex.Lex(); |
| 1569 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here" ) || parseUInt32(Val&: Value)) |
| 1570 | return true; |
| 1571 | Alignment = Align(Value); |
| 1572 | } else { |
| 1573 | if (parseOptionalAlignment(Alignment, AllowParens: true)) |
| 1574 | return true; |
| 1575 | } |
| 1576 | B.addAlignmentAttr(Align: Alignment); |
| 1577 | return false; |
| 1578 | } |
| 1579 | case Attribute::StackAlignment: { |
| 1580 | unsigned Alignment; |
| 1581 | if (InAttrGroup) { |
| 1582 | Lex.Lex(); |
| 1583 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here" ) || |
| 1584 | parseUInt32(Val&: Alignment)) |
| 1585 | return true; |
| 1586 | } else { |
| 1587 | if (parseOptionalStackAlignment(Alignment)) |
| 1588 | return true; |
| 1589 | } |
| 1590 | B.addStackAlignmentAttr(Align: Alignment); |
| 1591 | return false; |
| 1592 | } |
| 1593 | case Attribute::AllocSize: { |
| 1594 | unsigned ElemSizeArg; |
| 1595 | std::optional<unsigned> NumElemsArg; |
| 1596 | if (parseAllocSizeArguments(BaseSizeArg&: ElemSizeArg, HowManyArg&: NumElemsArg)) |
| 1597 | return true; |
| 1598 | B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); |
| 1599 | return false; |
| 1600 | } |
| 1601 | case Attribute::VScaleRange: { |
| 1602 | unsigned MinValue, MaxValue; |
| 1603 | if (parseVScaleRangeArguments(MinValue, MaxValue)) |
| 1604 | return true; |
| 1605 | B.addVScaleRangeAttr(MinValue, |
| 1606 | MaxValue: MaxValue > 0 ? MaxValue : std::optional<unsigned>()); |
| 1607 | return false; |
| 1608 | } |
| 1609 | case Attribute::Dereferenceable: { |
| 1610 | std::optional<uint64_t> Bytes; |
| 1611 | if (parseOptionalAttrBytes(AttrKind: lltok::kw_dereferenceable, Bytes)) |
| 1612 | return true; |
| 1613 | assert(Bytes.has_value()); |
| 1614 | B.addDereferenceableAttr(Bytes: Bytes.value()); |
| 1615 | return false; |
| 1616 | } |
| 1617 | case Attribute::DeadOnReturn: { |
| 1618 | std::optional<uint64_t> Bytes; |
| 1619 | if (parseOptionalAttrBytes(AttrKind: lltok::kw_dead_on_return, Bytes, |
| 1620 | /*ErrorNoBytes=*/false)) |
| 1621 | return true; |
| 1622 | if (Bytes.has_value()) { |
| 1623 | B.addDeadOnReturnAttr(Info: DeadOnReturnInfo(Bytes.value())); |
| 1624 | } else { |
| 1625 | B.addDeadOnReturnAttr(Info: DeadOnReturnInfo()); |
| 1626 | } |
| 1627 | return false; |
| 1628 | } |
| 1629 | case Attribute::DereferenceableOrNull: { |
| 1630 | std::optional<uint64_t> Bytes; |
| 1631 | if (parseOptionalAttrBytes(AttrKind: lltok::kw_dereferenceable_or_null, Bytes)) |
| 1632 | return true; |
| 1633 | assert(Bytes.has_value()); |
| 1634 | B.addDereferenceableOrNullAttr(Bytes: Bytes.value()); |
| 1635 | return false; |
| 1636 | } |
| 1637 | case Attribute::UWTable: { |
| 1638 | UWTableKind Kind; |
| 1639 | if (parseOptionalUWTableKind(Kind)) |
| 1640 | return true; |
| 1641 | B.addUWTableAttr(Kind); |
| 1642 | return false; |
| 1643 | } |
| 1644 | case Attribute::AllocKind: { |
| 1645 | AllocFnKind Kind = AllocFnKind::Unknown; |
| 1646 | if (parseAllocKind(Kind)) |
| 1647 | return true; |
| 1648 | B.addAllocKindAttr(Kind); |
| 1649 | return false; |
| 1650 | } |
| 1651 | case Attribute::Memory: { |
| 1652 | std::optional<MemoryEffects> ME = parseMemoryAttr(); |
| 1653 | if (!ME) |
| 1654 | return true; |
| 1655 | B.addMemoryAttr(ME: *ME); |
| 1656 | return false; |
| 1657 | } |
| 1658 | case Attribute::NoFPClass: { |
| 1659 | if (FPClassTest NoFPClass = |
| 1660 | static_cast<FPClassTest>(parseNoFPClassAttr())) { |
| 1661 | B.addNoFPClassAttr(NoFPClassMask: NoFPClass); |
| 1662 | return false; |
| 1663 | } |
| 1664 | |
| 1665 | return true; |
| 1666 | } |
| 1667 | case Attribute::Range: |
| 1668 | return parseRangeAttr(B); |
| 1669 | case Attribute::Initializes: |
| 1670 | return parseInitializesAttr(B); |
| 1671 | case Attribute::Captures: |
| 1672 | return parseCapturesAttr(B); |
| 1673 | default: |
| 1674 | B.addAttribute(Val: Attr); |
| 1675 | Lex.Lex(); |
| 1676 | return false; |
| 1677 | } |
| 1678 | } |
| 1679 | |
| 1680 | static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) { |
| 1681 | switch (Kind) { |
| 1682 | case lltok::kw_readnone: |
| 1683 | ME &= MemoryEffects::none(); |
| 1684 | return true; |
| 1685 | case lltok::kw_readonly: |
| 1686 | ME &= MemoryEffects::readOnly(); |
| 1687 | return true; |
| 1688 | case lltok::kw_writeonly: |
| 1689 | ME &= MemoryEffects::writeOnly(); |
| 1690 | return true; |
| 1691 | case lltok::kw_argmemonly: |
| 1692 | ME &= MemoryEffects::argMemOnly(); |
| 1693 | return true; |
| 1694 | case lltok::kw_inaccessiblememonly: |
| 1695 | ME &= MemoryEffects::inaccessibleMemOnly(); |
| 1696 | return true; |
| 1697 | case lltok::kw_inaccessiblemem_or_argmemonly: |
| 1698 | ME &= MemoryEffects::inaccessibleOrArgMemOnly(); |
| 1699 | return true; |
| 1700 | default: |
| 1701 | return false; |
| 1702 | } |
| 1703 | } |
| 1704 | |
| 1705 | /// parseFnAttributeValuePairs |
| 1706 | /// ::= <attr> | <attr> '=' <value> |
| 1707 | bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B, |
| 1708 | std::vector<unsigned> &FwdRefAttrGrps, |
| 1709 | bool InAttrGrp, LocTy &BuiltinLoc) { |
| 1710 | bool HaveError = false; |
| 1711 | |
| 1712 | B.clear(); |
| 1713 | |
| 1714 | MemoryEffects ME = MemoryEffects::unknown(); |
| 1715 | while (true) { |
| 1716 | lltok::Kind Token = Lex.getKind(); |
| 1717 | if (Token == lltok::rbrace) |
| 1718 | break; // Finished. |
| 1719 | |
| 1720 | if (Token == lltok::StringConstant) { |
| 1721 | if (parseStringAttribute(B)) |
| 1722 | return true; |
| 1723 | continue; |
| 1724 | } |
| 1725 | |
| 1726 | if (Token == lltok::AttrGrpID) { |
| 1727 | // Allow a function to reference an attribute group: |
| 1728 | // |
| 1729 | // define void @foo() #1 { ... } |
| 1730 | if (InAttrGrp) { |
| 1731 | HaveError |= error( |
| 1732 | L: Lex.getLoc(), |
| 1733 | Msg: "cannot have an attribute group reference in an attribute group" ); |
| 1734 | } else { |
| 1735 | // Save the reference to the attribute group. We'll fill it in later. |
| 1736 | FwdRefAttrGrps.push_back(x: Lex.getUIntVal()); |
| 1737 | } |
| 1738 | Lex.Lex(); |
| 1739 | continue; |
| 1740 | } |
| 1741 | |
| 1742 | SMLoc Loc = Lex.getLoc(); |
| 1743 | if (Token == lltok::kw_builtin) |
| 1744 | BuiltinLoc = Loc; |
| 1745 | |
| 1746 | if (upgradeMemoryAttr(ME, Kind: Token)) { |
| 1747 | Lex.Lex(); |
| 1748 | continue; |
| 1749 | } |
| 1750 | |
| 1751 | Attribute::AttrKind Attr = tokenToAttribute(Kind: Token); |
| 1752 | if (Attr == Attribute::None) { |
| 1753 | if (!InAttrGrp) |
| 1754 | break; |
| 1755 | return error(L: Lex.getLoc(), Msg: "unterminated attribute group" ); |
| 1756 | } |
| 1757 | |
| 1758 | if (parseEnumAttribute(Attr, B, InAttrGroup: InAttrGrp)) |
| 1759 | return true; |
| 1760 | |
| 1761 | // As a hack, we allow function alignment to be initially parsed as an |
| 1762 | // attribute on a function declaration/definition or added to an attribute |
| 1763 | // group and later moved to the alignment field. |
| 1764 | if (!Attribute::canUseAsFnAttr(Kind: Attr) && Attr != Attribute::Alignment) |
| 1765 | HaveError |= error(L: Loc, Msg: "this attribute does not apply to functions" ); |
| 1766 | } |
| 1767 | |
| 1768 | if (ME != MemoryEffects::unknown()) |
| 1769 | B.addMemoryAttr(ME); |
| 1770 | return HaveError; |
| 1771 | } |
| 1772 | |
| 1773 | //===----------------------------------------------------------------------===// |
| 1774 | // GlobalValue Reference/Resolution Routines. |
| 1775 | //===----------------------------------------------------------------------===// |
| 1776 | |
| 1777 | static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) { |
| 1778 | // The used global type does not matter. We will later RAUW it with a |
| 1779 | // global/function of the correct type. |
| 1780 | return new GlobalVariable(*M, Type::getInt8Ty(C&: M->getContext()), false, |
| 1781 | GlobalValue::ExternalWeakLinkage, nullptr, "" , |
| 1782 | nullptr, GlobalVariable::NotThreadLocal, |
| 1783 | PTy->getAddressSpace()); |
| 1784 | } |
| 1785 | |
| 1786 | Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty, |
| 1787 | Value *Val) { |
| 1788 | Type *ValTy = Val->getType(); |
| 1789 | if (ValTy == Ty) |
| 1790 | return Val; |
| 1791 | if (Ty->isLabelTy()) |
| 1792 | error(L: Loc, Msg: "'" + Name + "' is not a basic block" ); |
| 1793 | else |
| 1794 | error(L: Loc, Msg: "'" + Name + "' defined with type '" + |
| 1795 | getTypeString(T: Val->getType()) + "' but expected '" + |
| 1796 | getTypeString(T: Ty) + "'" ); |
| 1797 | return nullptr; |
| 1798 | } |
| 1799 | |
| 1800 | /// getGlobalVal - Get a value with the specified name or ID, creating a |
| 1801 | /// forward reference record if needed. This can return null if the value |
| 1802 | /// exists but does not have the right type. |
| 1803 | GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty, |
| 1804 | LocTy Loc) { |
| 1805 | PointerType *PTy = dyn_cast<PointerType>(Val: Ty); |
| 1806 | if (!PTy) { |
| 1807 | error(L: Loc, Msg: "global variable reference must have pointer type" ); |
| 1808 | return nullptr; |
| 1809 | } |
| 1810 | |
| 1811 | // Look this name up in the normal function symbol table. |
| 1812 | GlobalValue *Val = |
| 1813 | cast_or_null<GlobalValue>(Val: M->getValueSymbolTable().lookup(Name)); |
| 1814 | |
| 1815 | // If this is a forward reference for the value, see if we already created a |
| 1816 | // forward ref record. |
| 1817 | if (!Val) { |
| 1818 | auto I = ForwardRefVals.find(x: Name); |
| 1819 | if (I != ForwardRefVals.end()) |
| 1820 | Val = I->second.first; |
| 1821 | } |
| 1822 | |
| 1823 | // If we have the value in the symbol table or fwd-ref table, return it. |
| 1824 | if (Val) |
| 1825 | return cast_or_null<GlobalValue>( |
| 1826 | Val: checkValidVariableType(Loc, Name: "@" + Name, Ty, Val)); |
| 1827 | |
| 1828 | // Otherwise, create a new forward reference for this value and remember it. |
| 1829 | GlobalValue *FwdVal = createGlobalFwdRef(M, PTy); |
| 1830 | ForwardRefVals[Name] = std::make_pair(x&: FwdVal, y&: Loc); |
| 1831 | return FwdVal; |
| 1832 | } |
| 1833 | |
| 1834 | GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { |
| 1835 | PointerType *PTy = dyn_cast<PointerType>(Val: Ty); |
| 1836 | if (!PTy) { |
| 1837 | error(L: Loc, Msg: "global variable reference must have pointer type" ); |
| 1838 | return nullptr; |
| 1839 | } |
| 1840 | |
| 1841 | GlobalValue *Val = NumberedVals.get(ID); |
| 1842 | |
| 1843 | // If this is a forward reference for the value, see if we already created a |
| 1844 | // forward ref record. |
| 1845 | if (!Val) { |
| 1846 | auto I = ForwardRefValIDs.find(x: ID); |
| 1847 | if (I != ForwardRefValIDs.end()) |
| 1848 | Val = I->second.first; |
| 1849 | } |
| 1850 | |
| 1851 | // If we have the value in the symbol table or fwd-ref table, return it. |
| 1852 | if (Val) |
| 1853 | return cast_or_null<GlobalValue>( |
| 1854 | Val: checkValidVariableType(Loc, Name: "@" + Twine(ID), Ty, Val)); |
| 1855 | |
| 1856 | // Otherwise, create a new forward reference for this value and remember it. |
| 1857 | GlobalValue *FwdVal = createGlobalFwdRef(M, PTy); |
| 1858 | ForwardRefValIDs[ID] = std::make_pair(x&: FwdVal, y&: Loc); |
| 1859 | return FwdVal; |
| 1860 | } |
| 1861 | |
| 1862 | //===----------------------------------------------------------------------===// |
| 1863 | // Comdat Reference/Resolution Routines. |
| 1864 | //===----------------------------------------------------------------------===// |
| 1865 | |
| 1866 | Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) { |
| 1867 | // Look this name up in the comdat symbol table. |
| 1868 | Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); |
| 1869 | Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Key: Name); |
| 1870 | if (I != ComdatSymTab.end()) |
| 1871 | return &I->second; |
| 1872 | |
| 1873 | // Otherwise, create a new forward reference for this value and remember it. |
| 1874 | Comdat *C = M->getOrInsertComdat(Name); |
| 1875 | ForwardRefComdats[Name] = Loc; |
| 1876 | return C; |
| 1877 | } |
| 1878 | |
| 1879 | //===----------------------------------------------------------------------===// |
| 1880 | // Helper Routines. |
| 1881 | //===----------------------------------------------------------------------===// |
| 1882 | |
| 1883 | /// parseToken - If the current token has the specified kind, eat it and return |
| 1884 | /// success. Otherwise, emit the specified error and return failure. |
| 1885 | bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) { |
| 1886 | if (Lex.getKind() != T) |
| 1887 | return tokError(Msg: ErrMsg); |
| 1888 | Lex.Lex(); |
| 1889 | return false; |
| 1890 | } |
| 1891 | |
| 1892 | /// parseStringConstant |
| 1893 | /// ::= StringConstant |
| 1894 | bool LLParser::parseStringConstant(std::string &Result) { |
| 1895 | if (Lex.getKind() != lltok::StringConstant) |
| 1896 | return tokError(Msg: "expected string constant" ); |
| 1897 | Result = Lex.getStrVal(); |
| 1898 | Lex.Lex(); |
| 1899 | return false; |
| 1900 | } |
| 1901 | |
| 1902 | /// parseUInt32 |
| 1903 | /// ::= uint32 |
| 1904 | bool LLParser::parseUInt32(uint32_t &Val) { |
| 1905 | if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) |
| 1906 | return tokError(Msg: "expected integer" ); |
| 1907 | uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(Limit: 0xFFFFFFFFULL+1); |
| 1908 | if (Val64 != unsigned(Val64)) |
| 1909 | return tokError(Msg: "expected 32-bit integer (too large)" ); |
| 1910 | Val = Val64; |
| 1911 | Lex.Lex(); |
| 1912 | return false; |
| 1913 | } |
| 1914 | |
| 1915 | /// parseUInt64 |
| 1916 | /// ::= uint64 |
| 1917 | bool LLParser::parseUInt64(uint64_t &Val) { |
| 1918 | if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) |
| 1919 | return tokError(Msg: "expected integer" ); |
| 1920 | Val = Lex.getAPSIntVal().getLimitedValue(); |
| 1921 | Lex.Lex(); |
| 1922 | return false; |
| 1923 | } |
| 1924 | |
| 1925 | /// parseTLSModel |
| 1926 | /// := 'localdynamic' |
| 1927 | /// := 'initialexec' |
| 1928 | /// := 'localexec' |
| 1929 | bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { |
| 1930 | switch (Lex.getKind()) { |
| 1931 | default: |
| 1932 | return tokError(Msg: "expected localdynamic, initialexec or localexec" ); |
| 1933 | case lltok::kw_localdynamic: |
| 1934 | TLM = GlobalVariable::LocalDynamicTLSModel; |
| 1935 | break; |
| 1936 | case lltok::kw_initialexec: |
| 1937 | TLM = GlobalVariable::InitialExecTLSModel; |
| 1938 | break; |
| 1939 | case lltok::kw_localexec: |
| 1940 | TLM = GlobalVariable::LocalExecTLSModel; |
| 1941 | break; |
| 1942 | } |
| 1943 | |
| 1944 | Lex.Lex(); |
| 1945 | return false; |
| 1946 | } |
| 1947 | |
| 1948 | /// parseOptionalThreadLocal |
| 1949 | /// := /*empty*/ |
| 1950 | /// := 'thread_local' |
| 1951 | /// := 'thread_local' '(' tlsmodel ')' |
| 1952 | bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { |
| 1953 | TLM = GlobalVariable::NotThreadLocal; |
| 1954 | if (!EatIfPresent(T: lltok::kw_thread_local)) |
| 1955 | return false; |
| 1956 | |
| 1957 | TLM = GlobalVariable::GeneralDynamicTLSModel; |
| 1958 | if (Lex.getKind() == lltok::lparen) { |
| 1959 | Lex.Lex(); |
| 1960 | return parseTLSModel(TLM) || |
| 1961 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' after thread local model" ); |
| 1962 | } |
| 1963 | return false; |
| 1964 | } |
| 1965 | |
| 1966 | /// parseOptionalAddrSpace |
| 1967 | /// := /*empty*/ |
| 1968 | /// := 'addrspace' '(' uint32 ')' |
| 1969 | bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) { |
| 1970 | AddrSpace = DefaultAS; |
| 1971 | if (!EatIfPresent(T: lltok::kw_addrspace)) |
| 1972 | return false; |
| 1973 | |
| 1974 | auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool { |
| 1975 | if (Lex.getKind() == lltok::StringConstant) { |
| 1976 | const std::string &AddrSpaceStr = Lex.getStrVal(); |
| 1977 | if (AddrSpaceStr == "A" ) { |
| 1978 | AddrSpace = M->getDataLayout().getAllocaAddrSpace(); |
| 1979 | } else if (AddrSpaceStr == "G" ) { |
| 1980 | AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace(); |
| 1981 | } else if (AddrSpaceStr == "P" ) { |
| 1982 | AddrSpace = M->getDataLayout().getProgramAddressSpace(); |
| 1983 | } else if (std::optional<unsigned> AS = |
| 1984 | M->getDataLayout().getNamedAddressSpace(Name: AddrSpaceStr)) { |
| 1985 | AddrSpace = *AS; |
| 1986 | } else { |
| 1987 | return tokError(Msg: "invalid symbolic addrspace '" + AddrSpaceStr + "'" ); |
| 1988 | } |
| 1989 | Lex.Lex(); |
| 1990 | return false; |
| 1991 | } |
| 1992 | if (Lex.getKind() != lltok::APSInt) |
| 1993 | return tokError(Msg: "expected integer or string constant" ); |
| 1994 | SMLoc Loc = Lex.getLoc(); |
| 1995 | if (parseUInt32(Val&: AddrSpace)) |
| 1996 | return true; |
| 1997 | if (!isUInt<24>(x: AddrSpace)) |
| 1998 | return error(L: Loc, Msg: "invalid address space, must be a 24-bit integer" ); |
| 1999 | return false; |
| 2000 | }; |
| 2001 | |
| 2002 | return parseToken(T: lltok::lparen, ErrMsg: "expected '(' in address space" ) || |
| 2003 | ParseAddrspaceValue(AddrSpace) || |
| 2004 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' in address space" ); |
| 2005 | } |
| 2006 | |
| 2007 | /// parseStringAttribute |
| 2008 | /// := StringConstant |
| 2009 | /// := StringConstant '=' StringConstant |
| 2010 | bool LLParser::parseStringAttribute(AttrBuilder &B) { |
| 2011 | std::string Attr = Lex.getStrVal(); |
| 2012 | Lex.Lex(); |
| 2013 | std::string Val; |
| 2014 | if (EatIfPresent(T: lltok::equal) && parseStringConstant(Result&: Val)) |
| 2015 | return true; |
| 2016 | B.addAttribute(A: Attr, V: Val); |
| 2017 | return false; |
| 2018 | } |
| 2019 | |
| 2020 | /// Parse a potentially empty list of parameter or return attributes. |
| 2021 | bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) { |
| 2022 | bool HaveError = false; |
| 2023 | |
| 2024 | B.clear(); |
| 2025 | |
| 2026 | while (true) { |
| 2027 | lltok::Kind Token = Lex.getKind(); |
| 2028 | if (Token == lltok::StringConstant) { |
| 2029 | if (parseStringAttribute(B)) |
| 2030 | return true; |
| 2031 | continue; |
| 2032 | } |
| 2033 | |
| 2034 | if (Token == lltok::kw_nocapture) { |
| 2035 | Lex.Lex(); |
| 2036 | B.addCapturesAttr(CI: CaptureInfo::none()); |
| 2037 | continue; |
| 2038 | } |
| 2039 | |
| 2040 | SMLoc Loc = Lex.getLoc(); |
| 2041 | Attribute::AttrKind Attr = tokenToAttribute(Kind: Token); |
| 2042 | if (Attr == Attribute::None) |
| 2043 | return HaveError; |
| 2044 | |
| 2045 | if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false)) |
| 2046 | return true; |
| 2047 | |
| 2048 | if (IsParam && !Attribute::canUseAsParamAttr(Kind: Attr)) |
| 2049 | HaveError |= error(L: Loc, Msg: "this attribute does not apply to parameters" ); |
| 2050 | if (!IsParam && !Attribute::canUseAsRetAttr(Kind: Attr)) |
| 2051 | HaveError |= error(L: Loc, Msg: "this attribute does not apply to return values" ); |
| 2052 | } |
| 2053 | } |
| 2054 | |
| 2055 | static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) { |
| 2056 | HasLinkage = true; |
| 2057 | switch (Kind) { |
| 2058 | default: |
| 2059 | HasLinkage = false; |
| 2060 | return GlobalValue::ExternalLinkage; |
| 2061 | case lltok::kw_private: |
| 2062 | return GlobalValue::PrivateLinkage; |
| 2063 | case lltok::kw_internal: |
| 2064 | return GlobalValue::InternalLinkage; |
| 2065 | case lltok::kw_weak: |
| 2066 | return GlobalValue::WeakAnyLinkage; |
| 2067 | case lltok::kw_weak_odr: |
| 2068 | return GlobalValue::WeakODRLinkage; |
| 2069 | case lltok::kw_linkonce: |
| 2070 | return GlobalValue::LinkOnceAnyLinkage; |
| 2071 | case lltok::kw_linkonce_odr: |
| 2072 | return GlobalValue::LinkOnceODRLinkage; |
| 2073 | case lltok::kw_available_externally: |
| 2074 | return GlobalValue::AvailableExternallyLinkage; |
| 2075 | case lltok::kw_appending: |
| 2076 | return GlobalValue::AppendingLinkage; |
| 2077 | case lltok::kw_common: |
| 2078 | return GlobalValue::CommonLinkage; |
| 2079 | case lltok::kw_extern_weak: |
| 2080 | return GlobalValue::ExternalWeakLinkage; |
| 2081 | case lltok::kw_external: |
| 2082 | return GlobalValue::ExternalLinkage; |
| 2083 | } |
| 2084 | } |
| 2085 | |
| 2086 | /// parseOptionalLinkage |
| 2087 | /// ::= /*empty*/ |
| 2088 | /// ::= 'private' |
| 2089 | /// ::= 'internal' |
| 2090 | /// ::= 'weak' |
| 2091 | /// ::= 'weak_odr' |
| 2092 | /// ::= 'linkonce' |
| 2093 | /// ::= 'linkonce_odr' |
| 2094 | /// ::= 'available_externally' |
| 2095 | /// ::= 'appending' |
| 2096 | /// ::= 'common' |
| 2097 | /// ::= 'extern_weak' |
| 2098 | /// ::= 'external' |
| 2099 | bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage, |
| 2100 | unsigned &Visibility, |
| 2101 | unsigned &DLLStorageClass, bool &DSOLocal) { |
| 2102 | Res = parseOptionalLinkageAux(Kind: Lex.getKind(), HasLinkage); |
| 2103 | if (HasLinkage) |
| 2104 | Lex.Lex(); |
| 2105 | parseOptionalDSOLocal(DSOLocal); |
| 2106 | parseOptionalVisibility(Res&: Visibility); |
| 2107 | parseOptionalDLLStorageClass(Res&: DLLStorageClass); |
| 2108 | |
| 2109 | if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) { |
| 2110 | return error(L: Lex.getLoc(), Msg: "dso_location and DLL-StorageClass mismatch" ); |
| 2111 | } |
| 2112 | |
| 2113 | return false; |
| 2114 | } |
| 2115 | |
| 2116 | void LLParser::parseOptionalDSOLocal(bool &DSOLocal) { |
| 2117 | switch (Lex.getKind()) { |
| 2118 | default: |
| 2119 | DSOLocal = false; |
| 2120 | break; |
| 2121 | case lltok::kw_dso_local: |
| 2122 | DSOLocal = true; |
| 2123 | Lex.Lex(); |
| 2124 | break; |
| 2125 | case lltok::kw_dso_preemptable: |
| 2126 | DSOLocal = false; |
| 2127 | Lex.Lex(); |
| 2128 | break; |
| 2129 | } |
| 2130 | } |
| 2131 | |
| 2132 | /// parseOptionalVisibility |
| 2133 | /// ::= /*empty*/ |
| 2134 | /// ::= 'default' |
| 2135 | /// ::= 'hidden' |
| 2136 | /// ::= 'protected' |
| 2137 | /// |
| 2138 | void LLParser::parseOptionalVisibility(unsigned &Res) { |
| 2139 | switch (Lex.getKind()) { |
| 2140 | default: |
| 2141 | Res = GlobalValue::DefaultVisibility; |
| 2142 | return; |
| 2143 | case lltok::kw_default: |
| 2144 | Res = GlobalValue::DefaultVisibility; |
| 2145 | break; |
| 2146 | case lltok::kw_hidden: |
| 2147 | Res = GlobalValue::HiddenVisibility; |
| 2148 | break; |
| 2149 | case lltok::kw_protected: |
| 2150 | Res = GlobalValue::ProtectedVisibility; |
| 2151 | break; |
| 2152 | } |
| 2153 | Lex.Lex(); |
| 2154 | } |
| 2155 | |
| 2156 | bool LLParser::parseOptionalImportType(lltok::Kind Kind, |
| 2157 | GlobalValueSummary::ImportKind &Res) { |
| 2158 | switch (Kind) { |
| 2159 | default: |
| 2160 | return tokError(Msg: "unknown import kind. Expect definition or declaration." ); |
| 2161 | case lltok::kw_definition: |
| 2162 | Res = GlobalValueSummary::Definition; |
| 2163 | return false; |
| 2164 | case lltok::kw_declaration: |
| 2165 | Res = GlobalValueSummary::Declaration; |
| 2166 | return false; |
| 2167 | } |
| 2168 | } |
| 2169 | |
| 2170 | /// parseOptionalDLLStorageClass |
| 2171 | /// ::= /*empty*/ |
| 2172 | /// ::= 'dllimport' |
| 2173 | /// ::= 'dllexport' |
| 2174 | /// |
| 2175 | void LLParser::parseOptionalDLLStorageClass(unsigned &Res) { |
| 2176 | switch (Lex.getKind()) { |
| 2177 | default: |
| 2178 | Res = GlobalValue::DefaultStorageClass; |
| 2179 | return; |
| 2180 | case lltok::kw_dllimport: |
| 2181 | Res = GlobalValue::DLLImportStorageClass; |
| 2182 | break; |
| 2183 | case lltok::kw_dllexport: |
| 2184 | Res = GlobalValue::DLLExportStorageClass; |
| 2185 | break; |
| 2186 | } |
| 2187 | Lex.Lex(); |
| 2188 | } |
| 2189 | |
| 2190 | /// parseOptionalCallingConv |
| 2191 | /// ::= /*empty*/ |
| 2192 | /// ::= 'ccc' |
| 2193 | /// ::= 'fastcc' |
| 2194 | /// ::= 'intel_ocl_bicc' |
| 2195 | /// ::= 'coldcc' |
| 2196 | /// ::= 'cfguard_checkcc' |
| 2197 | /// ::= 'x86_stdcallcc' |
| 2198 | /// ::= 'x86_fastcallcc' |
| 2199 | /// ::= 'x86_thiscallcc' |
| 2200 | /// ::= 'x86_vectorcallcc' |
| 2201 | /// ::= 'arm_apcscc' |
| 2202 | /// ::= 'arm_aapcscc' |
| 2203 | /// ::= 'arm_aapcs_vfpcc' |
| 2204 | /// ::= 'aarch64_vector_pcs' |
| 2205 | /// ::= 'aarch64_sve_vector_pcs' |
| 2206 | /// ::= 'aarch64_sme_preservemost_from_x0' |
| 2207 | /// ::= 'aarch64_sme_preservemost_from_x1' |
| 2208 | /// ::= 'aarch64_sme_preservemost_from_x2' |
| 2209 | /// ::= 'msp430_intrcc' |
| 2210 | /// ::= 'avr_intrcc' |
| 2211 | /// ::= 'avr_signalcc' |
| 2212 | /// ::= 'ptx_kernel' |
| 2213 | /// ::= 'ptx_device' |
| 2214 | /// ::= 'spir_func' |
| 2215 | /// ::= 'spir_kernel' |
| 2216 | /// ::= 'x86_64_sysvcc' |
| 2217 | /// ::= 'win64cc' |
| 2218 | /// ::= 'anyregcc' |
| 2219 | /// ::= 'preserve_mostcc' |
| 2220 | /// ::= 'preserve_allcc' |
| 2221 | /// ::= 'preserve_nonecc' |
| 2222 | /// ::= 'ghccc' |
| 2223 | /// ::= 'swiftcc' |
| 2224 | /// ::= 'swifttailcc' |
| 2225 | /// ::= 'x86_intrcc' |
| 2226 | /// ::= 'hhvmcc' |
| 2227 | /// ::= 'hhvm_ccc' |
| 2228 | /// ::= 'cxx_fast_tlscc' |
| 2229 | /// ::= 'amdgpu_vs' |
| 2230 | /// ::= 'amdgpu_ls' |
| 2231 | /// ::= 'amdgpu_hs' |
| 2232 | /// ::= 'amdgpu_es' |
| 2233 | /// ::= 'amdgpu_gs' |
| 2234 | /// ::= 'amdgpu_ps' |
| 2235 | /// ::= 'amdgpu_cs' |
| 2236 | /// ::= 'amdgpu_cs_chain' |
| 2237 | /// ::= 'amdgpu_cs_chain_preserve' |
| 2238 | /// ::= 'amdgpu_kernel' |
| 2239 | /// ::= 'tailcc' |
| 2240 | /// ::= 'm68k_rtdcc' |
| 2241 | /// ::= 'graalcc' |
| 2242 | /// ::= 'riscv_vector_cc' |
| 2243 | /// ::= 'riscv_vls_cc' |
| 2244 | /// ::= 'cc' UINT |
| 2245 | /// |
| 2246 | bool LLParser::parseOptionalCallingConv(unsigned &CC) { |
| 2247 | switch (Lex.getKind()) { |
| 2248 | default: CC = CallingConv::C; return false; |
| 2249 | case lltok::kw_ccc: CC = CallingConv::C; break; |
| 2250 | case lltok::kw_fastcc: CC = CallingConv::Fast; break; |
| 2251 | case lltok::kw_coldcc: CC = CallingConv::Cold; break; |
| 2252 | case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break; |
| 2253 | case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; |
| 2254 | case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; |
| 2255 | case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break; |
| 2256 | case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; |
| 2257 | case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break; |
| 2258 | case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; |
| 2259 | case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; |
| 2260 | case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; |
| 2261 | case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break; |
| 2262 | case lltok::kw_aarch64_sve_vector_pcs: |
| 2263 | CC = CallingConv::AArch64_SVE_VectorCall; |
| 2264 | break; |
| 2265 | case lltok::kw_aarch64_sme_preservemost_from_x0: |
| 2266 | CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0; |
| 2267 | break; |
| 2268 | case lltok::kw_aarch64_sme_preservemost_from_x1: |
| 2269 | CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1; |
| 2270 | break; |
| 2271 | case lltok::kw_aarch64_sme_preservemost_from_x2: |
| 2272 | CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2; |
| 2273 | break; |
| 2274 | case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; |
| 2275 | case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break; |
| 2276 | case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break; |
| 2277 | case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; |
| 2278 | case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; |
| 2279 | case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; |
| 2280 | case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; |
| 2281 | case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; |
| 2282 | case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break; |
| 2283 | case lltok::kw_win64cc: CC = CallingConv::Win64; break; |
| 2284 | case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break; |
| 2285 | case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break; |
| 2286 | case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break; |
| 2287 | case lltok::kw_preserve_nonecc:CC = CallingConv::PreserveNone; break; |
| 2288 | case lltok::kw_ghccc: CC = CallingConv::GHC; break; |
| 2289 | case lltok::kw_swiftcc: CC = CallingConv::Swift; break; |
| 2290 | case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break; |
| 2291 | case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break; |
| 2292 | case lltok::kw_hhvmcc: |
| 2293 | CC = CallingConv::DUMMY_HHVM; |
| 2294 | break; |
| 2295 | case lltok::kw_hhvm_ccc: |
| 2296 | CC = CallingConv::DUMMY_HHVM_C; |
| 2297 | break; |
| 2298 | case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break; |
| 2299 | case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break; |
| 2300 | case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break; |
| 2301 | case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break; |
| 2302 | case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break; |
| 2303 | case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break; |
| 2304 | case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break; |
| 2305 | case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break; |
| 2306 | case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break; |
| 2307 | case lltok::kw_amdgpu_cs_chain: |
| 2308 | CC = CallingConv::AMDGPU_CS_Chain; |
| 2309 | break; |
| 2310 | case lltok::kw_amdgpu_cs_chain_preserve: |
| 2311 | CC = CallingConv::AMDGPU_CS_ChainPreserve; |
| 2312 | break; |
| 2313 | case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break; |
| 2314 | case lltok::kw_amdgpu_gfx_whole_wave: |
| 2315 | CC = CallingConv::AMDGPU_Gfx_WholeWave; |
| 2316 | break; |
| 2317 | case lltok::kw_tailcc: CC = CallingConv::Tail; break; |
| 2318 | case lltok::kw_m68k_rtdcc: CC = CallingConv::M68k_RTD; break; |
| 2319 | case lltok::kw_graalcc: CC = CallingConv::GRAAL; break; |
| 2320 | case lltok::kw_riscv_vector_cc: |
| 2321 | CC = CallingConv::RISCV_VectorCall; |
| 2322 | break; |
| 2323 | case lltok::kw_riscv_vls_cc: |
| 2324 | // Default ABI_VLEN |
| 2325 | CC = CallingConv::RISCV_VLSCall_128; |
| 2326 | Lex.Lex(); |
| 2327 | if (!EatIfPresent(T: lltok::lparen)) |
| 2328 | break; |
| 2329 | uint32_t ABIVlen; |
| 2330 | if (parseUInt32(Val&: ABIVlen) || !EatIfPresent(T: lltok::rparen)) |
| 2331 | return true; |
| 2332 | switch (ABIVlen) { |
| 2333 | default: |
| 2334 | return tokError(Msg: "unknown RISC-V ABI VLEN" ); |
| 2335 | #define CC_VLS_CASE(ABIVlen) \ |
| 2336 | case ABIVlen: \ |
| 2337 | CC = CallingConv::RISCV_VLSCall_##ABIVlen; \ |
| 2338 | break; |
| 2339 | CC_VLS_CASE(32) |
| 2340 | CC_VLS_CASE(64) |
| 2341 | CC_VLS_CASE(128) |
| 2342 | CC_VLS_CASE(256) |
| 2343 | CC_VLS_CASE(512) |
| 2344 | CC_VLS_CASE(1024) |
| 2345 | CC_VLS_CASE(2048) |
| 2346 | CC_VLS_CASE(4096) |
| 2347 | CC_VLS_CASE(8192) |
| 2348 | CC_VLS_CASE(16384) |
| 2349 | CC_VLS_CASE(32768) |
| 2350 | CC_VLS_CASE(65536) |
| 2351 | #undef CC_VLS_CASE |
| 2352 | } |
| 2353 | return false; |
| 2354 | case lltok::kw_cheriot_compartmentcallcc: |
| 2355 | CC = CallingConv::CHERIoT_CompartmentCall; |
| 2356 | break; |
| 2357 | case lltok::kw_cheriot_compartmentcalleecc: |
| 2358 | CC = CallingConv::CHERIoT_CompartmentCallee; |
| 2359 | break; |
| 2360 | case lltok::kw_cheriot_librarycallcc: |
| 2361 | CC = CallingConv::CHERIoT_LibraryCall; |
| 2362 | break; |
| 2363 | case lltok::kw_cc: { |
| 2364 | Lex.Lex(); |
| 2365 | return parseUInt32(Val&: CC); |
| 2366 | } |
| 2367 | } |
| 2368 | |
| 2369 | Lex.Lex(); |
| 2370 | return false; |
| 2371 | } |
| 2372 | |
| 2373 | /// parseMetadataAttachment |
| 2374 | /// ::= !dbg !42 |
| 2375 | bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) { |
| 2376 | assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment" ); |
| 2377 | |
| 2378 | std::string Name = Lex.getStrVal(); |
| 2379 | Kind = M->getMDKindID(Name); |
| 2380 | Lex.Lex(); |
| 2381 | |
| 2382 | return parseMDNode(N&: MD); |
| 2383 | } |
| 2384 | |
| 2385 | /// parseInstructionMetadata |
| 2386 | /// ::= !dbg !42 (',' !dbg !57)* |
| 2387 | bool LLParser::parseInstructionMetadata(Instruction &Inst) { |
| 2388 | do { |
| 2389 | if (Lex.getKind() != lltok::MetadataVar) |
| 2390 | return tokError(Msg: "expected metadata after comma" ); |
| 2391 | |
| 2392 | unsigned MDK; |
| 2393 | MDNode *N; |
| 2394 | if (parseMetadataAttachment(Kind&: MDK, MD&: N)) |
| 2395 | return true; |
| 2396 | |
| 2397 | if (MDK == LLVMContext::MD_DIAssignID) |
| 2398 | TempDIAssignIDAttachments[N].push_back(Elt: &Inst); |
| 2399 | else |
| 2400 | Inst.setMetadata(KindID: MDK, Node: N); |
| 2401 | |
| 2402 | if (MDK == LLVMContext::MD_tbaa) |
| 2403 | InstsWithTBAATag.push_back(Elt: &Inst); |
| 2404 | |
| 2405 | // If this is the end of the list, we're done. |
| 2406 | } while (EatIfPresent(T: lltok::comma)); |
| 2407 | return false; |
| 2408 | } |
| 2409 | |
| 2410 | /// parseGlobalObjectMetadataAttachment |
| 2411 | /// ::= !dbg !57 |
| 2412 | bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) { |
| 2413 | unsigned MDK; |
| 2414 | MDNode *N; |
| 2415 | if (parseMetadataAttachment(Kind&: MDK, MD&: N)) |
| 2416 | return true; |
| 2417 | |
| 2418 | GO.addMetadata(KindID: MDK, MD&: *N); |
| 2419 | return false; |
| 2420 | } |
| 2421 | |
| 2422 | /// parseOptionalFunctionMetadata |
| 2423 | /// ::= (!dbg !57)* |
| 2424 | bool LLParser::parseOptionalFunctionMetadata(Function &F) { |
| 2425 | while (Lex.getKind() == lltok::MetadataVar) |
| 2426 | if (parseGlobalObjectMetadataAttachment(GO&: F)) |
| 2427 | return true; |
| 2428 | return false; |
| 2429 | } |
| 2430 | |
| 2431 | /// parseOptionalAlignment |
| 2432 | /// ::= /* empty */ |
| 2433 | /// ::= 'align' 4 |
| 2434 | bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) { |
| 2435 | Alignment = std::nullopt; |
| 2436 | if (!EatIfPresent(T: lltok::kw_align)) |
| 2437 | return false; |
| 2438 | LocTy AlignLoc = Lex.getLoc(); |
| 2439 | uint64_t Value = 0; |
| 2440 | |
| 2441 | LocTy ParenLoc = Lex.getLoc(); |
| 2442 | bool HaveParens = false; |
| 2443 | if (AllowParens) { |
| 2444 | if (EatIfPresent(T: lltok::lparen)) |
| 2445 | HaveParens = true; |
| 2446 | } |
| 2447 | |
| 2448 | if (parseUInt64(Val&: Value)) |
| 2449 | return true; |
| 2450 | |
| 2451 | if (HaveParens && !EatIfPresent(T: lltok::rparen)) |
| 2452 | return error(L: ParenLoc, Msg: "expected ')'" ); |
| 2453 | |
| 2454 | if (!isPowerOf2_64(Value)) |
| 2455 | return error(L: AlignLoc, Msg: "alignment is not a power of two" ); |
| 2456 | if (Value > Value::MaximumAlignment) |
| 2457 | return error(L: AlignLoc, Msg: "huge alignments are not supported yet" ); |
| 2458 | Alignment = Align(Value); |
| 2459 | return false; |
| 2460 | } |
| 2461 | |
| 2462 | /// parseOptionalCodeModel |
| 2463 | /// ::= /* empty */ |
| 2464 | /// ::= 'code_model' "large" |
| 2465 | bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) { |
| 2466 | Lex.Lex(); |
| 2467 | auto StrVal = Lex.getStrVal(); |
| 2468 | auto ErrMsg = "expected global code model string" ; |
| 2469 | if (StrVal == "tiny" ) |
| 2470 | model = CodeModel::Tiny; |
| 2471 | else if (StrVal == "small" ) |
| 2472 | model = CodeModel::Small; |
| 2473 | else if (StrVal == "kernel" ) |
| 2474 | model = CodeModel::Kernel; |
| 2475 | else if (StrVal == "medium" ) |
| 2476 | model = CodeModel::Medium; |
| 2477 | else if (StrVal == "large" ) |
| 2478 | model = CodeModel::Large; |
| 2479 | else |
| 2480 | return tokError(Msg: ErrMsg); |
| 2481 | if (parseToken(T: lltok::StringConstant, ErrMsg)) |
| 2482 | return true; |
| 2483 | return false; |
| 2484 | } |
| 2485 | |
| 2486 | /// parseOptionalAttrBytes |
| 2487 | /// ::= /* empty */ |
| 2488 | /// ::= AttrKind '(' 4 ')' |
| 2489 | /// |
| 2490 | /// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or |
| 2491 | /// 'dead_on_return' |
| 2492 | bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind, |
| 2493 | std::optional<uint64_t> &Bytes, |
| 2494 | bool ErrorNoBytes) { |
| 2495 | assert((AttrKind == lltok::kw_dereferenceable || |
| 2496 | AttrKind == lltok::kw_dereferenceable_or_null || |
| 2497 | AttrKind == lltok::kw_dead_on_return) && |
| 2498 | "contract!" ); |
| 2499 | |
| 2500 | Bytes = 0; |
| 2501 | if (!EatIfPresent(T: AttrKind)) |
| 2502 | return false; |
| 2503 | LocTy ParenLoc = Lex.getLoc(); |
| 2504 | if (!EatIfPresent(T: lltok::lparen)) { |
| 2505 | if (ErrorNoBytes) |
| 2506 | return error(L: ParenLoc, Msg: "expected '('" ); |
| 2507 | Bytes = std::nullopt; |
| 2508 | return false; |
| 2509 | } |
| 2510 | LocTy DerefLoc = Lex.getLoc(); |
| 2511 | if (parseUInt64(Val&: Bytes.value())) |
| 2512 | return true; |
| 2513 | ParenLoc = Lex.getLoc(); |
| 2514 | if (!EatIfPresent(T: lltok::rparen)) |
| 2515 | return error(L: ParenLoc, Msg: "expected ')'" ); |
| 2516 | if (!Bytes.value()) |
| 2517 | return error(L: DerefLoc, Msg: "byte count specified must be non-zero" ); |
| 2518 | return false; |
| 2519 | } |
| 2520 | |
| 2521 | bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) { |
| 2522 | Lex.Lex(); |
| 2523 | Kind = UWTableKind::Default; |
| 2524 | if (!EatIfPresent(T: lltok::lparen)) |
| 2525 | return false; |
| 2526 | LocTy KindLoc = Lex.getLoc(); |
| 2527 | if (Lex.getKind() == lltok::kw_sync) |
| 2528 | Kind = UWTableKind::Sync; |
| 2529 | else if (Lex.getKind() == lltok::kw_async) |
| 2530 | Kind = UWTableKind::Async; |
| 2531 | else |
| 2532 | return error(L: KindLoc, Msg: "expected unwind table kind" ); |
| 2533 | Lex.Lex(); |
| 2534 | return parseToken(T: lltok::rparen, ErrMsg: "expected ')'" ); |
| 2535 | } |
| 2536 | |
| 2537 | bool LLParser::parseAllocKind(AllocFnKind &Kind) { |
| 2538 | Lex.Lex(); |
| 2539 | LocTy ParenLoc = Lex.getLoc(); |
| 2540 | if (!EatIfPresent(T: lltok::lparen)) |
| 2541 | return error(L: ParenLoc, Msg: "expected '('" ); |
| 2542 | LocTy KindLoc = Lex.getLoc(); |
| 2543 | std::string Arg; |
| 2544 | if (parseStringConstant(Result&: Arg)) |
| 2545 | return error(L: KindLoc, Msg: "expected allockind value" ); |
| 2546 | for (StringRef A : llvm::split(Str: Arg, Separator: "," )) { |
| 2547 | if (A == "alloc" ) { |
| 2548 | Kind |= AllocFnKind::Alloc; |
| 2549 | } else if (A == "realloc" ) { |
| 2550 | Kind |= AllocFnKind::Realloc; |
| 2551 | } else if (A == "free" ) { |
| 2552 | Kind |= AllocFnKind::Free; |
| 2553 | } else if (A == "uninitialized" ) { |
| 2554 | Kind |= AllocFnKind::Uninitialized; |
| 2555 | } else if (A == "zeroed" ) { |
| 2556 | Kind |= AllocFnKind::Zeroed; |
| 2557 | } else if (A == "aligned" ) { |
| 2558 | Kind |= AllocFnKind::Aligned; |
| 2559 | } else { |
| 2560 | return error(L: KindLoc, Msg: Twine("unknown allockind " ) + A); |
| 2561 | } |
| 2562 | } |
| 2563 | ParenLoc = Lex.getLoc(); |
| 2564 | if (!EatIfPresent(T: lltok::rparen)) |
| 2565 | return error(L: ParenLoc, Msg: "expected ')'" ); |
| 2566 | if (Kind == AllocFnKind::Unknown) |
| 2567 | return error(L: KindLoc, Msg: "expected allockind value" ); |
| 2568 | return false; |
| 2569 | } |
| 2570 | |
| 2571 | static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) { |
| 2572 | switch (Tok) { |
| 2573 | case lltok::kw_argmem: |
| 2574 | return IRMemLocation::ArgMem; |
| 2575 | case lltok::kw_inaccessiblemem: |
| 2576 | return IRMemLocation::InaccessibleMem; |
| 2577 | case lltok::kw_errnomem: |
| 2578 | return IRMemLocation::ErrnoMem; |
| 2579 | case lltok::kw_target_mem0: |
| 2580 | return IRMemLocation::TargetMem0; |
| 2581 | case lltok::kw_target_mem1: |
| 2582 | return IRMemLocation::TargetMem1; |
| 2583 | default: |
| 2584 | return std::nullopt; |
| 2585 | } |
| 2586 | } |
| 2587 | |
| 2588 | static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) { |
| 2589 | switch (Tok) { |
| 2590 | case lltok::kw_none: |
| 2591 | return ModRefInfo::NoModRef; |
| 2592 | case lltok::kw_read: |
| 2593 | return ModRefInfo::Ref; |
| 2594 | case lltok::kw_write: |
| 2595 | return ModRefInfo::Mod; |
| 2596 | case lltok::kw_readwrite: |
| 2597 | return ModRefInfo::ModRef; |
| 2598 | default: |
| 2599 | return std::nullopt; |
| 2600 | } |
| 2601 | } |
| 2602 | |
| 2603 | std::optional<MemoryEffects> LLParser::parseMemoryAttr() { |
| 2604 | MemoryEffects ME = MemoryEffects::none(); |
| 2605 | |
| 2606 | // We use syntax like memory(argmem: read), so the colon should not be |
| 2607 | // interpreted as a label terminator. |
| 2608 | Lex.setIgnoreColonInIdentifiers(true); |
| 2609 | llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); }); |
| 2610 | |
| 2611 | Lex.Lex(); |
| 2612 | if (!EatIfPresent(T: lltok::lparen)) { |
| 2613 | tokError(Msg: "expected '('" ); |
| 2614 | return std::nullopt; |
| 2615 | } |
| 2616 | |
| 2617 | bool SeenLoc = false; |
| 2618 | do { |
| 2619 | std::optional<IRMemLocation> Loc = keywordToLoc(Tok: Lex.getKind()); |
| 2620 | if (Loc) { |
| 2621 | Lex.Lex(); |
| 2622 | if (!EatIfPresent(T: lltok::colon)) { |
| 2623 | tokError(Msg: "expected ':' after location" ); |
| 2624 | return std::nullopt; |
| 2625 | } |
| 2626 | } |
| 2627 | |
| 2628 | std::optional<ModRefInfo> MR = keywordToModRef(Tok: Lex.getKind()); |
| 2629 | if (!MR) { |
| 2630 | if (!Loc) |
| 2631 | tokError(Msg: "expected memory location (argmem, inaccessiblemem, errnomem) " |
| 2632 | "or access kind (none, read, write, readwrite)" ); |
| 2633 | else |
| 2634 | tokError(Msg: "expected access kind (none, read, write, readwrite)" ); |
| 2635 | return std::nullopt; |
| 2636 | } |
| 2637 | |
| 2638 | Lex.Lex(); |
| 2639 | if (Loc) { |
| 2640 | SeenLoc = true; |
| 2641 | ME = ME.getWithModRef(Loc: *Loc, MR: *MR); |
| 2642 | } else { |
| 2643 | if (SeenLoc) { |
| 2644 | tokError(Msg: "default access kind must be specified first" ); |
| 2645 | return std::nullopt; |
| 2646 | } |
| 2647 | ME = MemoryEffects(*MR); |
| 2648 | } |
| 2649 | |
| 2650 | if (EatIfPresent(T: lltok::rparen)) |
| 2651 | return ME; |
| 2652 | } while (EatIfPresent(T: lltok::comma)); |
| 2653 | |
| 2654 | tokError(Msg: "unterminated memory attribute" ); |
| 2655 | return std::nullopt; |
| 2656 | } |
| 2657 | |
| 2658 | static unsigned keywordToFPClassTest(lltok::Kind Tok) { |
| 2659 | switch (Tok) { |
| 2660 | case lltok::kw_all: |
| 2661 | return fcAllFlags; |
| 2662 | case lltok::kw_nan: |
| 2663 | return fcNan; |
| 2664 | case lltok::kw_snan: |
| 2665 | return fcSNan; |
| 2666 | case lltok::kw_qnan: |
| 2667 | return fcQNan; |
| 2668 | case lltok::kw_inf: |
| 2669 | return fcInf; |
| 2670 | case lltok::kw_ninf: |
| 2671 | return fcNegInf; |
| 2672 | case lltok::kw_pinf: |
| 2673 | return fcPosInf; |
| 2674 | case lltok::kw_norm: |
| 2675 | return fcNormal; |
| 2676 | case lltok::kw_nnorm: |
| 2677 | return fcNegNormal; |
| 2678 | case lltok::kw_pnorm: |
| 2679 | return fcPosNormal; |
| 2680 | case lltok::kw_sub: |
| 2681 | return fcSubnormal; |
| 2682 | case lltok::kw_nsub: |
| 2683 | return fcNegSubnormal; |
| 2684 | case lltok::kw_psub: |
| 2685 | return fcPosSubnormal; |
| 2686 | case lltok::kw_zero: |
| 2687 | return fcZero; |
| 2688 | case lltok::kw_nzero: |
| 2689 | return fcNegZero; |
| 2690 | case lltok::kw_pzero: |
| 2691 | return fcPosZero; |
| 2692 | default: |
| 2693 | return 0; |
| 2694 | } |
| 2695 | } |
| 2696 | |
| 2697 | unsigned LLParser::parseNoFPClassAttr() { |
| 2698 | unsigned Mask = fcNone; |
| 2699 | |
| 2700 | Lex.Lex(); |
| 2701 | if (!EatIfPresent(T: lltok::lparen)) { |
| 2702 | tokError(Msg: "expected '('" ); |
| 2703 | return 0; |
| 2704 | } |
| 2705 | |
| 2706 | do { |
| 2707 | uint64_t Value = 0; |
| 2708 | unsigned TestMask = keywordToFPClassTest(Tok: Lex.getKind()); |
| 2709 | if (TestMask != 0) { |
| 2710 | Mask |= TestMask; |
| 2711 | // TODO: Disallow overlapping masks to avoid copy paste errors |
| 2712 | } else if (Mask == 0 && Lex.getKind() == lltok::APSInt && |
| 2713 | !parseUInt64(Val&: Value)) { |
| 2714 | if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) { |
| 2715 | error(L: Lex.getLoc(), Msg: "invalid mask value for 'nofpclass'" ); |
| 2716 | return 0; |
| 2717 | } |
| 2718 | |
| 2719 | if (!EatIfPresent(T: lltok::rparen)) { |
| 2720 | error(L: Lex.getLoc(), Msg: "expected ')'" ); |
| 2721 | return 0; |
| 2722 | } |
| 2723 | |
| 2724 | return Value; |
| 2725 | } else { |
| 2726 | error(L: Lex.getLoc(), Msg: "expected nofpclass test mask" ); |
| 2727 | return 0; |
| 2728 | } |
| 2729 | |
| 2730 | Lex.Lex(); |
| 2731 | if (EatIfPresent(T: lltok::rparen)) |
| 2732 | return Mask; |
| 2733 | } while (1); |
| 2734 | |
| 2735 | llvm_unreachable("unterminated nofpclass attribute" ); |
| 2736 | } |
| 2737 | |
| 2738 | /// parseOptionalCommaAlign |
| 2739 | /// ::= |
| 2740 | /// ::= ',' align 4 |
| 2741 | /// |
| 2742 | /// This returns with AteExtraComma set to true if it ate an excess comma at the |
| 2743 | /// end. |
| 2744 | bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment, |
| 2745 | bool &) { |
| 2746 | AteExtraComma = false; |
| 2747 | while (EatIfPresent(T: lltok::comma)) { |
| 2748 | // Metadata at the end is an early exit. |
| 2749 | if (Lex.getKind() == lltok::MetadataVar) { |
| 2750 | AteExtraComma = true; |
| 2751 | return false; |
| 2752 | } |
| 2753 | |
| 2754 | if (Lex.getKind() != lltok::kw_align) |
| 2755 | return error(L: Lex.getLoc(), Msg: "expected metadata or 'align'" ); |
| 2756 | |
| 2757 | if (parseOptionalAlignment(Alignment)) |
| 2758 | return true; |
| 2759 | } |
| 2760 | |
| 2761 | return false; |
| 2762 | } |
| 2763 | |
| 2764 | /// parseOptionalCommaAddrSpace |
| 2765 | /// ::= |
| 2766 | /// ::= ',' addrspace(1) |
| 2767 | /// |
| 2768 | /// This returns with AteExtraComma set to true if it ate an excess comma at the |
| 2769 | /// end. |
| 2770 | bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc, |
| 2771 | bool &) { |
| 2772 | AteExtraComma = false; |
| 2773 | while (EatIfPresent(T: lltok::comma)) { |
| 2774 | // Metadata at the end is an early exit. |
| 2775 | if (Lex.getKind() == lltok::MetadataVar) { |
| 2776 | AteExtraComma = true; |
| 2777 | return false; |
| 2778 | } |
| 2779 | |
| 2780 | Loc = Lex.getLoc(); |
| 2781 | if (Lex.getKind() != lltok::kw_addrspace) |
| 2782 | return error(L: Lex.getLoc(), Msg: "expected metadata or 'addrspace'" ); |
| 2783 | |
| 2784 | if (parseOptionalAddrSpace(AddrSpace)) |
| 2785 | return true; |
| 2786 | } |
| 2787 | |
| 2788 | return false; |
| 2789 | } |
| 2790 | |
| 2791 | bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg, |
| 2792 | std::optional<unsigned> &HowManyArg) { |
| 2793 | Lex.Lex(); |
| 2794 | |
| 2795 | auto StartParen = Lex.getLoc(); |
| 2796 | if (!EatIfPresent(T: lltok::lparen)) |
| 2797 | return error(L: StartParen, Msg: "expected '('" ); |
| 2798 | |
| 2799 | if (parseUInt32(Val&: BaseSizeArg)) |
| 2800 | return true; |
| 2801 | |
| 2802 | if (EatIfPresent(T: lltok::comma)) { |
| 2803 | auto HowManyAt = Lex.getLoc(); |
| 2804 | unsigned HowMany; |
| 2805 | if (parseUInt32(Val&: HowMany)) |
| 2806 | return true; |
| 2807 | if (HowMany == BaseSizeArg) |
| 2808 | return error(L: HowManyAt, |
| 2809 | Msg: "'allocsize' indices can't refer to the same parameter" ); |
| 2810 | HowManyArg = HowMany; |
| 2811 | } else |
| 2812 | HowManyArg = std::nullopt; |
| 2813 | |
| 2814 | auto EndParen = Lex.getLoc(); |
| 2815 | if (!EatIfPresent(T: lltok::rparen)) |
| 2816 | return error(L: EndParen, Msg: "expected ')'" ); |
| 2817 | return false; |
| 2818 | } |
| 2819 | |
| 2820 | bool LLParser::parseVScaleRangeArguments(unsigned &MinValue, |
| 2821 | unsigned &MaxValue) { |
| 2822 | Lex.Lex(); |
| 2823 | |
| 2824 | auto StartParen = Lex.getLoc(); |
| 2825 | if (!EatIfPresent(T: lltok::lparen)) |
| 2826 | return error(L: StartParen, Msg: "expected '('" ); |
| 2827 | |
| 2828 | if (parseUInt32(Val&: MinValue)) |
| 2829 | return true; |
| 2830 | |
| 2831 | if (EatIfPresent(T: lltok::comma)) { |
| 2832 | if (parseUInt32(Val&: MaxValue)) |
| 2833 | return true; |
| 2834 | } else |
| 2835 | MaxValue = MinValue; |
| 2836 | |
| 2837 | auto EndParen = Lex.getLoc(); |
| 2838 | if (!EatIfPresent(T: lltok::rparen)) |
| 2839 | return error(L: EndParen, Msg: "expected ')'" ); |
| 2840 | return false; |
| 2841 | } |
| 2842 | |
| 2843 | /// parseScopeAndOrdering |
| 2844 | /// if isAtomic: ::= SyncScope? AtomicOrdering |
| 2845 | /// else: ::= |
| 2846 | /// |
| 2847 | /// This sets Scope and Ordering to the parsed values. |
| 2848 | bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID, |
| 2849 | AtomicOrdering &Ordering) { |
| 2850 | if (!IsAtomic) |
| 2851 | return false; |
| 2852 | |
| 2853 | return parseScope(SSID) || parseOrdering(Ordering); |
| 2854 | } |
| 2855 | |
| 2856 | /// parseScope |
| 2857 | /// ::= syncscope("singlethread" | "<target scope>")? |
| 2858 | /// |
| 2859 | /// This sets synchronization scope ID to the ID of the parsed value. |
| 2860 | bool LLParser::parseScope(SyncScope::ID &SSID) { |
| 2861 | SSID = SyncScope::System; |
| 2862 | if (EatIfPresent(T: lltok::kw_syncscope)) { |
| 2863 | auto StartParenAt = Lex.getLoc(); |
| 2864 | if (!EatIfPresent(T: lltok::lparen)) |
| 2865 | return error(L: StartParenAt, Msg: "Expected '(' in syncscope" ); |
| 2866 | |
| 2867 | std::string SSN; |
| 2868 | auto SSNAt = Lex.getLoc(); |
| 2869 | if (parseStringConstant(Result&: SSN)) |
| 2870 | return error(L: SSNAt, Msg: "Expected synchronization scope name" ); |
| 2871 | |
| 2872 | auto EndParenAt = Lex.getLoc(); |
| 2873 | if (!EatIfPresent(T: lltok::rparen)) |
| 2874 | return error(L: EndParenAt, Msg: "Expected ')' in syncscope" ); |
| 2875 | |
| 2876 | SSID = Context.getOrInsertSyncScopeID(SSN); |
| 2877 | } |
| 2878 | |
| 2879 | return false; |
| 2880 | } |
| 2881 | |
| 2882 | /// parseOrdering |
| 2883 | /// ::= AtomicOrdering |
| 2884 | /// |
| 2885 | /// This sets Ordering to the parsed value. |
| 2886 | bool LLParser::parseOrdering(AtomicOrdering &Ordering) { |
| 2887 | switch (Lex.getKind()) { |
| 2888 | default: |
| 2889 | return tokError(Msg: "Expected ordering on atomic instruction" ); |
| 2890 | case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break; |
| 2891 | case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break; |
| 2892 | // Not specified yet: |
| 2893 | // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break; |
| 2894 | case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break; |
| 2895 | case lltok::kw_release: Ordering = AtomicOrdering::Release; break; |
| 2896 | case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break; |
| 2897 | case lltok::kw_seq_cst: |
| 2898 | Ordering = AtomicOrdering::SequentiallyConsistent; |
| 2899 | break; |
| 2900 | } |
| 2901 | Lex.Lex(); |
| 2902 | return false; |
| 2903 | } |
| 2904 | |
| 2905 | /// parseOptionalStackAlignment |
| 2906 | /// ::= /* empty */ |
| 2907 | /// ::= 'alignstack' '(' 4 ')' |
| 2908 | bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) { |
| 2909 | Alignment = 0; |
| 2910 | if (!EatIfPresent(T: lltok::kw_alignstack)) |
| 2911 | return false; |
| 2912 | LocTy ParenLoc = Lex.getLoc(); |
| 2913 | if (!EatIfPresent(T: lltok::lparen)) |
| 2914 | return error(L: ParenLoc, Msg: "expected '('" ); |
| 2915 | LocTy AlignLoc = Lex.getLoc(); |
| 2916 | if (parseUInt32(Val&: Alignment)) |
| 2917 | return true; |
| 2918 | ParenLoc = Lex.getLoc(); |
| 2919 | if (!EatIfPresent(T: lltok::rparen)) |
| 2920 | return error(L: ParenLoc, Msg: "expected ')'" ); |
| 2921 | if (!isPowerOf2_32(Value: Alignment)) |
| 2922 | return error(L: AlignLoc, Msg: "stack alignment is not a power of two" ); |
| 2923 | return false; |
| 2924 | } |
| 2925 | |
| 2926 | /// parseIndexList - This parses the index list for an insert/extractvalue |
| 2927 | /// instruction. This sets AteExtraComma in the case where we eat an extra |
| 2928 | /// comma at the end of the line and find that it is followed by metadata. |
| 2929 | /// Clients that don't allow metadata can call the version of this function that |
| 2930 | /// only takes one argument. |
| 2931 | /// |
| 2932 | /// parseIndexList |
| 2933 | /// ::= (',' uint32)+ |
| 2934 | /// |
| 2935 | bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices, |
| 2936 | bool &) { |
| 2937 | AteExtraComma = false; |
| 2938 | |
| 2939 | if (Lex.getKind() != lltok::comma) |
| 2940 | return tokError(Msg: "expected ',' as start of index list" ); |
| 2941 | |
| 2942 | while (EatIfPresent(T: lltok::comma)) { |
| 2943 | if (Lex.getKind() == lltok::MetadataVar) { |
| 2944 | if (Indices.empty()) |
| 2945 | return tokError(Msg: "expected index" ); |
| 2946 | AteExtraComma = true; |
| 2947 | return false; |
| 2948 | } |
| 2949 | unsigned Idx = 0; |
| 2950 | if (parseUInt32(Val&: Idx)) |
| 2951 | return true; |
| 2952 | Indices.push_back(Elt: Idx); |
| 2953 | } |
| 2954 | |
| 2955 | return false; |
| 2956 | } |
| 2957 | |
| 2958 | //===----------------------------------------------------------------------===// |
| 2959 | // Type Parsing. |
| 2960 | //===----------------------------------------------------------------------===// |
| 2961 | |
| 2962 | /// parseType - parse a type. |
| 2963 | bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) { |
| 2964 | SMLoc TypeLoc = Lex.getLoc(); |
| 2965 | switch (Lex.getKind()) { |
| 2966 | default: |
| 2967 | return tokError(Msg); |
| 2968 | case lltok::Type: |
| 2969 | // Type ::= 'float' | 'void' (etc) |
| 2970 | Result = Lex.getTyVal(); |
| 2971 | Lex.Lex(); |
| 2972 | |
| 2973 | // Handle "ptr" opaque pointer type. |
| 2974 | // |
| 2975 | // Type ::= ptr ('addrspace' '(' uint32 ')')? |
| 2976 | if (Result->isPointerTy()) { |
| 2977 | unsigned AddrSpace; |
| 2978 | if (parseOptionalAddrSpace(AddrSpace)) |
| 2979 | return true; |
| 2980 | Result = PointerType::get(C&: getContext(), AddressSpace: AddrSpace); |
| 2981 | |
| 2982 | // Give a nice error for 'ptr*'. |
| 2983 | if (Lex.getKind() == lltok::star) |
| 2984 | return tokError(Msg: "ptr* is invalid - use ptr instead" ); |
| 2985 | |
| 2986 | // Fall through to parsing the type suffixes only if this 'ptr' is a |
| 2987 | // function return. Otherwise, return success, implicitly rejecting other |
| 2988 | // suffixes. |
| 2989 | if (Lex.getKind() != lltok::lparen) |
| 2990 | return false; |
| 2991 | } |
| 2992 | break; |
| 2993 | case lltok::kw_target: { |
| 2994 | // Type ::= TargetExtType |
| 2995 | if (parseTargetExtType(Result)) |
| 2996 | return true; |
| 2997 | break; |
| 2998 | } |
| 2999 | case lltok::lbrace: |
| 3000 | // Type ::= StructType |
| 3001 | if (parseAnonStructType(Result, Packed: false)) |
| 3002 | return true; |
| 3003 | break; |
| 3004 | case lltok::lsquare: |
| 3005 | // Type ::= '[' ... ']' |
| 3006 | Lex.Lex(); // eat the lsquare. |
| 3007 | if (parseArrayVectorType(Result, IsVector: false)) |
| 3008 | return true; |
| 3009 | break; |
| 3010 | case lltok::less: // Either vector or packed struct. |
| 3011 | // Type ::= '<' ... '>' |
| 3012 | Lex.Lex(); |
| 3013 | if (Lex.getKind() == lltok::lbrace) { |
| 3014 | if (parseAnonStructType(Result, Packed: true) || |
| 3015 | parseToken(T: lltok::greater, ErrMsg: "expected '>' at end of packed struct" )) |
| 3016 | return true; |
| 3017 | } else if (parseArrayVectorType(Result, IsVector: true)) |
| 3018 | return true; |
| 3019 | break; |
| 3020 | case lltok::LocalVar: { |
| 3021 | // Type ::= %foo |
| 3022 | std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; |
| 3023 | |
| 3024 | // If the type hasn't been defined yet, create a forward definition and |
| 3025 | // remember where that forward def'n was seen (in case it never is defined). |
| 3026 | if (!Entry.first) { |
| 3027 | Entry.first = StructType::create(Context, Name: Lex.getStrVal()); |
| 3028 | Entry.second = Lex.getLoc(); |
| 3029 | } |
| 3030 | Result = Entry.first; |
| 3031 | Lex.Lex(); |
| 3032 | break; |
| 3033 | } |
| 3034 | |
| 3035 | case lltok::LocalVarID: { |
| 3036 | // Type ::= %4 |
| 3037 | std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; |
| 3038 | |
| 3039 | // If the type hasn't been defined yet, create a forward definition and |
| 3040 | // remember where that forward def'n was seen (in case it never is defined). |
| 3041 | if (!Entry.first) { |
| 3042 | Entry.first = StructType::create(Context); |
| 3043 | Entry.second = Lex.getLoc(); |
| 3044 | } |
| 3045 | Result = Entry.first; |
| 3046 | Lex.Lex(); |
| 3047 | break; |
| 3048 | } |
| 3049 | } |
| 3050 | |
| 3051 | // parse the type suffixes. |
| 3052 | while (true) { |
| 3053 | switch (Lex.getKind()) { |
| 3054 | // End of type. |
| 3055 | default: |
| 3056 | if (!AllowVoid && Result->isVoidTy()) |
| 3057 | return error(L: TypeLoc, Msg: "void type only allowed for function results" ); |
| 3058 | return false; |
| 3059 | |
| 3060 | // Type ::= Type '*' |
| 3061 | case lltok::star: |
| 3062 | if (Result->isLabelTy()) |
| 3063 | return tokError(Msg: "basic block pointers are invalid" ); |
| 3064 | if (Result->isVoidTy()) |
| 3065 | return tokError(Msg: "pointers to void are invalid - use i8* instead" ); |
| 3066 | if (!PointerType::isValidElementType(ElemTy: Result)) |
| 3067 | return tokError(Msg: "pointer to this type is invalid" ); |
| 3068 | Result = PointerType::getUnqual(C&: Context); |
| 3069 | Lex.Lex(); |
| 3070 | break; |
| 3071 | |
| 3072 | // Type ::= Type 'addrspace' '(' uint32 ')' '*' |
| 3073 | case lltok::kw_addrspace: { |
| 3074 | if (Result->isLabelTy()) |
| 3075 | return tokError(Msg: "basic block pointers are invalid" ); |
| 3076 | if (Result->isVoidTy()) |
| 3077 | return tokError(Msg: "pointers to void are invalid; use i8* instead" ); |
| 3078 | if (!PointerType::isValidElementType(ElemTy: Result)) |
| 3079 | return tokError(Msg: "pointer to this type is invalid" ); |
| 3080 | unsigned AddrSpace; |
| 3081 | if (parseOptionalAddrSpace(AddrSpace) || |
| 3082 | parseToken(T: lltok::star, ErrMsg: "expected '*' in address space" )) |
| 3083 | return true; |
| 3084 | |
| 3085 | Result = PointerType::get(C&: Context, AddressSpace: AddrSpace); |
| 3086 | break; |
| 3087 | } |
| 3088 | |
| 3089 | /// Types '(' ArgTypeListI ')' OptFuncAttrs |
| 3090 | case lltok::lparen: |
| 3091 | if (parseFunctionType(Result)) |
| 3092 | return true; |
| 3093 | break; |
| 3094 | } |
| 3095 | } |
| 3096 | } |
| 3097 | |
| 3098 | /// parseParameterList |
| 3099 | /// ::= '(' ')' |
| 3100 | /// ::= '(' Arg (',' Arg)* ')' |
| 3101 | /// Arg |
| 3102 | /// ::= Type OptionalAttributes Value OptionalAttributes |
| 3103 | bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList, |
| 3104 | PerFunctionState &PFS, bool IsMustTailCall, |
| 3105 | bool InVarArgsFunc) { |
| 3106 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in call" )) |
| 3107 | return true; |
| 3108 | |
| 3109 | while (Lex.getKind() != lltok::rparen) { |
| 3110 | // If this isn't the first argument, we need a comma. |
| 3111 | if (!ArgList.empty() && |
| 3112 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in argument list" )) |
| 3113 | return true; |
| 3114 | |
| 3115 | // parse an ellipsis if this is a musttail call in a variadic function. |
| 3116 | if (Lex.getKind() == lltok::dotdotdot) { |
| 3117 | const char *Msg = "unexpected ellipsis in argument list for " ; |
| 3118 | if (!IsMustTailCall) |
| 3119 | return tokError(Msg: Twine(Msg) + "non-musttail call" ); |
| 3120 | if (!InVarArgsFunc) |
| 3121 | return tokError(Msg: Twine(Msg) + "musttail call in non-varargs function" ); |
| 3122 | Lex.Lex(); // Lex the '...', it is purely for readability. |
| 3123 | return parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of argument list" ); |
| 3124 | } |
| 3125 | |
| 3126 | // parse the argument. |
| 3127 | LocTy ArgLoc; |
| 3128 | Type *ArgTy = nullptr; |
| 3129 | Value *V; |
| 3130 | if (parseType(Result&: ArgTy, Loc&: ArgLoc)) |
| 3131 | return true; |
| 3132 | if (!FunctionType::isValidArgumentType(ArgTy)) |
| 3133 | return error(L: ArgLoc, Msg: "invalid type for function argument" ); |
| 3134 | |
| 3135 | AttrBuilder ArgAttrs(M->getContext()); |
| 3136 | |
| 3137 | if (ArgTy->isMetadataTy()) { |
| 3138 | if (parseMetadataAsValue(V, PFS)) |
| 3139 | return true; |
| 3140 | } else { |
| 3141 | // Otherwise, handle normal operands. |
| 3142 | if (parseOptionalParamAttrs(B&: ArgAttrs) || parseValue(Ty: ArgTy, V, PFS)) |
| 3143 | return true; |
| 3144 | } |
| 3145 | ArgList.push_back(Elt: ParamInfo( |
| 3146 | ArgLoc, V, AttributeSet::get(C&: V->getContext(), B: ArgAttrs))); |
| 3147 | } |
| 3148 | |
| 3149 | if (IsMustTailCall && InVarArgsFunc) |
| 3150 | return tokError(Msg: "expected '...' at end of argument list for musttail call " |
| 3151 | "in varargs function" ); |
| 3152 | |
| 3153 | Lex.Lex(); // Lex the ')'. |
| 3154 | return false; |
| 3155 | } |
| 3156 | |
| 3157 | /// parseRequiredTypeAttr |
| 3158 | /// ::= attrname(<ty>) |
| 3159 | bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken, |
| 3160 | Attribute::AttrKind AttrKind) { |
| 3161 | Type *Ty = nullptr; |
| 3162 | if (!EatIfPresent(T: AttrToken)) |
| 3163 | return true; |
| 3164 | if (!EatIfPresent(T: lltok::lparen)) |
| 3165 | return error(L: Lex.getLoc(), Msg: "expected '('" ); |
| 3166 | if (parseType(Result&: Ty)) |
| 3167 | return true; |
| 3168 | if (!EatIfPresent(T: lltok::rparen)) |
| 3169 | return error(L: Lex.getLoc(), Msg: "expected ')'" ); |
| 3170 | |
| 3171 | B.addTypeAttr(Kind: AttrKind, Ty); |
| 3172 | return false; |
| 3173 | } |
| 3174 | |
| 3175 | /// parseRangeAttr |
| 3176 | /// ::= range(<ty> <n>,<n>) |
| 3177 | bool LLParser::parseRangeAttr(AttrBuilder &B) { |
| 3178 | Lex.Lex(); |
| 3179 | |
| 3180 | APInt Lower; |
| 3181 | APInt Upper; |
| 3182 | Type *Ty = nullptr; |
| 3183 | LocTy TyLoc; |
| 3184 | |
| 3185 | auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) { |
| 3186 | if (Lex.getKind() != lltok::APSInt) |
| 3187 | return tokError(Msg: "expected integer" ); |
| 3188 | if (Lex.getAPSIntVal().getBitWidth() > BitWidth) |
| 3189 | return tokError( |
| 3190 | Msg: "integer is too large for the bit width of specified type" ); |
| 3191 | Val = Lex.getAPSIntVal().extend(width: BitWidth); |
| 3192 | Lex.Lex(); |
| 3193 | return false; |
| 3194 | }; |
| 3195 | |
| 3196 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '('" ) || parseType(Result&: Ty, Loc&: TyLoc)) |
| 3197 | return true; |
| 3198 | if (!Ty->isIntegerTy()) |
| 3199 | return error(L: TyLoc, Msg: "the range must have integer type!" ); |
| 3200 | |
| 3201 | unsigned BitWidth = Ty->getPrimitiveSizeInBits(); |
| 3202 | |
| 3203 | if (ParseAPSInt(BitWidth, Lower) || |
| 3204 | parseToken(T: lltok::comma, ErrMsg: "expected ','" ) || ParseAPSInt(BitWidth, Upper)) |
| 3205 | return true; |
| 3206 | if (Lower == Upper && !Lower.isZero()) |
| 3207 | return tokError(Msg: "the range represent the empty set but limits aren't 0!" ); |
| 3208 | |
| 3209 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'" )) |
| 3210 | return true; |
| 3211 | |
| 3212 | B.addRangeAttr(CR: ConstantRange(Lower, Upper)); |
| 3213 | return false; |
| 3214 | } |
| 3215 | |
| 3216 | /// parseInitializesAttr |
| 3217 | /// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...) |
| 3218 | bool LLParser::parseInitializesAttr(AttrBuilder &B) { |
| 3219 | Lex.Lex(); |
| 3220 | |
| 3221 | auto ParseAPSInt = [&](APInt &Val) { |
| 3222 | if (Lex.getKind() != lltok::APSInt) |
| 3223 | return tokError(Msg: "expected integer" ); |
| 3224 | Val = Lex.getAPSIntVal().extend(width: 64); |
| 3225 | Lex.Lex(); |
| 3226 | return false; |
| 3227 | }; |
| 3228 | |
| 3229 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '('" )) |
| 3230 | return true; |
| 3231 | |
| 3232 | SmallVector<ConstantRange, 2> RangeList; |
| 3233 | // Parse each constant range. |
| 3234 | do { |
| 3235 | APInt Lower, Upper; |
| 3236 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '('" )) |
| 3237 | return true; |
| 3238 | |
| 3239 | if (ParseAPSInt(Lower) || parseToken(T: lltok::comma, ErrMsg: "expected ','" ) || |
| 3240 | ParseAPSInt(Upper)) |
| 3241 | return true; |
| 3242 | |
| 3243 | if (Lower == Upper) |
| 3244 | return tokError(Msg: "the range should not represent the full or empty set!" ); |
| 3245 | |
| 3246 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'" )) |
| 3247 | return true; |
| 3248 | |
| 3249 | RangeList.push_back(Elt: ConstantRange(Lower, Upper)); |
| 3250 | } while (EatIfPresent(T: lltok::comma)); |
| 3251 | |
| 3252 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'" )) |
| 3253 | return true; |
| 3254 | |
| 3255 | auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangesRef: RangeList); |
| 3256 | if (!CRLOrNull.has_value()) |
| 3257 | return tokError(Msg: "Invalid (unordered or overlapping) range list" ); |
| 3258 | B.addInitializesAttr(CRL: *CRLOrNull); |
| 3259 | return false; |
| 3260 | } |
| 3261 | |
| 3262 | bool LLParser::parseCapturesAttr(AttrBuilder &B) { |
| 3263 | CaptureComponents Other = CaptureComponents::None; |
| 3264 | std::optional<CaptureComponents> Ret; |
| 3265 | |
| 3266 | // We use syntax like captures(ret: address, provenance), so the colon |
| 3267 | // should not be interpreted as a label terminator. |
| 3268 | Lex.setIgnoreColonInIdentifiers(true); |
| 3269 | llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); }); |
| 3270 | |
| 3271 | Lex.Lex(); |
| 3272 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '('" )) |
| 3273 | return true; |
| 3274 | |
| 3275 | CaptureComponents *Current = &Other; |
| 3276 | bool SeenComponent = false; |
| 3277 | while (true) { |
| 3278 | if (EatIfPresent(T: lltok::kw_ret)) { |
| 3279 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 3280 | return true; |
| 3281 | if (Ret) |
| 3282 | return tokError(Msg: "duplicate 'ret' location" ); |
| 3283 | Ret = CaptureComponents::None; |
| 3284 | Current = &*Ret; |
| 3285 | SeenComponent = false; |
| 3286 | } |
| 3287 | |
| 3288 | if (EatIfPresent(T: lltok::kw_none)) { |
| 3289 | if (SeenComponent) |
| 3290 | return tokError(Msg: "cannot use 'none' with other component" ); |
| 3291 | *Current = CaptureComponents::None; |
| 3292 | } else { |
| 3293 | if (SeenComponent && capturesNothing(CC: *Current)) |
| 3294 | return tokError(Msg: "cannot use 'none' with other component" ); |
| 3295 | |
| 3296 | if (EatIfPresent(T: lltok::kw_address_is_null)) |
| 3297 | *Current |= CaptureComponents::AddressIsNull; |
| 3298 | else if (EatIfPresent(T: lltok::kw_address)) |
| 3299 | *Current |= CaptureComponents::Address; |
| 3300 | else if (EatIfPresent(T: lltok::kw_provenance)) |
| 3301 | *Current |= CaptureComponents::Provenance; |
| 3302 | else if (EatIfPresent(T: lltok::kw_read_provenance)) |
| 3303 | *Current |= CaptureComponents::ReadProvenance; |
| 3304 | else |
| 3305 | return tokError(Msg: "expected one of 'none', 'address', 'address_is_null', " |
| 3306 | "'provenance' or 'read_provenance'" ); |
| 3307 | } |
| 3308 | |
| 3309 | SeenComponent = true; |
| 3310 | if (EatIfPresent(T: lltok::rparen)) |
| 3311 | break; |
| 3312 | |
| 3313 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' or ')'" )) |
| 3314 | return true; |
| 3315 | } |
| 3316 | |
| 3317 | B.addCapturesAttr(CI: CaptureInfo(Other, Ret.value_or(u&: Other))); |
| 3318 | return false; |
| 3319 | } |
| 3320 | |
| 3321 | /// parseOptionalOperandBundles |
| 3322 | /// ::= /*empty*/ |
| 3323 | /// ::= '[' OperandBundle [, OperandBundle ]* ']' |
| 3324 | /// |
| 3325 | /// OperandBundle |
| 3326 | /// ::= bundle-tag '(' ')' |
| 3327 | /// ::= bundle-tag '(' Type Value [, Type Value ]* ')' |
| 3328 | /// |
| 3329 | /// bundle-tag ::= String Constant |
| 3330 | bool LLParser::parseOptionalOperandBundles( |
| 3331 | SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) { |
| 3332 | LocTy BeginLoc = Lex.getLoc(); |
| 3333 | if (!EatIfPresent(T: lltok::lsquare)) |
| 3334 | return false; |
| 3335 | |
| 3336 | while (Lex.getKind() != lltok::rsquare) { |
| 3337 | // If this isn't the first operand bundle, we need a comma. |
| 3338 | if (!BundleList.empty() && |
| 3339 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in input list" )) |
| 3340 | return true; |
| 3341 | |
| 3342 | std::string Tag; |
| 3343 | if (parseStringConstant(Result&: Tag)) |
| 3344 | return true; |
| 3345 | |
| 3346 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in operand bundle" )) |
| 3347 | return true; |
| 3348 | |
| 3349 | std::vector<Value *> Inputs; |
| 3350 | while (Lex.getKind() != lltok::rparen) { |
| 3351 | // If this isn't the first input, we need a comma. |
| 3352 | if (!Inputs.empty() && |
| 3353 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in input list" )) |
| 3354 | return true; |
| 3355 | |
| 3356 | Type *Ty = nullptr; |
| 3357 | Value *Input = nullptr; |
| 3358 | if (parseType(Result&: Ty)) |
| 3359 | return true; |
| 3360 | if (Ty->isMetadataTy()) { |
| 3361 | if (parseMetadataAsValue(V&: Input, PFS)) |
| 3362 | return true; |
| 3363 | } else if (parseValue(Ty, V&: Input, PFS)) { |
| 3364 | return true; |
| 3365 | } |
| 3366 | Inputs.push_back(x: Input); |
| 3367 | } |
| 3368 | |
| 3369 | BundleList.emplace_back(Args: std::move(Tag), Args: std::move(Inputs)); |
| 3370 | |
| 3371 | Lex.Lex(); // Lex the ')'. |
| 3372 | } |
| 3373 | |
| 3374 | if (BundleList.empty()) |
| 3375 | return error(L: BeginLoc, Msg: "operand bundle set must not be empty" ); |
| 3376 | |
| 3377 | Lex.Lex(); // Lex the ']'. |
| 3378 | return false; |
| 3379 | } |
| 3380 | |
| 3381 | bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix, |
| 3382 | unsigned NextID, unsigned ID) { |
| 3383 | if (ID < NextID) |
| 3384 | return error(L: Loc, Msg: Kind + " expected to be numbered '" + Prefix + |
| 3385 | Twine(NextID) + "' or greater" ); |
| 3386 | |
| 3387 | return false; |
| 3388 | } |
| 3389 | |
| 3390 | /// parseArgumentList - parse the argument list for a function type or function |
| 3391 | /// prototype. |
| 3392 | /// ::= '(' ArgTypeListI ')' |
| 3393 | /// ArgTypeListI |
| 3394 | /// ::= /*empty*/ |
| 3395 | /// ::= '...' |
| 3396 | /// ::= ArgTypeList ',' '...' |
| 3397 | /// ::= ArgType (',' ArgType)* |
| 3398 | /// |
| 3399 | bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, |
| 3400 | SmallVectorImpl<unsigned> &UnnamedArgNums, |
| 3401 | bool &IsVarArg) { |
| 3402 | unsigned CurValID = 0; |
| 3403 | IsVarArg = false; |
| 3404 | assert(Lex.getKind() == lltok::lparen); |
| 3405 | Lex.Lex(); // eat the (. |
| 3406 | |
| 3407 | if (Lex.getKind() != lltok::rparen) { |
| 3408 | do { |
| 3409 | // Handle ... at end of arg list. |
| 3410 | if (EatIfPresent(T: lltok::dotdotdot)) { |
| 3411 | IsVarArg = true; |
| 3412 | break; |
| 3413 | } |
| 3414 | |
| 3415 | // Otherwise must be an argument type. |
| 3416 | LocTy TypeLoc = Lex.getLoc(); |
| 3417 | Type *ArgTy = nullptr; |
| 3418 | AttrBuilder Attrs(M->getContext()); |
| 3419 | if (parseType(Result&: ArgTy) || parseOptionalParamAttrs(B&: Attrs)) |
| 3420 | return true; |
| 3421 | |
| 3422 | if (ArgTy->isVoidTy()) |
| 3423 | return error(L: TypeLoc, Msg: "argument can not have void type" ); |
| 3424 | |
| 3425 | std::string Name; |
| 3426 | FileLoc IdentStart; |
| 3427 | FileLoc IdentEnd; |
| 3428 | bool Unnamed = false; |
| 3429 | if (Lex.getKind() == lltok::LocalVar) { |
| 3430 | Name = Lex.getStrVal(); |
| 3431 | IdentStart = Lex.getTokLineColumnPos(); |
| 3432 | Lex.Lex(); |
| 3433 | IdentEnd = Lex.getPrevTokEndLineColumnPos(); |
| 3434 | } else { |
| 3435 | unsigned ArgID; |
| 3436 | if (Lex.getKind() == lltok::LocalVarID) { |
| 3437 | ArgID = Lex.getUIntVal(); |
| 3438 | IdentStart = Lex.getTokLineColumnPos(); |
| 3439 | if (checkValueID(Loc: TypeLoc, Kind: "argument" , Prefix: "%" , NextID: CurValID, ID: ArgID)) |
| 3440 | return true; |
| 3441 | Lex.Lex(); |
| 3442 | IdentEnd = Lex.getPrevTokEndLineColumnPos(); |
| 3443 | } else { |
| 3444 | ArgID = CurValID; |
| 3445 | Unnamed = true; |
| 3446 | } |
| 3447 | UnnamedArgNums.push_back(Elt: ArgID); |
| 3448 | CurValID = ArgID + 1; |
| 3449 | } |
| 3450 | |
| 3451 | if (!FunctionType::isValidArgumentType(ArgTy)) |
| 3452 | return error(L: TypeLoc, Msg: "invalid type for function argument" ); |
| 3453 | |
| 3454 | ArgList.emplace_back( |
| 3455 | Args&: TypeLoc, Args&: ArgTy, |
| 3456 | Args: Unnamed ? std::nullopt |
| 3457 | : std::make_optional(t: FileLocRange(IdentStart, IdentEnd)), |
| 3458 | Args: AttributeSet::get(C&: ArgTy->getContext(), B: Attrs), Args: std::move(Name)); |
| 3459 | } while (EatIfPresent(T: lltok::comma)); |
| 3460 | } |
| 3461 | |
| 3462 | return parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of argument list" ); |
| 3463 | } |
| 3464 | |
| 3465 | /// parseFunctionType |
| 3466 | /// ::= Type ArgumentList OptionalAttrs |
| 3467 | bool LLParser::parseFunctionType(Type *&Result) { |
| 3468 | assert(Lex.getKind() == lltok::lparen); |
| 3469 | |
| 3470 | if (!FunctionType::isValidReturnType(RetTy: Result)) |
| 3471 | return tokError(Msg: "invalid function return type" ); |
| 3472 | |
| 3473 | SmallVector<ArgInfo, 8> ArgList; |
| 3474 | bool IsVarArg; |
| 3475 | SmallVector<unsigned> UnnamedArgNums; |
| 3476 | if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg)) |
| 3477 | return true; |
| 3478 | |
| 3479 | // Reject names on the arguments lists. |
| 3480 | for (const ArgInfo &Arg : ArgList) { |
| 3481 | if (!Arg.Name.empty()) |
| 3482 | return error(L: Arg.Loc, Msg: "argument name invalid in function type" ); |
| 3483 | if (Arg.Attrs.hasAttributes()) |
| 3484 | return error(L: Arg.Loc, Msg: "argument attributes invalid in function type" ); |
| 3485 | } |
| 3486 | |
| 3487 | SmallVector<Type*, 16> ArgListTy; |
| 3488 | for (const ArgInfo &Arg : ArgList) |
| 3489 | ArgListTy.push_back(Elt: Arg.Ty); |
| 3490 | |
| 3491 | Result = FunctionType::get(Result, Params: ArgListTy, isVarArg: IsVarArg); |
| 3492 | return false; |
| 3493 | } |
| 3494 | |
| 3495 | /// parseAnonStructType - parse an anonymous struct type, which is inlined into |
| 3496 | /// other structs. |
| 3497 | bool LLParser::parseAnonStructType(Type *&Result, bool Packed) { |
| 3498 | SmallVector<Type*, 8> Elts; |
| 3499 | if (parseStructBody(Body&: Elts)) |
| 3500 | return true; |
| 3501 | |
| 3502 | Result = StructType::get(Context, Elements: Elts, isPacked: Packed); |
| 3503 | return false; |
| 3504 | } |
| 3505 | |
| 3506 | /// parseStructDefinition - parse a struct in a 'type' definition. |
| 3507 | bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name, |
| 3508 | std::pair<Type *, LocTy> &Entry, |
| 3509 | Type *&ResultTy) { |
| 3510 | // If the type was already defined, diagnose the redefinition. |
| 3511 | if (Entry.first && !Entry.second.isValid()) |
| 3512 | return error(L: TypeLoc, Msg: "redefinition of type" ); |
| 3513 | |
| 3514 | // If we have opaque, just return without filling in the definition for the |
| 3515 | // struct. This counts as a definition as far as the .ll file goes. |
| 3516 | if (EatIfPresent(T: lltok::kw_opaque)) { |
| 3517 | // This type is being defined, so clear the location to indicate this. |
| 3518 | Entry.second = SMLoc(); |
| 3519 | |
| 3520 | // If this type number has never been uttered, create it. |
| 3521 | if (!Entry.first) |
| 3522 | Entry.first = StructType::create(Context, Name); |
| 3523 | ResultTy = Entry.first; |
| 3524 | return false; |
| 3525 | } |
| 3526 | |
| 3527 | // If the type starts with '<', then it is either a packed struct or a vector. |
| 3528 | bool isPacked = EatIfPresent(T: lltok::less); |
| 3529 | |
| 3530 | // If we don't have a struct, then we have a random type alias, which we |
| 3531 | // accept for compatibility with old files. These types are not allowed to be |
| 3532 | // forward referenced and not allowed to be recursive. |
| 3533 | if (Lex.getKind() != lltok::lbrace) { |
| 3534 | if (Entry.first) |
| 3535 | return error(L: TypeLoc, Msg: "forward references to non-struct type" ); |
| 3536 | |
| 3537 | ResultTy = nullptr; |
| 3538 | if (isPacked) |
| 3539 | return parseArrayVectorType(Result&: ResultTy, IsVector: true); |
| 3540 | return parseType(Result&: ResultTy); |
| 3541 | } |
| 3542 | |
| 3543 | // This type is being defined, so clear the location to indicate this. |
| 3544 | Entry.second = SMLoc(); |
| 3545 | |
| 3546 | // If this type number has never been uttered, create it. |
| 3547 | if (!Entry.first) |
| 3548 | Entry.first = StructType::create(Context, Name); |
| 3549 | |
| 3550 | StructType *STy = cast<StructType>(Val: Entry.first); |
| 3551 | |
| 3552 | SmallVector<Type*, 8> Body; |
| 3553 | if (parseStructBody(Body) || |
| 3554 | (isPacked && parseToken(T: lltok::greater, ErrMsg: "expected '>' in packed struct" ))) |
| 3555 | return true; |
| 3556 | |
| 3557 | if (auto E = STy->setBodyOrError(Elements: Body, isPacked)) |
| 3558 | return tokError(Msg: toString(E: std::move(E))); |
| 3559 | |
| 3560 | ResultTy = STy; |
| 3561 | return false; |
| 3562 | } |
| 3563 | |
| 3564 | /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere. |
| 3565 | /// StructType |
| 3566 | /// ::= '{' '}' |
| 3567 | /// ::= '{' Type (',' Type)* '}' |
| 3568 | /// ::= '<' '{' '}' '>' |
| 3569 | /// ::= '<' '{' Type (',' Type)* '}' '>' |
| 3570 | bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) { |
| 3571 | assert(Lex.getKind() == lltok::lbrace); |
| 3572 | Lex.Lex(); // Consume the '{' |
| 3573 | |
| 3574 | // Handle the empty struct. |
| 3575 | if (EatIfPresent(T: lltok::rbrace)) |
| 3576 | return false; |
| 3577 | |
| 3578 | LocTy EltTyLoc = Lex.getLoc(); |
| 3579 | Type *Ty = nullptr; |
| 3580 | if (parseType(Result&: Ty)) |
| 3581 | return true; |
| 3582 | Body.push_back(Elt: Ty); |
| 3583 | |
| 3584 | if (!StructType::isValidElementType(ElemTy: Ty)) |
| 3585 | return error(L: EltTyLoc, Msg: "invalid element type for struct" ); |
| 3586 | |
| 3587 | while (EatIfPresent(T: lltok::comma)) { |
| 3588 | EltTyLoc = Lex.getLoc(); |
| 3589 | if (parseType(Result&: Ty)) |
| 3590 | return true; |
| 3591 | |
| 3592 | if (!StructType::isValidElementType(ElemTy: Ty)) |
| 3593 | return error(L: EltTyLoc, Msg: "invalid element type for struct" ); |
| 3594 | |
| 3595 | Body.push_back(Elt: Ty); |
| 3596 | } |
| 3597 | |
| 3598 | return parseToken(T: lltok::rbrace, ErrMsg: "expected '}' at end of struct" ); |
| 3599 | } |
| 3600 | |
| 3601 | /// parseArrayVectorType - parse an array or vector type, assuming the first |
| 3602 | /// token has already been consumed. |
| 3603 | /// Type |
| 3604 | /// ::= '[' APSINTVAL 'x' Types ']' |
| 3605 | /// ::= '<' APSINTVAL 'x' Types '>' |
| 3606 | /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>' |
| 3607 | bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) { |
| 3608 | bool Scalable = false; |
| 3609 | |
| 3610 | if (IsVector && Lex.getKind() == lltok::kw_vscale) { |
| 3611 | Lex.Lex(); // consume the 'vscale' |
| 3612 | if (parseToken(T: lltok::kw_x, ErrMsg: "expected 'x' after vscale" )) |
| 3613 | return true; |
| 3614 | |
| 3615 | Scalable = true; |
| 3616 | } |
| 3617 | |
| 3618 | if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || |
| 3619 | Lex.getAPSIntVal().getBitWidth() > 64) |
| 3620 | return tokError(Msg: "expected number in address space" ); |
| 3621 | |
| 3622 | LocTy SizeLoc = Lex.getLoc(); |
| 3623 | uint64_t Size = Lex.getAPSIntVal().getZExtValue(); |
| 3624 | Lex.Lex(); |
| 3625 | |
| 3626 | if (parseToken(T: lltok::kw_x, ErrMsg: "expected 'x' after element count" )) |
| 3627 | return true; |
| 3628 | |
| 3629 | LocTy TypeLoc = Lex.getLoc(); |
| 3630 | Type *EltTy = nullptr; |
| 3631 | if (parseType(Result&: EltTy)) |
| 3632 | return true; |
| 3633 | |
| 3634 | if (parseToken(T: IsVector ? lltok::greater : lltok::rsquare, |
| 3635 | ErrMsg: "expected end of sequential type" )) |
| 3636 | return true; |
| 3637 | |
| 3638 | if (IsVector) { |
| 3639 | if (Size == 0) |
| 3640 | return error(L: SizeLoc, Msg: "zero element vector is illegal" ); |
| 3641 | if ((unsigned)Size != Size) |
| 3642 | return error(L: SizeLoc, Msg: "size too large for vector" ); |
| 3643 | if (!VectorType::isValidElementType(ElemTy: EltTy)) |
| 3644 | return error(L: TypeLoc, Msg: "invalid vector element type" ); |
| 3645 | Result = VectorType::get(ElementType: EltTy, NumElements: unsigned(Size), Scalable); |
| 3646 | } else { |
| 3647 | if (!ArrayType::isValidElementType(ElemTy: EltTy)) |
| 3648 | return error(L: TypeLoc, Msg: "invalid array element type" ); |
| 3649 | Result = ArrayType::get(ElementType: EltTy, NumElements: Size); |
| 3650 | } |
| 3651 | return false; |
| 3652 | } |
| 3653 | |
| 3654 | /// parseTargetExtType - handle target extension type syntax |
| 3655 | /// TargetExtType |
| 3656 | /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')' |
| 3657 | /// |
| 3658 | /// TargetExtTypeParams |
| 3659 | /// ::= /*empty*/ |
| 3660 | /// ::= ',' Type TargetExtTypeParams |
| 3661 | /// |
| 3662 | /// TargetExtIntParams |
| 3663 | /// ::= /*empty*/ |
| 3664 | /// ::= ',' uint32 TargetExtIntParams |
| 3665 | bool LLParser::parseTargetExtType(Type *&Result) { |
| 3666 | Lex.Lex(); // Eat the 'target' keyword. |
| 3667 | |
| 3668 | // Get the mandatory type name. |
| 3669 | std::string TypeName; |
| 3670 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in target extension type" ) || |
| 3671 | parseStringConstant(Result&: TypeName)) |
| 3672 | return true; |
| 3673 | |
| 3674 | // Parse all of the integer and type parameters at the same time; the use of |
| 3675 | // SeenInt will allow us to catch cases where type parameters follow integer |
| 3676 | // parameters. |
| 3677 | SmallVector<Type *> TypeParams; |
| 3678 | SmallVector<unsigned> IntParams; |
| 3679 | bool SeenInt = false; |
| 3680 | while (Lex.getKind() == lltok::comma) { |
| 3681 | Lex.Lex(); // Eat the comma. |
| 3682 | |
| 3683 | if (Lex.getKind() == lltok::APSInt) { |
| 3684 | SeenInt = true; |
| 3685 | unsigned IntVal; |
| 3686 | if (parseUInt32(Val&: IntVal)) |
| 3687 | return true; |
| 3688 | IntParams.push_back(Elt: IntVal); |
| 3689 | } else if (SeenInt) { |
| 3690 | // The only other kind of parameter we support is type parameters, which |
| 3691 | // must precede the integer parameters. This is therefore an error. |
| 3692 | return tokError(Msg: "expected uint32 param" ); |
| 3693 | } else { |
| 3694 | Type *TypeParam; |
| 3695 | if (parseType(Result&: TypeParam, /*AllowVoid=*/true)) |
| 3696 | return true; |
| 3697 | TypeParams.push_back(Elt: TypeParam); |
| 3698 | } |
| 3699 | } |
| 3700 | |
| 3701 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in target extension type" )) |
| 3702 | return true; |
| 3703 | |
| 3704 | auto TTy = |
| 3705 | TargetExtType::getOrError(Context, Name: TypeName, Types: TypeParams, Ints: IntParams); |
| 3706 | if (auto E = TTy.takeError()) |
| 3707 | return tokError(Msg: toString(E: std::move(E))); |
| 3708 | |
| 3709 | Result = *TTy; |
| 3710 | return false; |
| 3711 | } |
| 3712 | |
| 3713 | //===----------------------------------------------------------------------===// |
| 3714 | // Function Semantic Analysis. |
| 3715 | //===----------------------------------------------------------------------===// |
| 3716 | |
| 3717 | LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, |
| 3718 | int functionNumber, |
| 3719 | ArrayRef<unsigned> UnnamedArgNums) |
| 3720 | : P(p), F(f), FunctionNumber(functionNumber) { |
| 3721 | |
| 3722 | // Insert unnamed arguments into the NumberedVals list. |
| 3723 | auto It = UnnamedArgNums.begin(); |
| 3724 | for (Argument &A : F.args()) { |
| 3725 | if (!A.hasName()) { |
| 3726 | unsigned ArgNum = *It++; |
| 3727 | NumberedVals.add(ID: ArgNum, V: &A); |
| 3728 | } |
| 3729 | } |
| 3730 | } |
| 3731 | |
| 3732 | LLParser::PerFunctionState::~PerFunctionState() { |
| 3733 | // If there were any forward referenced non-basicblock values, delete them. |
| 3734 | |
| 3735 | for (const auto &P : ForwardRefVals) { |
| 3736 | if (isa<BasicBlock>(Val: P.second.first)) |
| 3737 | continue; |
| 3738 | P.second.first->replaceAllUsesWith( |
| 3739 | V: PoisonValue::get(T: P.second.first->getType())); |
| 3740 | P.second.first->deleteValue(); |
| 3741 | } |
| 3742 | |
| 3743 | for (const auto &P : ForwardRefValIDs) { |
| 3744 | if (isa<BasicBlock>(Val: P.second.first)) |
| 3745 | continue; |
| 3746 | P.second.first->replaceAllUsesWith( |
| 3747 | V: PoisonValue::get(T: P.second.first->getType())); |
| 3748 | P.second.first->deleteValue(); |
| 3749 | } |
| 3750 | } |
| 3751 | |
| 3752 | bool LLParser::PerFunctionState::finishFunction() { |
| 3753 | if (!ForwardRefVals.empty()) |
| 3754 | return P.error(L: ForwardRefVals.begin()->second.second, |
| 3755 | Msg: "use of undefined value '%" + ForwardRefVals.begin()->first + |
| 3756 | "'" ); |
| 3757 | if (!ForwardRefValIDs.empty()) |
| 3758 | return P.error(L: ForwardRefValIDs.begin()->second.second, |
| 3759 | Msg: "use of undefined value '%" + |
| 3760 | Twine(ForwardRefValIDs.begin()->first) + "'" ); |
| 3761 | return false; |
| 3762 | } |
| 3763 | |
| 3764 | /// getVal - Get a value with the specified name or ID, creating a |
| 3765 | /// forward reference record if needed. This can return null if the value |
| 3766 | /// exists but does not have the right type. |
| 3767 | Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty, |
| 3768 | LocTy Loc) { |
| 3769 | // Look this name up in the normal function symbol table. |
| 3770 | Value *Val = F.getValueSymbolTable()->lookup(Name); |
| 3771 | |
| 3772 | // If this is a forward reference for the value, see if we already created a |
| 3773 | // forward ref record. |
| 3774 | if (!Val) { |
| 3775 | auto I = ForwardRefVals.find(x: Name); |
| 3776 | if (I != ForwardRefVals.end()) |
| 3777 | Val = I->second.first; |
| 3778 | } |
| 3779 | |
| 3780 | // If we have the value in the symbol table or fwd-ref table, return it. |
| 3781 | if (Val) |
| 3782 | return P.checkValidVariableType(Loc, Name: "%" + Name, Ty, Val); |
| 3783 | |
| 3784 | // Don't make placeholders with invalid type. |
| 3785 | if (!Ty->isFirstClassType()) { |
| 3786 | P.error(L: Loc, Msg: "invalid use of a non-first-class type" ); |
| 3787 | return nullptr; |
| 3788 | } |
| 3789 | |
| 3790 | // Otherwise, create a new forward reference for this value and remember it. |
| 3791 | Value *FwdVal; |
| 3792 | if (Ty->isLabelTy()) { |
| 3793 | FwdVal = BasicBlock::Create(Context&: F.getContext(), Name, Parent: &F); |
| 3794 | } else { |
| 3795 | FwdVal = new Argument(Ty, Name); |
| 3796 | } |
| 3797 | if (FwdVal->getName() != Name) { |
| 3798 | P.error(L: Loc, Msg: "name is too long which can result in name collisions, " |
| 3799 | "consider making the name shorter or " |
| 3800 | "increasing -non-global-value-max-name-size" ); |
| 3801 | return nullptr; |
| 3802 | } |
| 3803 | |
| 3804 | ForwardRefVals[Name] = std::make_pair(x&: FwdVal, y&: Loc); |
| 3805 | return FwdVal; |
| 3806 | } |
| 3807 | |
| 3808 | Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) { |
| 3809 | // Look this name up in the normal function symbol table. |
| 3810 | Value *Val = NumberedVals.get(ID); |
| 3811 | |
| 3812 | // If this is a forward reference for the value, see if we already created a |
| 3813 | // forward ref record. |
| 3814 | if (!Val) { |
| 3815 | auto I = ForwardRefValIDs.find(x: ID); |
| 3816 | if (I != ForwardRefValIDs.end()) |
| 3817 | Val = I->second.first; |
| 3818 | } |
| 3819 | |
| 3820 | // If we have the value in the symbol table or fwd-ref table, return it. |
| 3821 | if (Val) |
| 3822 | return P.checkValidVariableType(Loc, Name: "%" + Twine(ID), Ty, Val); |
| 3823 | |
| 3824 | if (!Ty->isFirstClassType()) { |
| 3825 | P.error(L: Loc, Msg: "invalid use of a non-first-class type" ); |
| 3826 | return nullptr; |
| 3827 | } |
| 3828 | |
| 3829 | // Otherwise, create a new forward reference for this value and remember it. |
| 3830 | Value *FwdVal; |
| 3831 | if (Ty->isLabelTy()) { |
| 3832 | FwdVal = BasicBlock::Create(Context&: F.getContext(), Name: "" , Parent: &F); |
| 3833 | } else { |
| 3834 | FwdVal = new Argument(Ty); |
| 3835 | } |
| 3836 | |
| 3837 | ForwardRefValIDs[ID] = std::make_pair(x&: FwdVal, y&: Loc); |
| 3838 | return FwdVal; |
| 3839 | } |
| 3840 | |
| 3841 | /// setInstName - After an instruction is parsed and inserted into its |
| 3842 | /// basic block, this installs its name. |
| 3843 | bool LLParser::PerFunctionState::setInstName(int NameID, |
| 3844 | const std::string &NameStr, |
| 3845 | LocTy NameLoc, Instruction *Inst) { |
| 3846 | // If this instruction has void type, it cannot have a name or ID specified. |
| 3847 | if (Inst->getType()->isVoidTy()) { |
| 3848 | if (NameID != -1 || !NameStr.empty()) |
| 3849 | return P.error(L: NameLoc, Msg: "instructions returning void cannot have a name" ); |
| 3850 | return false; |
| 3851 | } |
| 3852 | |
| 3853 | // If this was a numbered instruction, verify that the instruction is the |
| 3854 | // expected value and resolve any forward references. |
| 3855 | if (NameStr.empty()) { |
| 3856 | // If neither a name nor an ID was specified, just use the next ID. |
| 3857 | if (NameID == -1) |
| 3858 | NameID = NumberedVals.getNext(); |
| 3859 | |
| 3860 | if (P.checkValueID(Loc: NameLoc, Kind: "instruction" , Prefix: "%" , NextID: NumberedVals.getNext(), |
| 3861 | ID: NameID)) |
| 3862 | return true; |
| 3863 | |
| 3864 | auto FI = ForwardRefValIDs.find(x: NameID); |
| 3865 | if (FI != ForwardRefValIDs.end()) { |
| 3866 | Value *Sentinel = FI->second.first; |
| 3867 | if (Sentinel->getType() != Inst->getType()) |
| 3868 | return P.error(L: NameLoc, Msg: "instruction forward referenced with type '" + |
| 3869 | getTypeString(T: FI->second.first->getType()) + |
| 3870 | "'" ); |
| 3871 | |
| 3872 | Sentinel->replaceAllUsesWith(V: Inst); |
| 3873 | Sentinel->deleteValue(); |
| 3874 | ForwardRefValIDs.erase(position: FI); |
| 3875 | } |
| 3876 | |
| 3877 | NumberedVals.add(ID: NameID, V: Inst); |
| 3878 | return false; |
| 3879 | } |
| 3880 | |
| 3881 | // Otherwise, the instruction had a name. Resolve forward refs and set it. |
| 3882 | auto FI = ForwardRefVals.find(x: NameStr); |
| 3883 | if (FI != ForwardRefVals.end()) { |
| 3884 | Value *Sentinel = FI->second.first; |
| 3885 | if (Sentinel->getType() != Inst->getType()) |
| 3886 | return P.error(L: NameLoc, Msg: "instruction forward referenced with type '" + |
| 3887 | getTypeString(T: FI->second.first->getType()) + |
| 3888 | "'" ); |
| 3889 | |
| 3890 | Sentinel->replaceAllUsesWith(V: Inst); |
| 3891 | Sentinel->deleteValue(); |
| 3892 | ForwardRefVals.erase(position: FI); |
| 3893 | } |
| 3894 | |
| 3895 | // Set the name on the instruction. |
| 3896 | Inst->setName(NameStr); |
| 3897 | |
| 3898 | if (Inst->getName() != NameStr) |
| 3899 | return P.error(L: NameLoc, Msg: "multiple definition of local value named '" + |
| 3900 | NameStr + "'" ); |
| 3901 | return false; |
| 3902 | } |
| 3903 | |
| 3904 | /// getBB - Get a basic block with the specified name or ID, creating a |
| 3905 | /// forward reference record if needed. |
| 3906 | BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name, |
| 3907 | LocTy Loc) { |
| 3908 | return dyn_cast_or_null<BasicBlock>( |
| 3909 | Val: getVal(Name, Ty: Type::getLabelTy(C&: F.getContext()), Loc)); |
| 3910 | } |
| 3911 | |
| 3912 | BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) { |
| 3913 | return dyn_cast_or_null<BasicBlock>( |
| 3914 | Val: getVal(ID, Ty: Type::getLabelTy(C&: F.getContext()), Loc)); |
| 3915 | } |
| 3916 | |
| 3917 | /// defineBB - Define the specified basic block, which is either named or |
| 3918 | /// unnamed. If there is an error, this returns null otherwise it returns |
| 3919 | /// the block being defined. |
| 3920 | BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name, |
| 3921 | int NameID, LocTy Loc) { |
| 3922 | BasicBlock *BB; |
| 3923 | if (Name.empty()) { |
| 3924 | if (NameID != -1) { |
| 3925 | if (P.checkValueID(Loc, Kind: "label" , Prefix: "" , NextID: NumberedVals.getNext(), ID: NameID)) |
| 3926 | return nullptr; |
| 3927 | } else { |
| 3928 | NameID = NumberedVals.getNext(); |
| 3929 | } |
| 3930 | BB = getBB(ID: NameID, Loc); |
| 3931 | if (!BB) { |
| 3932 | P.error(L: Loc, Msg: "unable to create block numbered '" + Twine(NameID) + "'" ); |
| 3933 | return nullptr; |
| 3934 | } |
| 3935 | } else { |
| 3936 | BB = getBB(Name, Loc); |
| 3937 | if (!BB) { |
| 3938 | P.error(L: Loc, Msg: "unable to create block named '" + Name + "'" ); |
| 3939 | return nullptr; |
| 3940 | } |
| 3941 | } |
| 3942 | |
| 3943 | // Move the block to the end of the function. Forward ref'd blocks are |
| 3944 | // inserted wherever they happen to be referenced. |
| 3945 | F.splice(ToIt: F.end(), FromF: &F, FromIt: BB->getIterator()); |
| 3946 | |
| 3947 | // Remove the block from forward ref sets. |
| 3948 | if (Name.empty()) { |
| 3949 | ForwardRefValIDs.erase(x: NameID); |
| 3950 | NumberedVals.add(ID: NameID, V: BB); |
| 3951 | } else { |
| 3952 | // BB forward references are already in the function symbol table. |
| 3953 | ForwardRefVals.erase(x: Name); |
| 3954 | } |
| 3955 | |
| 3956 | return BB; |
| 3957 | } |
| 3958 | |
| 3959 | //===----------------------------------------------------------------------===// |
| 3960 | // Constants. |
| 3961 | //===----------------------------------------------------------------------===// |
| 3962 | |
| 3963 | /// parseValID - parse an abstract value that doesn't necessarily have a |
| 3964 | /// type implied. For example, if we parse "4" we don't know what integer type |
| 3965 | /// it has. The value will later be combined with its type and checked for |
| 3966 | /// basic correctness. PFS is used to convert function-local operands of |
| 3967 | /// metadata (since metadata operands are not just parsed here but also |
| 3968 | /// converted to values). PFS can be null when we are not parsing metadata |
| 3969 | /// values inside a function. |
| 3970 | bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) { |
| 3971 | ID.Loc = Lex.getLoc(); |
| 3972 | switch (Lex.getKind()) { |
| 3973 | default: |
| 3974 | return tokError(Msg: "expected value token" ); |
| 3975 | case lltok::GlobalID: // @42 |
| 3976 | ID.UIntVal = Lex.getUIntVal(); |
| 3977 | ID.Kind = ValID::t_GlobalID; |
| 3978 | break; |
| 3979 | case lltok::GlobalVar: // @foo |
| 3980 | ID.StrVal = Lex.getStrVal(); |
| 3981 | ID.Kind = ValID::t_GlobalName; |
| 3982 | break; |
| 3983 | case lltok::LocalVarID: // %42 |
| 3984 | ID.UIntVal = Lex.getUIntVal(); |
| 3985 | ID.Kind = ValID::t_LocalID; |
| 3986 | break; |
| 3987 | case lltok::LocalVar: // %foo |
| 3988 | ID.StrVal = Lex.getStrVal(); |
| 3989 | ID.Kind = ValID::t_LocalName; |
| 3990 | break; |
| 3991 | case lltok::APSInt: |
| 3992 | ID.APSIntVal = Lex.getAPSIntVal(); |
| 3993 | ID.Kind = ValID::t_APSInt; |
| 3994 | break; |
| 3995 | case lltok::APFloat: |
| 3996 | ID.APFloatVal = Lex.getAPFloatVal(); |
| 3997 | ID.Kind = ValID::t_APFloat; |
| 3998 | break; |
| 3999 | case lltok::kw_true: |
| 4000 | ID.ConstantVal = ConstantInt::getTrue(Context); |
| 4001 | ID.Kind = ValID::t_Constant; |
| 4002 | break; |
| 4003 | case lltok::kw_false: |
| 4004 | ID.ConstantVal = ConstantInt::getFalse(Context); |
| 4005 | ID.Kind = ValID::t_Constant; |
| 4006 | break; |
| 4007 | case lltok::kw_null: ID.Kind = ValID::t_Null; break; |
| 4008 | case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; |
| 4009 | case lltok::kw_poison: ID.Kind = ValID::t_Poison; break; |
| 4010 | case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; |
| 4011 | case lltok::kw_none: ID.Kind = ValID::t_None; break; |
| 4012 | |
| 4013 | case lltok::lbrace: { |
| 4014 | // ValID ::= '{' ConstVector '}' |
| 4015 | Lex.Lex(); |
| 4016 | SmallVector<Constant*, 16> Elts; |
| 4017 | if (parseGlobalValueVector(Elts) || |
| 4018 | parseToken(T: lltok::rbrace, ErrMsg: "expected end of struct constant" )) |
| 4019 | return true; |
| 4020 | |
| 4021 | ID.ConstantStructElts = std::make_unique<Constant *[]>(num: Elts.size()); |
| 4022 | ID.UIntVal = Elts.size(); |
| 4023 | memcpy(dest: ID.ConstantStructElts.get(), src: Elts.data(), |
| 4024 | n: Elts.size() * sizeof(Elts[0])); |
| 4025 | ID.Kind = ValID::t_ConstantStruct; |
| 4026 | return false; |
| 4027 | } |
| 4028 | case lltok::less: { |
| 4029 | // ValID ::= '<' ConstVector '>' --> Vector. |
| 4030 | // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. |
| 4031 | Lex.Lex(); |
| 4032 | bool isPackedStruct = EatIfPresent(T: lltok::lbrace); |
| 4033 | |
| 4034 | SmallVector<Constant*, 16> Elts; |
| 4035 | LocTy FirstEltLoc = Lex.getLoc(); |
| 4036 | if (parseGlobalValueVector(Elts) || |
| 4037 | (isPackedStruct && |
| 4038 | parseToken(T: lltok::rbrace, ErrMsg: "expected end of packed struct" )) || |
| 4039 | parseToken(T: lltok::greater, ErrMsg: "expected end of constant" )) |
| 4040 | return true; |
| 4041 | |
| 4042 | if (isPackedStruct) { |
| 4043 | ID.ConstantStructElts = std::make_unique<Constant *[]>(num: Elts.size()); |
| 4044 | memcpy(dest: ID.ConstantStructElts.get(), src: Elts.data(), |
| 4045 | n: Elts.size() * sizeof(Elts[0])); |
| 4046 | ID.UIntVal = Elts.size(); |
| 4047 | ID.Kind = ValID::t_PackedConstantStruct; |
| 4048 | return false; |
| 4049 | } |
| 4050 | |
| 4051 | if (Elts.empty()) |
| 4052 | return error(L: ID.Loc, Msg: "constant vector must not be empty" ); |
| 4053 | |
| 4054 | if (!Elts[0]->getType()->isIntegerTy() && |
| 4055 | !Elts[0]->getType()->isFloatingPointTy() && |
| 4056 | !Elts[0]->getType()->isPointerTy()) |
| 4057 | return error( |
| 4058 | L: FirstEltLoc, |
| 4059 | Msg: "vector elements must have integer, pointer or floating point type" ); |
| 4060 | |
| 4061 | // Verify that all the vector elements have the same type. |
| 4062 | for (unsigned i = 1, e = Elts.size(); i != e; ++i) |
| 4063 | if (Elts[i]->getType() != Elts[0]->getType()) |
| 4064 | return error(L: FirstEltLoc, Msg: "vector element #" + Twine(i) + |
| 4065 | " is not of type '" + |
| 4066 | getTypeString(T: Elts[0]->getType())); |
| 4067 | |
| 4068 | ID.ConstantVal = ConstantVector::get(V: Elts); |
| 4069 | ID.Kind = ValID::t_Constant; |
| 4070 | return false; |
| 4071 | } |
| 4072 | case lltok::lsquare: { // Array Constant |
| 4073 | Lex.Lex(); |
| 4074 | SmallVector<Constant*, 16> Elts; |
| 4075 | LocTy FirstEltLoc = Lex.getLoc(); |
| 4076 | if (parseGlobalValueVector(Elts) || |
| 4077 | parseToken(T: lltok::rsquare, ErrMsg: "expected end of array constant" )) |
| 4078 | return true; |
| 4079 | |
| 4080 | // Handle empty element. |
| 4081 | if (Elts.empty()) { |
| 4082 | // Use undef instead of an array because it's inconvenient to determine |
| 4083 | // the element type at this point, there being no elements to examine. |
| 4084 | ID.Kind = ValID::t_EmptyArray; |
| 4085 | return false; |
| 4086 | } |
| 4087 | |
| 4088 | if (!Elts[0]->getType()->isFirstClassType()) |
| 4089 | return error(L: FirstEltLoc, Msg: "invalid array element type: " + |
| 4090 | getTypeString(T: Elts[0]->getType())); |
| 4091 | |
| 4092 | ArrayType *ATy = ArrayType::get(ElementType: Elts[0]->getType(), NumElements: Elts.size()); |
| 4093 | |
| 4094 | // Verify all elements are correct type! |
| 4095 | for (unsigned i = 0, e = Elts.size(); i != e; ++i) { |
| 4096 | if (Elts[i]->getType() != Elts[0]->getType()) |
| 4097 | return error(L: FirstEltLoc, Msg: "array element #" + Twine(i) + |
| 4098 | " is not of type '" + |
| 4099 | getTypeString(T: Elts[0]->getType())); |
| 4100 | } |
| 4101 | |
| 4102 | ID.ConstantVal = ConstantArray::get(T: ATy, V: Elts); |
| 4103 | ID.Kind = ValID::t_Constant; |
| 4104 | return false; |
| 4105 | } |
| 4106 | case lltok::kw_c: // c "foo" |
| 4107 | Lex.Lex(); |
| 4108 | ID.ConstantVal = ConstantDataArray::getString(Context, Initializer: Lex.getStrVal(), |
| 4109 | AddNull: false); |
| 4110 | if (parseToken(T: lltok::StringConstant, ErrMsg: "expected string" )) |
| 4111 | return true; |
| 4112 | ID.Kind = ValID::t_Constant; |
| 4113 | return false; |
| 4114 | |
| 4115 | case lltok::kw_asm: { |
| 4116 | // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' |
| 4117 | // STRINGCONSTANT |
| 4118 | bool HasSideEffect, AlignStack, AsmDialect, CanThrow; |
| 4119 | Lex.Lex(); |
| 4120 | if (parseOptionalToken(T: lltok::kw_sideeffect, Present&: HasSideEffect) || |
| 4121 | parseOptionalToken(T: lltok::kw_alignstack, Present&: AlignStack) || |
| 4122 | parseOptionalToken(T: lltok::kw_inteldialect, Present&: AsmDialect) || |
| 4123 | parseOptionalToken(T: lltok::kw_unwind, Present&: CanThrow) || |
| 4124 | parseStringConstant(Result&: ID.StrVal) || |
| 4125 | parseToken(T: lltok::comma, ErrMsg: "expected comma in inline asm expression" ) || |
| 4126 | parseToken(T: lltok::StringConstant, ErrMsg: "expected constraint string" )) |
| 4127 | return true; |
| 4128 | ID.StrVal2 = Lex.getStrVal(); |
| 4129 | ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) | |
| 4130 | (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3); |
| 4131 | ID.Kind = ValID::t_InlineAsm; |
| 4132 | return false; |
| 4133 | } |
| 4134 | |
| 4135 | case lltok::kw_blockaddress: { |
| 4136 | // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' |
| 4137 | Lex.Lex(); |
| 4138 | |
| 4139 | ValID Fn, Label; |
| 4140 | |
| 4141 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in block address expression" ) || |
| 4142 | parseValID(ID&: Fn, PFS) || |
| 4143 | parseToken(T: lltok::comma, |
| 4144 | ErrMsg: "expected comma in block address expression" ) || |
| 4145 | parseValID(ID&: Label, PFS) || |
| 4146 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' in block address expression" )) |
| 4147 | return true; |
| 4148 | |
| 4149 | if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) |
| 4150 | return error(L: Fn.Loc, Msg: "expected function name in blockaddress" ); |
| 4151 | if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) |
| 4152 | return error(L: Label.Loc, Msg: "expected basic block name in blockaddress" ); |
| 4153 | |
| 4154 | // Try to find the function (but skip it if it's forward-referenced). |
| 4155 | GlobalValue *GV = nullptr; |
| 4156 | if (Fn.Kind == ValID::t_GlobalID) { |
| 4157 | GV = NumberedVals.get(ID: Fn.UIntVal); |
| 4158 | } else if (!ForwardRefVals.count(x: Fn.StrVal)) { |
| 4159 | GV = M->getNamedValue(Name: Fn.StrVal); |
| 4160 | } |
| 4161 | Function *F = nullptr; |
| 4162 | if (GV) { |
| 4163 | // Confirm that it's actually a function with a definition. |
| 4164 | if (!isa<Function>(Val: GV)) |
| 4165 | return error(L: Fn.Loc, Msg: "expected function name in blockaddress" ); |
| 4166 | F = cast<Function>(Val: GV); |
| 4167 | if (F->isDeclaration()) |
| 4168 | return error(L: Fn.Loc, Msg: "cannot take blockaddress inside a declaration" ); |
| 4169 | } |
| 4170 | |
| 4171 | if (!F) { |
| 4172 | // Make a global variable as a placeholder for this reference. |
| 4173 | GlobalValue *&FwdRef = |
| 4174 | ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)]; |
| 4175 | if (!FwdRef) { |
| 4176 | unsigned FwdDeclAS; |
| 4177 | if (ExpectedTy) { |
| 4178 | // If we know the type that the blockaddress is being assigned to, |
| 4179 | // we can use the address space of that type. |
| 4180 | if (!ExpectedTy->isPointerTy()) |
| 4181 | return error(L: ID.Loc, |
| 4182 | Msg: "type of blockaddress must be a pointer and not '" + |
| 4183 | getTypeString(T: ExpectedTy) + "'" ); |
| 4184 | FwdDeclAS = ExpectedTy->getPointerAddressSpace(); |
| 4185 | } else if (PFS) { |
| 4186 | // Otherwise, we default the address space of the current function. |
| 4187 | FwdDeclAS = PFS->getFunction().getAddressSpace(); |
| 4188 | } else { |
| 4189 | llvm_unreachable("Unknown address space for blockaddress" ); |
| 4190 | } |
| 4191 | FwdRef = new GlobalVariable( |
| 4192 | *M, Type::getInt8Ty(C&: Context), false, GlobalValue::InternalLinkage, |
| 4193 | nullptr, "" , nullptr, GlobalValue::NotThreadLocal, FwdDeclAS); |
| 4194 | } |
| 4195 | |
| 4196 | ID.ConstantVal = FwdRef; |
| 4197 | ID.Kind = ValID::t_Constant; |
| 4198 | return false; |
| 4199 | } |
| 4200 | |
| 4201 | // We found the function; now find the basic block. Don't use PFS, since we |
| 4202 | // might be inside a constant expression. |
| 4203 | BasicBlock *BB; |
| 4204 | if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { |
| 4205 | if (Label.Kind == ValID::t_LocalID) |
| 4206 | BB = BlockAddressPFS->getBB(ID: Label.UIntVal, Loc: Label.Loc); |
| 4207 | else |
| 4208 | BB = BlockAddressPFS->getBB(Name: Label.StrVal, Loc: Label.Loc); |
| 4209 | if (!BB) |
| 4210 | return error(L: Label.Loc, Msg: "referenced value is not a basic block" ); |
| 4211 | } else { |
| 4212 | if (Label.Kind == ValID::t_LocalID) |
| 4213 | return error(L: Label.Loc, Msg: "cannot take address of numeric label after " |
| 4214 | "the function is defined" ); |
| 4215 | BB = dyn_cast_or_null<BasicBlock>( |
| 4216 | Val: F->getValueSymbolTable()->lookup(Name: Label.StrVal)); |
| 4217 | if (!BB) |
| 4218 | return error(L: Label.Loc, Msg: "referenced value is not a basic block" ); |
| 4219 | } |
| 4220 | |
| 4221 | ID.ConstantVal = BlockAddress::get(F, BB); |
| 4222 | ID.Kind = ValID::t_Constant; |
| 4223 | return false; |
| 4224 | } |
| 4225 | |
| 4226 | case lltok::kw_dso_local_equivalent: { |
| 4227 | // ValID ::= 'dso_local_equivalent' @foo |
| 4228 | Lex.Lex(); |
| 4229 | |
| 4230 | ValID Fn; |
| 4231 | |
| 4232 | if (parseValID(ID&: Fn, PFS)) |
| 4233 | return true; |
| 4234 | |
| 4235 | if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) |
| 4236 | return error(L: Fn.Loc, |
| 4237 | Msg: "expected global value name in dso_local_equivalent" ); |
| 4238 | |
| 4239 | // Try to find the function (but skip it if it's forward-referenced). |
| 4240 | GlobalValue *GV = nullptr; |
| 4241 | if (Fn.Kind == ValID::t_GlobalID) { |
| 4242 | GV = NumberedVals.get(ID: Fn.UIntVal); |
| 4243 | } else if (!ForwardRefVals.count(x: Fn.StrVal)) { |
| 4244 | GV = M->getNamedValue(Name: Fn.StrVal); |
| 4245 | } |
| 4246 | |
| 4247 | if (!GV) { |
| 4248 | // Make a placeholder global variable as a placeholder for this reference. |
| 4249 | auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID) |
| 4250 | ? ForwardRefDSOLocalEquivalentIDs |
| 4251 | : ForwardRefDSOLocalEquivalentNames; |
| 4252 | GlobalValue *&FwdRef = FwdRefMap[Fn]; |
| 4253 | if (!FwdRef) { |
| 4254 | FwdRef = new GlobalVariable(*M, Type::getInt8Ty(C&: Context), false, |
| 4255 | GlobalValue::InternalLinkage, nullptr, "" , |
| 4256 | nullptr, GlobalValue::NotThreadLocal); |
| 4257 | } |
| 4258 | |
| 4259 | ID.ConstantVal = FwdRef; |
| 4260 | ID.Kind = ValID::t_Constant; |
| 4261 | return false; |
| 4262 | } |
| 4263 | |
| 4264 | if (!GV->getValueType()->isFunctionTy()) |
| 4265 | return error(L: Fn.Loc, Msg: "expected a function, alias to function, or ifunc " |
| 4266 | "in dso_local_equivalent" ); |
| 4267 | |
| 4268 | ID.ConstantVal = DSOLocalEquivalent::get(GV); |
| 4269 | ID.Kind = ValID::t_Constant; |
| 4270 | return false; |
| 4271 | } |
| 4272 | |
| 4273 | case lltok::kw_no_cfi: { |
| 4274 | // ValID ::= 'no_cfi' @foo |
| 4275 | Lex.Lex(); |
| 4276 | |
| 4277 | if (parseValID(ID, PFS)) |
| 4278 | return true; |
| 4279 | |
| 4280 | if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName) |
| 4281 | return error(L: ID.Loc, Msg: "expected global value name in no_cfi" ); |
| 4282 | |
| 4283 | ID.NoCFI = true; |
| 4284 | return false; |
| 4285 | } |
| 4286 | case lltok::kw_ptrauth: { |
| 4287 | // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key> |
| 4288 | // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)? |
| 4289 | // )? )? ')' |
| 4290 | Lex.Lex(); |
| 4291 | |
| 4292 | Constant *Ptr, *Key; |
| 4293 | Constant *Disc = nullptr, *AddrDisc = nullptr, |
| 4294 | *DeactivationSymbol = nullptr; |
| 4295 | |
| 4296 | if (parseToken(T: lltok::lparen, |
| 4297 | ErrMsg: "expected '(' in constant ptrauth expression" ) || |
| 4298 | parseGlobalTypeAndValue(V&: Ptr) || |
| 4299 | parseToken(T: lltok::comma, |
| 4300 | ErrMsg: "expected comma in constant ptrauth expression" ) || |
| 4301 | parseGlobalTypeAndValue(V&: Key)) |
| 4302 | return true; |
| 4303 | // If present, parse the optional disc/addrdisc/ds. |
| 4304 | if (EatIfPresent(T: lltok::comma) && parseGlobalTypeAndValue(V&: Disc)) |
| 4305 | return true; |
| 4306 | if (EatIfPresent(T: lltok::comma) && parseGlobalTypeAndValue(V&: AddrDisc)) |
| 4307 | return true; |
| 4308 | if (EatIfPresent(T: lltok::comma) && |
| 4309 | parseGlobalTypeAndValue(V&: DeactivationSymbol)) |
| 4310 | return true; |
| 4311 | if (parseToken(T: lltok::rparen, |
| 4312 | ErrMsg: "expected ')' in constant ptrauth expression" )) |
| 4313 | return true; |
| 4314 | |
| 4315 | if (!Ptr->getType()->isPointerTy()) |
| 4316 | return error(L: ID.Loc, Msg: "constant ptrauth base pointer must be a pointer" ); |
| 4317 | |
| 4318 | auto *KeyC = dyn_cast<ConstantInt>(Val: Key); |
| 4319 | if (!KeyC || KeyC->getBitWidth() != 32) |
| 4320 | return error(L: ID.Loc, Msg: "constant ptrauth key must be i32 constant" ); |
| 4321 | |
| 4322 | ConstantInt *DiscC = nullptr; |
| 4323 | if (Disc) { |
| 4324 | DiscC = dyn_cast<ConstantInt>(Val: Disc); |
| 4325 | if (!DiscC || DiscC->getBitWidth() != 64) |
| 4326 | return error( |
| 4327 | L: ID.Loc, |
| 4328 | Msg: "constant ptrauth integer discriminator must be i64 constant" ); |
| 4329 | } else { |
| 4330 | DiscC = ConstantInt::get(Ty: Type::getInt64Ty(C&: Context), V: 0); |
| 4331 | } |
| 4332 | |
| 4333 | if (AddrDisc) { |
| 4334 | if (!AddrDisc->getType()->isPointerTy()) |
| 4335 | return error( |
| 4336 | L: ID.Loc, Msg: "constant ptrauth address discriminator must be a pointer" ); |
| 4337 | } else { |
| 4338 | AddrDisc = ConstantPointerNull::get(T: PointerType::get(C&: Context, AddressSpace: 0)); |
| 4339 | } |
| 4340 | |
| 4341 | if (!DeactivationSymbol) |
| 4342 | DeactivationSymbol = |
| 4343 | ConstantPointerNull::get(T: PointerType::get(C&: Context, AddressSpace: 0)); |
| 4344 | if (!DeactivationSymbol->getType()->isPointerTy()) |
| 4345 | return error(L: ID.Loc, |
| 4346 | Msg: "constant ptrauth deactivation symbol must be a pointer" ); |
| 4347 | |
| 4348 | ID.ConstantVal = |
| 4349 | ConstantPtrAuth::get(Ptr, Key: KeyC, Disc: DiscC, AddrDisc, DeactivationSymbol); |
| 4350 | ID.Kind = ValID::t_Constant; |
| 4351 | return false; |
| 4352 | } |
| 4353 | |
| 4354 | case lltok::kw_trunc: |
| 4355 | case lltok::kw_bitcast: |
| 4356 | case lltok::kw_addrspacecast: |
| 4357 | case lltok::kw_inttoptr: |
| 4358 | case lltok::kw_ptrtoaddr: |
| 4359 | case lltok::kw_ptrtoint: { |
| 4360 | unsigned Opc = Lex.getUIntVal(); |
| 4361 | Type *DestTy = nullptr; |
| 4362 | Constant *SrcVal; |
| 4363 | Lex.Lex(); |
| 4364 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' after constantexpr cast" ) || |
| 4365 | parseGlobalTypeAndValue(V&: SrcVal) || |
| 4366 | parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in constantexpr cast" ) || |
| 4367 | parseType(Result&: DestTy) || |
| 4368 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of constantexpr cast" )) |
| 4369 | return true; |
| 4370 | if (!CastInst::castIsValid(op: (Instruction::CastOps)Opc, S: SrcVal, DstTy: DestTy)) |
| 4371 | return error(L: ID.Loc, Msg: "invalid cast opcode for cast from '" + |
| 4372 | getTypeString(T: SrcVal->getType()) + "' to '" + |
| 4373 | getTypeString(T: DestTy) + "'" ); |
| 4374 | ID.ConstantVal = ConstantExpr::getCast(ops: (Instruction::CastOps)Opc, |
| 4375 | C: SrcVal, Ty: DestTy); |
| 4376 | ID.Kind = ValID::t_Constant; |
| 4377 | return false; |
| 4378 | } |
| 4379 | case lltok::kw_extractvalue: |
| 4380 | return error(L: ID.Loc, Msg: "extractvalue constexprs are no longer supported" ); |
| 4381 | case lltok::kw_insertvalue: |
| 4382 | return error(L: ID.Loc, Msg: "insertvalue constexprs are no longer supported" ); |
| 4383 | case lltok::kw_udiv: |
| 4384 | return error(L: ID.Loc, Msg: "udiv constexprs are no longer supported" ); |
| 4385 | case lltok::kw_sdiv: |
| 4386 | return error(L: ID.Loc, Msg: "sdiv constexprs are no longer supported" ); |
| 4387 | case lltok::kw_urem: |
| 4388 | return error(L: ID.Loc, Msg: "urem constexprs are no longer supported" ); |
| 4389 | case lltok::kw_srem: |
| 4390 | return error(L: ID.Loc, Msg: "srem constexprs are no longer supported" ); |
| 4391 | case lltok::kw_fadd: |
| 4392 | return error(L: ID.Loc, Msg: "fadd constexprs are no longer supported" ); |
| 4393 | case lltok::kw_fsub: |
| 4394 | return error(L: ID.Loc, Msg: "fsub constexprs are no longer supported" ); |
| 4395 | case lltok::kw_fmul: |
| 4396 | return error(L: ID.Loc, Msg: "fmul constexprs are no longer supported" ); |
| 4397 | case lltok::kw_fdiv: |
| 4398 | return error(L: ID.Loc, Msg: "fdiv constexprs are no longer supported" ); |
| 4399 | case lltok::kw_frem: |
| 4400 | return error(L: ID.Loc, Msg: "frem constexprs are no longer supported" ); |
| 4401 | case lltok::kw_and: |
| 4402 | return error(L: ID.Loc, Msg: "and constexprs are no longer supported" ); |
| 4403 | case lltok::kw_or: |
| 4404 | return error(L: ID.Loc, Msg: "or constexprs are no longer supported" ); |
| 4405 | case lltok::kw_lshr: |
| 4406 | return error(L: ID.Loc, Msg: "lshr constexprs are no longer supported" ); |
| 4407 | case lltok::kw_ashr: |
| 4408 | return error(L: ID.Loc, Msg: "ashr constexprs are no longer supported" ); |
| 4409 | case lltok::kw_shl: |
| 4410 | return error(L: ID.Loc, Msg: "shl constexprs are no longer supported" ); |
| 4411 | case lltok::kw_mul: |
| 4412 | return error(L: ID.Loc, Msg: "mul constexprs are no longer supported" ); |
| 4413 | case lltok::kw_fneg: |
| 4414 | return error(L: ID.Loc, Msg: "fneg constexprs are no longer supported" ); |
| 4415 | case lltok::kw_select: |
| 4416 | return error(L: ID.Loc, Msg: "select constexprs are no longer supported" ); |
| 4417 | case lltok::kw_zext: |
| 4418 | return error(L: ID.Loc, Msg: "zext constexprs are no longer supported" ); |
| 4419 | case lltok::kw_sext: |
| 4420 | return error(L: ID.Loc, Msg: "sext constexprs are no longer supported" ); |
| 4421 | case lltok::kw_fptrunc: |
| 4422 | return error(L: ID.Loc, Msg: "fptrunc constexprs are no longer supported" ); |
| 4423 | case lltok::kw_fpext: |
| 4424 | return error(L: ID.Loc, Msg: "fpext constexprs are no longer supported" ); |
| 4425 | case lltok::kw_uitofp: |
| 4426 | return error(L: ID.Loc, Msg: "uitofp constexprs are no longer supported" ); |
| 4427 | case lltok::kw_sitofp: |
| 4428 | return error(L: ID.Loc, Msg: "sitofp constexprs are no longer supported" ); |
| 4429 | case lltok::kw_fptoui: |
| 4430 | return error(L: ID.Loc, Msg: "fptoui constexprs are no longer supported" ); |
| 4431 | case lltok::kw_fptosi: |
| 4432 | return error(L: ID.Loc, Msg: "fptosi constexprs are no longer supported" ); |
| 4433 | case lltok::kw_icmp: |
| 4434 | return error(L: ID.Loc, Msg: "icmp constexprs are no longer supported" ); |
| 4435 | case lltok::kw_fcmp: |
| 4436 | return error(L: ID.Loc, Msg: "fcmp constexprs are no longer supported" ); |
| 4437 | |
| 4438 | // Binary Operators. |
| 4439 | case lltok::kw_add: |
| 4440 | case lltok::kw_sub: |
| 4441 | case lltok::kw_xor: { |
| 4442 | bool NUW = false; |
| 4443 | bool NSW = false; |
| 4444 | unsigned Opc = Lex.getUIntVal(); |
| 4445 | Constant *Val0, *Val1; |
| 4446 | Lex.Lex(); |
| 4447 | if (Opc == Instruction::Add || Opc == Instruction::Sub || |
| 4448 | Opc == Instruction::Mul) { |
| 4449 | if (EatIfPresent(T: lltok::kw_nuw)) |
| 4450 | NUW = true; |
| 4451 | if (EatIfPresent(T: lltok::kw_nsw)) { |
| 4452 | NSW = true; |
| 4453 | if (EatIfPresent(T: lltok::kw_nuw)) |
| 4454 | NUW = true; |
| 4455 | } |
| 4456 | } |
| 4457 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in binary constantexpr" ) || |
| 4458 | parseGlobalTypeAndValue(V&: Val0) || |
| 4459 | parseToken(T: lltok::comma, ErrMsg: "expected comma in binary constantexpr" ) || |
| 4460 | parseGlobalTypeAndValue(V&: Val1) || |
| 4461 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' in binary constantexpr" )) |
| 4462 | return true; |
| 4463 | if (Val0->getType() != Val1->getType()) |
| 4464 | return error(L: ID.Loc, Msg: "operands of constexpr must have same type" ); |
| 4465 | // Check that the type is valid for the operator. |
| 4466 | if (!Val0->getType()->isIntOrIntVectorTy()) |
| 4467 | return error(L: ID.Loc, |
| 4468 | Msg: "constexpr requires integer or integer vector operands" ); |
| 4469 | unsigned Flags = 0; |
| 4470 | if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; |
| 4471 | if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; |
| 4472 | ID.ConstantVal = ConstantExpr::get(Opcode: Opc, C1: Val0, C2: Val1, Flags); |
| 4473 | ID.Kind = ValID::t_Constant; |
| 4474 | return false; |
| 4475 | } |
| 4476 | |
| 4477 | case lltok::kw_splat: { |
| 4478 | Lex.Lex(); |
| 4479 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' after vector splat" )) |
| 4480 | return true; |
| 4481 | Constant *C; |
| 4482 | if (parseGlobalTypeAndValue(V&: C)) |
| 4483 | return true; |
| 4484 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of vector splat" )) |
| 4485 | return true; |
| 4486 | |
| 4487 | ID.ConstantVal = C; |
| 4488 | ID.Kind = ValID::t_ConstantSplat; |
| 4489 | return false; |
| 4490 | } |
| 4491 | |
| 4492 | case lltok::kw_getelementptr: |
| 4493 | case lltok::kw_shufflevector: |
| 4494 | case lltok::kw_insertelement: |
| 4495 | case lltok::kw_extractelement: { |
| 4496 | unsigned Opc = Lex.getUIntVal(); |
| 4497 | SmallVector<Constant*, 16> Elts; |
| 4498 | GEPNoWrapFlags NW; |
| 4499 | bool HasInRange = false; |
| 4500 | APSInt InRangeStart; |
| 4501 | APSInt InRangeEnd; |
| 4502 | Type *Ty; |
| 4503 | Lex.Lex(); |
| 4504 | |
| 4505 | if (Opc == Instruction::GetElementPtr) { |
| 4506 | while (true) { |
| 4507 | if (EatIfPresent(T: lltok::kw_inbounds)) |
| 4508 | NW |= GEPNoWrapFlags::inBounds(); |
| 4509 | else if (EatIfPresent(T: lltok::kw_nusw)) |
| 4510 | NW |= GEPNoWrapFlags::noUnsignedSignedWrap(); |
| 4511 | else if (EatIfPresent(T: lltok::kw_nuw)) |
| 4512 | NW |= GEPNoWrapFlags::noUnsignedWrap(); |
| 4513 | else |
| 4514 | break; |
| 4515 | } |
| 4516 | |
| 4517 | if (EatIfPresent(T: lltok::kw_inrange)) { |
| 4518 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '('" )) |
| 4519 | return true; |
| 4520 | if (Lex.getKind() != lltok::APSInt) |
| 4521 | return tokError(Msg: "expected integer" ); |
| 4522 | InRangeStart = Lex.getAPSIntVal(); |
| 4523 | Lex.Lex(); |
| 4524 | if (parseToken(T: lltok::comma, ErrMsg: "expected ','" )) |
| 4525 | return true; |
| 4526 | if (Lex.getKind() != lltok::APSInt) |
| 4527 | return tokError(Msg: "expected integer" ); |
| 4528 | InRangeEnd = Lex.getAPSIntVal(); |
| 4529 | Lex.Lex(); |
| 4530 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'" )) |
| 4531 | return true; |
| 4532 | HasInRange = true; |
| 4533 | } |
| 4534 | } |
| 4535 | |
| 4536 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in constantexpr" )) |
| 4537 | return true; |
| 4538 | |
| 4539 | if (Opc == Instruction::GetElementPtr) { |
| 4540 | if (parseType(Result&: Ty) || |
| 4541 | parseToken(T: lltok::comma, ErrMsg: "expected comma after getelementptr's type" )) |
| 4542 | return true; |
| 4543 | } |
| 4544 | |
| 4545 | if (parseGlobalValueVector(Elts) || |
| 4546 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' in constantexpr" )) |
| 4547 | return true; |
| 4548 | |
| 4549 | if (Opc == Instruction::GetElementPtr) { |
| 4550 | if (Elts.size() == 0 || |
| 4551 | !Elts[0]->getType()->isPtrOrPtrVectorTy()) |
| 4552 | return error(L: ID.Loc, Msg: "base of getelementptr must be a pointer" ); |
| 4553 | |
| 4554 | Type *BaseType = Elts[0]->getType(); |
| 4555 | std::optional<ConstantRange> InRange; |
| 4556 | if (HasInRange) { |
| 4557 | unsigned IndexWidth = |
| 4558 | M->getDataLayout().getIndexTypeSizeInBits(Ty: BaseType); |
| 4559 | InRangeStart = InRangeStart.extOrTrunc(width: IndexWidth); |
| 4560 | InRangeEnd = InRangeEnd.extOrTrunc(width: IndexWidth); |
| 4561 | if (InRangeStart.sge(RHS: InRangeEnd)) |
| 4562 | return error(L: ID.Loc, Msg: "expected end to be larger than start" ); |
| 4563 | InRange = ConstantRange::getNonEmpty(Lower: InRangeStart, Upper: InRangeEnd); |
| 4564 | } |
| 4565 | |
| 4566 | unsigned GEPWidth = |
| 4567 | BaseType->isVectorTy() |
| 4568 | ? cast<FixedVectorType>(Val: BaseType)->getNumElements() |
| 4569 | : 0; |
| 4570 | |
| 4571 | ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); |
| 4572 | for (Constant *Val : Indices) { |
| 4573 | Type *ValTy = Val->getType(); |
| 4574 | if (!ValTy->isIntOrIntVectorTy()) |
| 4575 | return error(L: ID.Loc, Msg: "getelementptr index must be an integer" ); |
| 4576 | if (auto *ValVTy = dyn_cast<VectorType>(Val: ValTy)) { |
| 4577 | unsigned ValNumEl = cast<FixedVectorType>(Val: ValVTy)->getNumElements(); |
| 4578 | if (GEPWidth && (ValNumEl != GEPWidth)) |
| 4579 | return error( |
| 4580 | L: ID.Loc, |
| 4581 | Msg: "getelementptr vector index has a wrong number of elements" ); |
| 4582 | // GEPWidth may have been unknown because the base is a scalar, |
| 4583 | // but it is known now. |
| 4584 | GEPWidth = ValNumEl; |
| 4585 | } |
| 4586 | } |
| 4587 | |
| 4588 | SmallPtrSet<Type*, 4> Visited; |
| 4589 | if (!Indices.empty() && !Ty->isSized(Visited: &Visited)) |
| 4590 | return error(L: ID.Loc, Msg: "base element of getelementptr must be sized" ); |
| 4591 | |
| 4592 | if (!ConstantExpr::isSupportedGetElementPtr(SrcElemTy: Ty)) |
| 4593 | return error(L: ID.Loc, Msg: "invalid base element for constant getelementptr" ); |
| 4594 | |
| 4595 | if (!GetElementPtrInst::getIndexedType(Ty, IdxList: Indices)) |
| 4596 | return error(L: ID.Loc, Msg: "invalid getelementptr indices" ); |
| 4597 | |
| 4598 | ID.ConstantVal = |
| 4599 | ConstantExpr::getGetElementPtr(Ty, C: Elts[0], IdxList: Indices, NW, InRange); |
| 4600 | } else if (Opc == Instruction::ShuffleVector) { |
| 4601 | if (Elts.size() != 3) |
| 4602 | return error(L: ID.Loc, Msg: "expected three operands to shufflevector" ); |
| 4603 | if (!ShuffleVectorInst::isValidOperands(V1: Elts[0], V2: Elts[1], Mask: Elts[2])) |
| 4604 | return error(L: ID.Loc, Msg: "invalid operands to shufflevector" ); |
| 4605 | SmallVector<int, 16> Mask; |
| 4606 | ShuffleVectorInst::getShuffleMask(Mask: cast<Constant>(Val: Elts[2]), Result&: Mask); |
| 4607 | ID.ConstantVal = ConstantExpr::getShuffleVector(V1: Elts[0], V2: Elts[1], Mask); |
| 4608 | } else if (Opc == Instruction::ExtractElement) { |
| 4609 | if (Elts.size() != 2) |
| 4610 | return error(L: ID.Loc, Msg: "expected two operands to extractelement" ); |
| 4611 | if (!ExtractElementInst::isValidOperands(Vec: Elts[0], Idx: Elts[1])) |
| 4612 | return error(L: ID.Loc, Msg: "invalid extractelement operands" ); |
| 4613 | ID.ConstantVal = ConstantExpr::getExtractElement(Vec: Elts[0], Idx: Elts[1]); |
| 4614 | } else { |
| 4615 | assert(Opc == Instruction::InsertElement && "Unknown opcode" ); |
| 4616 | if (Elts.size() != 3) |
| 4617 | return error(L: ID.Loc, Msg: "expected three operands to insertelement" ); |
| 4618 | if (!InsertElementInst::isValidOperands(Vec: Elts[0], NewElt: Elts[1], Idx: Elts[2])) |
| 4619 | return error(L: ID.Loc, Msg: "invalid insertelement operands" ); |
| 4620 | ID.ConstantVal = |
| 4621 | ConstantExpr::getInsertElement(Vec: Elts[0], Elt: Elts[1],Idx: Elts[2]); |
| 4622 | } |
| 4623 | |
| 4624 | ID.Kind = ValID::t_Constant; |
| 4625 | return false; |
| 4626 | } |
| 4627 | } |
| 4628 | |
| 4629 | Lex.Lex(); |
| 4630 | return false; |
| 4631 | } |
| 4632 | |
| 4633 | /// parseGlobalValue - parse a global value with the specified type. |
| 4634 | bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) { |
| 4635 | C = nullptr; |
| 4636 | ValID ID; |
| 4637 | Value *V = nullptr; |
| 4638 | bool Parsed = parseValID(ID, /*PFS=*/nullptr, ExpectedTy: Ty) || |
| 4639 | convertValIDToValue(Ty, ID, V, PFS: nullptr); |
| 4640 | if (V && !(C = dyn_cast<Constant>(Val: V))) |
| 4641 | return error(L: ID.Loc, Msg: "global values must be constants" ); |
| 4642 | return Parsed; |
| 4643 | } |
| 4644 | |
| 4645 | bool LLParser::parseGlobalTypeAndValue(Constant *&V) { |
| 4646 | Type *Ty = nullptr; |
| 4647 | return parseType(Result&: Ty) || parseGlobalValue(Ty, C&: V); |
| 4648 | } |
| 4649 | |
| 4650 | bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { |
| 4651 | C = nullptr; |
| 4652 | |
| 4653 | LocTy KwLoc = Lex.getLoc(); |
| 4654 | if (!EatIfPresent(T: lltok::kw_comdat)) |
| 4655 | return false; |
| 4656 | |
| 4657 | if (EatIfPresent(T: lltok::lparen)) { |
| 4658 | if (Lex.getKind() != lltok::ComdatVar) |
| 4659 | return tokError(Msg: "expected comdat variable" ); |
| 4660 | C = getComdat(Name: Lex.getStrVal(), Loc: Lex.getLoc()); |
| 4661 | Lex.Lex(); |
| 4662 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' after comdat var" )) |
| 4663 | return true; |
| 4664 | } else { |
| 4665 | if (GlobalName.empty()) |
| 4666 | return tokError(Msg: "comdat cannot be unnamed" ); |
| 4667 | C = getComdat(Name: std::string(GlobalName), Loc: KwLoc); |
| 4668 | } |
| 4669 | |
| 4670 | return false; |
| 4671 | } |
| 4672 | |
| 4673 | /// parseGlobalValueVector |
| 4674 | /// ::= /*empty*/ |
| 4675 | /// ::= TypeAndValue (',' TypeAndValue)* |
| 4676 | bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) { |
| 4677 | // Empty list. |
| 4678 | if (Lex.getKind() == lltok::rbrace || |
| 4679 | Lex.getKind() == lltok::rsquare || |
| 4680 | Lex.getKind() == lltok::greater || |
| 4681 | Lex.getKind() == lltok::rparen) |
| 4682 | return false; |
| 4683 | |
| 4684 | do { |
| 4685 | // Let the caller deal with inrange. |
| 4686 | if (Lex.getKind() == lltok::kw_inrange) |
| 4687 | return false; |
| 4688 | |
| 4689 | Constant *C; |
| 4690 | if (parseGlobalTypeAndValue(V&: C)) |
| 4691 | return true; |
| 4692 | Elts.push_back(Elt: C); |
| 4693 | } while (EatIfPresent(T: lltok::comma)); |
| 4694 | |
| 4695 | return false; |
| 4696 | } |
| 4697 | |
| 4698 | bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) { |
| 4699 | SmallVector<Metadata *, 16> Elts; |
| 4700 | if (parseMDNodeVector(Elts)) |
| 4701 | return true; |
| 4702 | |
| 4703 | MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); |
| 4704 | return false; |
| 4705 | } |
| 4706 | |
| 4707 | /// MDNode: |
| 4708 | /// ::= !{ ... } |
| 4709 | /// ::= !7 |
| 4710 | /// ::= !DILocation(...) |
| 4711 | bool LLParser::parseMDNode(MDNode *&N) { |
| 4712 | if (Lex.getKind() == lltok::MetadataVar) |
| 4713 | return parseSpecializedMDNode(N); |
| 4714 | |
| 4715 | return parseToken(T: lltok::exclaim, ErrMsg: "expected '!' here" ) || parseMDNodeTail(N); |
| 4716 | } |
| 4717 | |
| 4718 | bool LLParser::parseMDNodeTail(MDNode *&N) { |
| 4719 | // !{ ... } |
| 4720 | if (Lex.getKind() == lltok::lbrace) |
| 4721 | return parseMDTuple(MD&: N); |
| 4722 | |
| 4723 | // !42 |
| 4724 | return parseMDNodeID(Result&: N); |
| 4725 | } |
| 4726 | |
| 4727 | namespace { |
| 4728 | |
| 4729 | /// Structure to represent an optional metadata field. |
| 4730 | template <class FieldTy> struct MDFieldImpl { |
| 4731 | typedef MDFieldImpl ImplTy; |
| 4732 | FieldTy Val; |
| 4733 | bool Seen; |
| 4734 | |
| 4735 | void assign(FieldTy Val) { |
| 4736 | Seen = true; |
| 4737 | this->Val = std::move(Val); |
| 4738 | } |
| 4739 | |
| 4740 | explicit MDFieldImpl(FieldTy Default) |
| 4741 | : Val(std::move(Default)), Seen(false) {} |
| 4742 | }; |
| 4743 | |
| 4744 | /// Structure to represent an optional metadata field that |
| 4745 | /// can be of either type (A or B) and encapsulates the |
| 4746 | /// MD<typeofA>Field and MD<typeofB>Field structs, so not |
| 4747 | /// to reimplement the specifics for representing each Field. |
| 4748 | template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { |
| 4749 | typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; |
| 4750 | FieldTypeA A; |
| 4751 | FieldTypeB B; |
| 4752 | bool Seen; |
| 4753 | |
| 4754 | enum { |
| 4755 | IsInvalid = 0, |
| 4756 | IsTypeA = 1, |
| 4757 | IsTypeB = 2 |
| 4758 | } WhatIs; |
| 4759 | |
| 4760 | void assign(FieldTypeA A) { |
| 4761 | Seen = true; |
| 4762 | this->A = std::move(A); |
| 4763 | WhatIs = IsTypeA; |
| 4764 | } |
| 4765 | |
| 4766 | void assign(FieldTypeB B) { |
| 4767 | Seen = true; |
| 4768 | this->B = std::move(B); |
| 4769 | WhatIs = IsTypeB; |
| 4770 | } |
| 4771 | |
| 4772 | explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) |
| 4773 | : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), |
| 4774 | WhatIs(IsInvalid) {} |
| 4775 | }; |
| 4776 | |
| 4777 | struct MDUnsignedField : public MDFieldImpl<uint64_t> { |
| 4778 | uint64_t Max; |
| 4779 | |
| 4780 | MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) |
| 4781 | : ImplTy(Default), Max(Max) {} |
| 4782 | }; |
| 4783 | |
| 4784 | struct LineField : public MDUnsignedField { |
| 4785 | LineField() : MDUnsignedField(0, UINT32_MAX) {} |
| 4786 | }; |
| 4787 | |
| 4788 | struct ColumnField : public MDUnsignedField { |
| 4789 | ColumnField() : MDUnsignedField(0, UINT16_MAX) {} |
| 4790 | }; |
| 4791 | |
| 4792 | struct DwarfTagField : public MDUnsignedField { |
| 4793 | DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} |
| 4794 | DwarfTagField(dwarf::Tag DefaultTag) |
| 4795 | : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} |
| 4796 | }; |
| 4797 | |
| 4798 | struct DwarfMacinfoTypeField : public MDUnsignedField { |
| 4799 | DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} |
| 4800 | DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) |
| 4801 | : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} |
| 4802 | }; |
| 4803 | |
| 4804 | struct DwarfAttEncodingField : public MDUnsignedField { |
| 4805 | DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} |
| 4806 | }; |
| 4807 | |
| 4808 | struct DwarfVirtualityField : public MDUnsignedField { |
| 4809 | DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} |
| 4810 | }; |
| 4811 | |
| 4812 | struct DwarfLangField : public MDUnsignedField { |
| 4813 | DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} |
| 4814 | }; |
| 4815 | |
| 4816 | struct DwarfSourceLangNameField : public MDUnsignedField { |
| 4817 | DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {} |
| 4818 | }; |
| 4819 | |
| 4820 | struct DwarfCCField : public MDUnsignedField { |
| 4821 | DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} |
| 4822 | }; |
| 4823 | |
| 4824 | struct DwarfEnumKindField : public MDUnsignedField { |
| 4825 | DwarfEnumKindField() |
| 4826 | : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid, |
| 4827 | dwarf::DW_APPLE_ENUM_KIND_max) {} |
| 4828 | }; |
| 4829 | |
| 4830 | struct EmissionKindField : public MDUnsignedField { |
| 4831 | EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} |
| 4832 | }; |
| 4833 | |
| 4834 | struct FixedPointKindField : public MDUnsignedField { |
| 4835 | FixedPointKindField() |
| 4836 | : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {} |
| 4837 | }; |
| 4838 | |
| 4839 | struct NameTableKindField : public MDUnsignedField { |
| 4840 | NameTableKindField() |
| 4841 | : MDUnsignedField( |
| 4842 | 0, (unsigned) |
| 4843 | DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} |
| 4844 | }; |
| 4845 | |
| 4846 | struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { |
| 4847 | DIFlagField() : MDFieldImpl(DINode::FlagZero) {} |
| 4848 | }; |
| 4849 | |
| 4850 | struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { |
| 4851 | DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} |
| 4852 | }; |
| 4853 | |
| 4854 | struct MDAPSIntField : public MDFieldImpl<APSInt> { |
| 4855 | MDAPSIntField() : ImplTy(APSInt()) {} |
| 4856 | }; |
| 4857 | |
| 4858 | struct MDSignedField : public MDFieldImpl<int64_t> { |
| 4859 | int64_t Min = INT64_MIN; |
| 4860 | int64_t Max = INT64_MAX; |
| 4861 | |
| 4862 | MDSignedField(int64_t Default = 0) |
| 4863 | : ImplTy(Default) {} |
| 4864 | MDSignedField(int64_t Default, int64_t Min, int64_t Max) |
| 4865 | : ImplTy(Default), Min(Min), Max(Max) {} |
| 4866 | }; |
| 4867 | |
| 4868 | struct MDBoolField : public MDFieldImpl<bool> { |
| 4869 | MDBoolField(bool Default = false) : ImplTy(Default) {} |
| 4870 | }; |
| 4871 | |
| 4872 | struct MDField : public MDFieldImpl<Metadata *> { |
| 4873 | bool AllowNull; |
| 4874 | |
| 4875 | MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} |
| 4876 | }; |
| 4877 | |
| 4878 | struct MDStringField : public MDFieldImpl<MDString *> { |
| 4879 | enum class EmptyIs { |
| 4880 | Null, //< Allow empty input string, map to nullptr |
| 4881 | Empty, //< Allow empty input string, map to an empty MDString |
| 4882 | Error, //< Disallow empty string, map to an error |
| 4883 | } EmptyIs; |
| 4884 | MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null) |
| 4885 | : ImplTy(nullptr), EmptyIs(EmptyIs) {} |
| 4886 | }; |
| 4887 | |
| 4888 | struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { |
| 4889 | MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} |
| 4890 | }; |
| 4891 | |
| 4892 | struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { |
| 4893 | ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} |
| 4894 | }; |
| 4895 | |
| 4896 | struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { |
| 4897 | MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) |
| 4898 | : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} |
| 4899 | |
| 4900 | MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, |
| 4901 | bool AllowNull = true) |
| 4902 | : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} |
| 4903 | |
| 4904 | bool isMDSignedField() const { return WhatIs == IsTypeA; } |
| 4905 | bool isMDField() const { return WhatIs == IsTypeB; } |
| 4906 | int64_t getMDSignedValue() const { |
| 4907 | assert(isMDSignedField() && "Wrong field type" ); |
| 4908 | return A.Val; |
| 4909 | } |
| 4910 | Metadata *getMDFieldValue() const { |
| 4911 | assert(isMDField() && "Wrong field type" ); |
| 4912 | return B.Val; |
| 4913 | } |
| 4914 | }; |
| 4915 | |
| 4916 | struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> { |
| 4917 | MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true) |
| 4918 | : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {} |
| 4919 | |
| 4920 | MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true) |
| 4921 | : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {} |
| 4922 | |
| 4923 | bool isMDUnsignedField() const { return WhatIs == IsTypeA; } |
| 4924 | bool isMDField() const { return WhatIs == IsTypeB; } |
| 4925 | uint64_t getMDUnsignedValue() const { |
| 4926 | assert(isMDUnsignedField() && "Wrong field type" ); |
| 4927 | return A.Val; |
| 4928 | } |
| 4929 | Metadata *getMDFieldValue() const { |
| 4930 | assert(isMDField() && "Wrong field type" ); |
| 4931 | return B.Val; |
| 4932 | } |
| 4933 | |
| 4934 | Metadata *getValueAsMetadata(LLVMContext &Context) const { |
| 4935 | if (isMDUnsignedField()) |
| 4936 | return ConstantAsMetadata::get( |
| 4937 | C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Context), V: getMDUnsignedValue())); |
| 4938 | if (isMDField()) |
| 4939 | return getMDFieldValue(); |
| 4940 | return nullptr; |
| 4941 | } |
| 4942 | }; |
| 4943 | |
| 4944 | } // end anonymous namespace |
| 4945 | |
| 4946 | namespace llvm { |
| 4947 | |
| 4948 | template <> |
| 4949 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { |
| 4950 | if (Lex.getKind() != lltok::APSInt) |
| 4951 | return tokError(Msg: "expected integer" ); |
| 4952 | |
| 4953 | Result.assign(Val: Lex.getAPSIntVal()); |
| 4954 | Lex.Lex(); |
| 4955 | return false; |
| 4956 | } |
| 4957 | |
| 4958 | template <> |
| 4959 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 4960 | MDUnsignedField &Result) { |
| 4961 | if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) |
| 4962 | return tokError(Msg: "expected unsigned integer" ); |
| 4963 | |
| 4964 | auto &U = Lex.getAPSIntVal(); |
| 4965 | if (U.ugt(RHS: Result.Max)) |
| 4966 | return tokError(Msg: "value for '" + Name + "' too large, limit is " + |
| 4967 | Twine(Result.Max)); |
| 4968 | Result.assign(Val: U.getZExtValue()); |
| 4969 | assert(Result.Val <= Result.Max && "Expected value in range" ); |
| 4970 | Lex.Lex(); |
| 4971 | return false; |
| 4972 | } |
| 4973 | |
| 4974 | template <> |
| 4975 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) { |
| 4976 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 4977 | } |
| 4978 | template <> |
| 4979 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { |
| 4980 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 4981 | } |
| 4982 | |
| 4983 | template <> |
| 4984 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { |
| 4985 | if (Lex.getKind() == lltok::APSInt) |
| 4986 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 4987 | |
| 4988 | if (Lex.getKind() != lltok::DwarfTag) |
| 4989 | return tokError(Msg: "expected DWARF tag" ); |
| 4990 | |
| 4991 | unsigned Tag = dwarf::getTag(TagString: Lex.getStrVal()); |
| 4992 | if (Tag == dwarf::DW_TAG_invalid) |
| 4993 | return tokError(Msg: "invalid DWARF tag" + Twine(" '" ) + Lex.getStrVal() + "'" ); |
| 4994 | assert(Tag <= Result.Max && "Expected valid DWARF tag" ); |
| 4995 | |
| 4996 | Result.assign(Val: Tag); |
| 4997 | Lex.Lex(); |
| 4998 | return false; |
| 4999 | } |
| 5000 | |
| 5001 | template <> |
| 5002 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5003 | DwarfMacinfoTypeField &Result) { |
| 5004 | if (Lex.getKind() == lltok::APSInt) |
| 5005 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5006 | |
| 5007 | if (Lex.getKind() != lltok::DwarfMacinfo) |
| 5008 | return tokError(Msg: "expected DWARF macinfo type" ); |
| 5009 | |
| 5010 | unsigned Macinfo = dwarf::getMacinfo(MacinfoString: Lex.getStrVal()); |
| 5011 | if (Macinfo == dwarf::DW_MACINFO_invalid) |
| 5012 | return tokError(Msg: "invalid DWARF macinfo type" + Twine(" '" ) + |
| 5013 | Lex.getStrVal() + "'" ); |
| 5014 | assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type" ); |
| 5015 | |
| 5016 | Result.assign(Val: Macinfo); |
| 5017 | Lex.Lex(); |
| 5018 | return false; |
| 5019 | } |
| 5020 | |
| 5021 | template <> |
| 5022 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5023 | DwarfVirtualityField &Result) { |
| 5024 | if (Lex.getKind() == lltok::APSInt) |
| 5025 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5026 | |
| 5027 | if (Lex.getKind() != lltok::DwarfVirtuality) |
| 5028 | return tokError(Msg: "expected DWARF virtuality code" ); |
| 5029 | |
| 5030 | unsigned Virtuality = dwarf::getVirtuality(VirtualityString: Lex.getStrVal()); |
| 5031 | if (Virtuality == dwarf::DW_VIRTUALITY_invalid) |
| 5032 | return tokError(Msg: "invalid DWARF virtuality code" + Twine(" '" ) + |
| 5033 | Lex.getStrVal() + "'" ); |
| 5034 | assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code" ); |
| 5035 | Result.assign(Val: Virtuality); |
| 5036 | Lex.Lex(); |
| 5037 | return false; |
| 5038 | } |
| 5039 | |
| 5040 | template <> |
| 5041 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5042 | DwarfEnumKindField &Result) { |
| 5043 | if (Lex.getKind() == lltok::APSInt) |
| 5044 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5045 | |
| 5046 | if (Lex.getKind() != lltok::DwarfEnumKind) |
| 5047 | return tokError(Msg: "expected DWARF enum kind code" ); |
| 5048 | |
| 5049 | unsigned EnumKind = dwarf::getEnumKind(EnumKindString: Lex.getStrVal()); |
| 5050 | if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid) |
| 5051 | return tokError(Msg: "invalid DWARF enum kind code" + Twine(" '" ) + |
| 5052 | Lex.getStrVal() + "'" ); |
| 5053 | assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code" ); |
| 5054 | Result.assign(Val: EnumKind); |
| 5055 | Lex.Lex(); |
| 5056 | return false; |
| 5057 | } |
| 5058 | |
| 5059 | template <> |
| 5060 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { |
| 5061 | if (Lex.getKind() == lltok::APSInt) |
| 5062 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5063 | |
| 5064 | if (Lex.getKind() != lltok::DwarfLang) |
| 5065 | return tokError(Msg: "expected DWARF language" ); |
| 5066 | |
| 5067 | unsigned Lang = dwarf::getLanguage(LanguageString: Lex.getStrVal()); |
| 5068 | if (!Lang) |
| 5069 | return tokError(Msg: "invalid DWARF language" + Twine(" '" ) + Lex.getStrVal() + |
| 5070 | "'" ); |
| 5071 | assert(Lang <= Result.Max && "Expected valid DWARF language" ); |
| 5072 | Result.assign(Val: Lang); |
| 5073 | Lex.Lex(); |
| 5074 | return false; |
| 5075 | } |
| 5076 | |
| 5077 | template <> |
| 5078 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5079 | DwarfSourceLangNameField &Result) { |
| 5080 | if (Lex.getKind() == lltok::APSInt) |
| 5081 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5082 | |
| 5083 | if (Lex.getKind() != lltok::DwarfSourceLangName) |
| 5084 | return tokError(Msg: "expected DWARF source language name" ); |
| 5085 | |
| 5086 | unsigned Lang = dwarf::getSourceLanguageName(SourceLanguageNameString: Lex.getStrVal()); |
| 5087 | if (!Lang) |
| 5088 | return tokError(Msg: "invalid DWARF source language name" + Twine(" '" ) + |
| 5089 | Lex.getStrVal() + "'" ); |
| 5090 | assert(Lang <= Result.Max && "Expected valid DWARF source language name" ); |
| 5091 | Result.assign(Val: Lang); |
| 5092 | Lex.Lex(); |
| 5093 | return false; |
| 5094 | } |
| 5095 | |
| 5096 | template <> |
| 5097 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { |
| 5098 | if (Lex.getKind() == lltok::APSInt) |
| 5099 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5100 | |
| 5101 | if (Lex.getKind() != lltok::DwarfCC) |
| 5102 | return tokError(Msg: "expected DWARF calling convention" ); |
| 5103 | |
| 5104 | unsigned CC = dwarf::getCallingConvention(LanguageString: Lex.getStrVal()); |
| 5105 | if (!CC) |
| 5106 | return tokError(Msg: "invalid DWARF calling convention" + Twine(" '" ) + |
| 5107 | Lex.getStrVal() + "'" ); |
| 5108 | assert(CC <= Result.Max && "Expected valid DWARF calling convention" ); |
| 5109 | Result.assign(Val: CC); |
| 5110 | Lex.Lex(); |
| 5111 | return false; |
| 5112 | } |
| 5113 | |
| 5114 | template <> |
| 5115 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5116 | EmissionKindField &Result) { |
| 5117 | if (Lex.getKind() == lltok::APSInt) |
| 5118 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5119 | |
| 5120 | if (Lex.getKind() != lltok::EmissionKind) |
| 5121 | return tokError(Msg: "expected emission kind" ); |
| 5122 | |
| 5123 | auto Kind = DICompileUnit::getEmissionKind(Str: Lex.getStrVal()); |
| 5124 | if (!Kind) |
| 5125 | return tokError(Msg: "invalid emission kind" + Twine(" '" ) + Lex.getStrVal() + |
| 5126 | "'" ); |
| 5127 | assert(*Kind <= Result.Max && "Expected valid emission kind" ); |
| 5128 | Result.assign(Val: *Kind); |
| 5129 | Lex.Lex(); |
| 5130 | return false; |
| 5131 | } |
| 5132 | |
| 5133 | template <> |
| 5134 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5135 | FixedPointKindField &Result) { |
| 5136 | if (Lex.getKind() == lltok::APSInt) |
| 5137 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5138 | |
| 5139 | if (Lex.getKind() != lltok::FixedPointKind) |
| 5140 | return tokError(Msg: "expected fixed-point kind" ); |
| 5141 | |
| 5142 | auto Kind = DIFixedPointType::getFixedPointKind(Str: Lex.getStrVal()); |
| 5143 | if (!Kind) |
| 5144 | return tokError(Msg: "invalid fixed-point kind" + Twine(" '" ) + Lex.getStrVal() + |
| 5145 | "'" ); |
| 5146 | assert(*Kind <= Result.Max && "Expected valid fixed-point kind" ); |
| 5147 | Result.assign(Val: *Kind); |
| 5148 | Lex.Lex(); |
| 5149 | return false; |
| 5150 | } |
| 5151 | |
| 5152 | template <> |
| 5153 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5154 | NameTableKindField &Result) { |
| 5155 | if (Lex.getKind() == lltok::APSInt) |
| 5156 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5157 | |
| 5158 | if (Lex.getKind() != lltok::NameTableKind) |
| 5159 | return tokError(Msg: "expected nameTable kind" ); |
| 5160 | |
| 5161 | auto Kind = DICompileUnit::getNameTableKind(Str: Lex.getStrVal()); |
| 5162 | if (!Kind) |
| 5163 | return tokError(Msg: "invalid nameTable kind" + Twine(" '" ) + Lex.getStrVal() + |
| 5164 | "'" ); |
| 5165 | assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind" ); |
| 5166 | Result.assign(Val: (unsigned)*Kind); |
| 5167 | Lex.Lex(); |
| 5168 | return false; |
| 5169 | } |
| 5170 | |
| 5171 | template <> |
| 5172 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5173 | DwarfAttEncodingField &Result) { |
| 5174 | if (Lex.getKind() == lltok::APSInt) |
| 5175 | return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result)); |
| 5176 | |
| 5177 | if (Lex.getKind() != lltok::DwarfAttEncoding) |
| 5178 | return tokError(Msg: "expected DWARF type attribute encoding" ); |
| 5179 | |
| 5180 | unsigned Encoding = dwarf::getAttributeEncoding(EncodingString: Lex.getStrVal()); |
| 5181 | if (!Encoding) |
| 5182 | return tokError(Msg: "invalid DWARF type attribute encoding" + Twine(" '" ) + |
| 5183 | Lex.getStrVal() + "'" ); |
| 5184 | assert(Encoding <= Result.Max && "Expected valid DWARF language" ); |
| 5185 | Result.assign(Val: Encoding); |
| 5186 | Lex.Lex(); |
| 5187 | return false; |
| 5188 | } |
| 5189 | |
| 5190 | /// DIFlagField |
| 5191 | /// ::= uint32 |
| 5192 | /// ::= DIFlagVector |
| 5193 | /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic |
| 5194 | template <> |
| 5195 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { |
| 5196 | |
| 5197 | // parser for a single flag. |
| 5198 | auto parseFlag = [&](DINode::DIFlags &Val) { |
| 5199 | if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { |
| 5200 | uint32_t TempVal = static_cast<uint32_t>(Val); |
| 5201 | bool Res = parseUInt32(Val&: TempVal); |
| 5202 | Val = static_cast<DINode::DIFlags>(TempVal); |
| 5203 | return Res; |
| 5204 | } |
| 5205 | |
| 5206 | if (Lex.getKind() != lltok::DIFlag) |
| 5207 | return tokError(Msg: "expected debug info flag" ); |
| 5208 | |
| 5209 | Val = DINode::getFlag(Flag: Lex.getStrVal()); |
| 5210 | if (!Val) |
| 5211 | return tokError(Msg: Twine("invalid debug info flag '" ) + Lex.getStrVal() + |
| 5212 | "'" ); |
| 5213 | Lex.Lex(); |
| 5214 | return false; |
| 5215 | }; |
| 5216 | |
| 5217 | // parse the flags and combine them together. |
| 5218 | DINode::DIFlags Combined = DINode::FlagZero; |
| 5219 | do { |
| 5220 | DINode::DIFlags Val; |
| 5221 | if (parseFlag(Val)) |
| 5222 | return true; |
| 5223 | Combined |= Val; |
| 5224 | } while (EatIfPresent(T: lltok::bar)); |
| 5225 | |
| 5226 | Result.assign(Val: Combined); |
| 5227 | return false; |
| 5228 | } |
| 5229 | |
| 5230 | /// DISPFlagField |
| 5231 | /// ::= uint32 |
| 5232 | /// ::= DISPFlagVector |
| 5233 | /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 |
| 5234 | template <> |
| 5235 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { |
| 5236 | |
| 5237 | // parser for a single flag. |
| 5238 | auto parseFlag = [&](DISubprogram::DISPFlags &Val) { |
| 5239 | if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { |
| 5240 | uint32_t TempVal = static_cast<uint32_t>(Val); |
| 5241 | bool Res = parseUInt32(Val&: TempVal); |
| 5242 | Val = static_cast<DISubprogram::DISPFlags>(TempVal); |
| 5243 | return Res; |
| 5244 | } |
| 5245 | |
| 5246 | if (Lex.getKind() != lltok::DISPFlag) |
| 5247 | return tokError(Msg: "expected debug info flag" ); |
| 5248 | |
| 5249 | Val = DISubprogram::getFlag(Flag: Lex.getStrVal()); |
| 5250 | if (!Val) |
| 5251 | return tokError(Msg: Twine("invalid subprogram debug info flag '" ) + |
| 5252 | Lex.getStrVal() + "'" ); |
| 5253 | Lex.Lex(); |
| 5254 | return false; |
| 5255 | }; |
| 5256 | |
| 5257 | // parse the flags and combine them together. |
| 5258 | DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; |
| 5259 | do { |
| 5260 | DISubprogram::DISPFlags Val; |
| 5261 | if (parseFlag(Val)) |
| 5262 | return true; |
| 5263 | Combined |= Val; |
| 5264 | } while (EatIfPresent(T: lltok::bar)); |
| 5265 | |
| 5266 | Result.assign(Val: Combined); |
| 5267 | return false; |
| 5268 | } |
| 5269 | |
| 5270 | template <> |
| 5271 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) { |
| 5272 | if (Lex.getKind() != lltok::APSInt) |
| 5273 | return tokError(Msg: "expected signed integer" ); |
| 5274 | |
| 5275 | auto &S = Lex.getAPSIntVal(); |
| 5276 | if (S < Result.Min) |
| 5277 | return tokError(Msg: "value for '" + Name + "' too small, limit is " + |
| 5278 | Twine(Result.Min)); |
| 5279 | if (S > Result.Max) |
| 5280 | return tokError(Msg: "value for '" + Name + "' too large, limit is " + |
| 5281 | Twine(Result.Max)); |
| 5282 | Result.assign(Val: S.getExtValue()); |
| 5283 | assert(Result.Val >= Result.Min && "Expected value in range" ); |
| 5284 | assert(Result.Val <= Result.Max && "Expected value in range" ); |
| 5285 | Lex.Lex(); |
| 5286 | return false; |
| 5287 | } |
| 5288 | |
| 5289 | template <> |
| 5290 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { |
| 5291 | switch (Lex.getKind()) { |
| 5292 | default: |
| 5293 | return tokError(Msg: "expected 'true' or 'false'" ); |
| 5294 | case lltok::kw_true: |
| 5295 | Result.assign(Val: true); |
| 5296 | break; |
| 5297 | case lltok::kw_false: |
| 5298 | Result.assign(Val: false); |
| 5299 | break; |
| 5300 | } |
| 5301 | Lex.Lex(); |
| 5302 | return false; |
| 5303 | } |
| 5304 | |
| 5305 | template <> |
| 5306 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) { |
| 5307 | if (Lex.getKind() == lltok::kw_null) { |
| 5308 | if (!Result.AllowNull) |
| 5309 | return tokError(Msg: "'" + Name + "' cannot be null" ); |
| 5310 | Lex.Lex(); |
| 5311 | Result.assign(Val: nullptr); |
| 5312 | return false; |
| 5313 | } |
| 5314 | |
| 5315 | Metadata *MD; |
| 5316 | if (parseMetadata(MD, PFS: nullptr)) |
| 5317 | return true; |
| 5318 | |
| 5319 | Result.assign(Val: MD); |
| 5320 | return false; |
| 5321 | } |
| 5322 | |
| 5323 | template <> |
| 5324 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5325 | MDSignedOrMDField &Result) { |
| 5326 | // Try to parse a signed int. |
| 5327 | if (Lex.getKind() == lltok::APSInt) { |
| 5328 | MDSignedField Res = Result.A; |
| 5329 | if (!parseMDField(Loc, Name, Result&: Res)) { |
| 5330 | Result.assign(A: Res); |
| 5331 | return false; |
| 5332 | } |
| 5333 | return true; |
| 5334 | } |
| 5335 | |
| 5336 | // Otherwise, try to parse as an MDField. |
| 5337 | MDField Res = Result.B; |
| 5338 | if (!parseMDField(Loc, Name, Result&: Res)) { |
| 5339 | Result.assign(B: Res); |
| 5340 | return false; |
| 5341 | } |
| 5342 | |
| 5343 | return true; |
| 5344 | } |
| 5345 | |
| 5346 | template <> |
| 5347 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5348 | MDUnsignedOrMDField &Result) { |
| 5349 | // Try to parse an unsigned int. |
| 5350 | if (Lex.getKind() == lltok::APSInt) { |
| 5351 | MDUnsignedField Res = Result.A; |
| 5352 | if (!parseMDField(Loc, Name, Result&: Res)) { |
| 5353 | Result.assign(A: Res); |
| 5354 | return false; |
| 5355 | } |
| 5356 | return true; |
| 5357 | } |
| 5358 | |
| 5359 | // Otherwise, try to parse as an MDField. |
| 5360 | MDField Res = Result.B; |
| 5361 | if (!parseMDField(Loc, Name, Result&: Res)) { |
| 5362 | Result.assign(B: Res); |
| 5363 | return false; |
| 5364 | } |
| 5365 | |
| 5366 | return true; |
| 5367 | } |
| 5368 | |
| 5369 | template <> |
| 5370 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { |
| 5371 | LocTy ValueLoc = Lex.getLoc(); |
| 5372 | std::string S; |
| 5373 | if (parseStringConstant(Result&: S)) |
| 5374 | return true; |
| 5375 | |
| 5376 | if (S.empty()) { |
| 5377 | switch (Result.EmptyIs) { |
| 5378 | case MDStringField::EmptyIs::Null: |
| 5379 | Result.assign(Val: nullptr); |
| 5380 | return false; |
| 5381 | case MDStringField::EmptyIs::Empty: |
| 5382 | break; |
| 5383 | case MDStringField::EmptyIs::Error: |
| 5384 | return error(L: ValueLoc, Msg: "'" + Name + "' cannot be empty" ); |
| 5385 | } |
| 5386 | } |
| 5387 | |
| 5388 | Result.assign(Val: MDString::get(Context, Str: S)); |
| 5389 | return false; |
| 5390 | } |
| 5391 | |
| 5392 | template <> |
| 5393 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { |
| 5394 | SmallVector<Metadata *, 4> MDs; |
| 5395 | if (parseMDNodeVector(Elts&: MDs)) |
| 5396 | return true; |
| 5397 | |
| 5398 | Result.assign(Val: std::move(MDs)); |
| 5399 | return false; |
| 5400 | } |
| 5401 | |
| 5402 | template <> |
| 5403 | bool LLParser::parseMDField(LocTy Loc, StringRef Name, |
| 5404 | ChecksumKindField &Result) { |
| 5405 | std::optional<DIFile::ChecksumKind> CSKind = |
| 5406 | DIFile::getChecksumKind(CSKindStr: Lex.getStrVal()); |
| 5407 | |
| 5408 | if (Lex.getKind() != lltok::ChecksumKind || !CSKind) |
| 5409 | return tokError(Msg: "invalid checksum kind" + Twine(" '" ) + Lex.getStrVal() + |
| 5410 | "'" ); |
| 5411 | |
| 5412 | Result.assign(Val: *CSKind); |
| 5413 | Lex.Lex(); |
| 5414 | return false; |
| 5415 | } |
| 5416 | |
| 5417 | } // end namespace llvm |
| 5418 | |
| 5419 | template <class ParserTy> |
| 5420 | bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) { |
| 5421 | do { |
| 5422 | if (Lex.getKind() != lltok::LabelStr) |
| 5423 | return tokError(Msg: "expected field label here" ); |
| 5424 | |
| 5425 | if (ParseField()) |
| 5426 | return true; |
| 5427 | } while (EatIfPresent(T: lltok::comma)); |
| 5428 | |
| 5429 | return false; |
| 5430 | } |
| 5431 | |
| 5432 | template <class ParserTy> |
| 5433 | bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) { |
| 5434 | assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name" ); |
| 5435 | Lex.Lex(); |
| 5436 | |
| 5437 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 5438 | return true; |
| 5439 | if (Lex.getKind() != lltok::rparen) |
| 5440 | if (parseMDFieldsImplBody(ParseField)) |
| 5441 | return true; |
| 5442 | |
| 5443 | ClosingLoc = Lex.getLoc(); |
| 5444 | return parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" ); |
| 5445 | } |
| 5446 | |
| 5447 | template <class FieldTy> |
| 5448 | bool LLParser::parseMDField(StringRef Name, FieldTy &Result) { |
| 5449 | if (Result.Seen) |
| 5450 | return tokError(Msg: "field '" + Name + "' cannot be specified more than once" ); |
| 5451 | |
| 5452 | LocTy Loc = Lex.getLoc(); |
| 5453 | Lex.Lex(); |
| 5454 | return parseMDField(Loc, Name, Result); |
| 5455 | } |
| 5456 | |
| 5457 | bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) { |
| 5458 | assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name" ); |
| 5459 | |
| 5460 | #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ |
| 5461 | if (Lex.getStrVal() == #CLASS) \ |
| 5462 | return parse##CLASS(N, IsDistinct); |
| 5463 | #include "llvm/IR/Metadata.def" |
| 5464 | |
| 5465 | return tokError(Msg: "expected metadata type" ); |
| 5466 | } |
| 5467 | |
| 5468 | #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT |
| 5469 | #define NOP_FIELD(NAME, TYPE, INIT) |
| 5470 | #define REQUIRE_FIELD(NAME, TYPE, INIT) \ |
| 5471 | if (!NAME.Seen) \ |
| 5472 | return error(ClosingLoc, "missing required field '" #NAME "'"); |
| 5473 | #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ |
| 5474 | if (Lex.getStrVal() == #NAME) \ |
| 5475 | return parseMDField(#NAME, NAME); |
| 5476 | #define PARSE_MD_FIELDS() \ |
| 5477 | VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ |
| 5478 | do { \ |
| 5479 | LocTy ClosingLoc; \ |
| 5480 | if (parseMDFieldsImpl( \ |
| 5481 | [&]() -> bool { \ |
| 5482 | VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ |
| 5483 | return tokError(Twine("invalid field '") + Lex.getStrVal() + \ |
| 5484 | "'"); \ |
| 5485 | }, \ |
| 5486 | ClosingLoc)) \ |
| 5487 | return true; \ |
| 5488 | VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ |
| 5489 | } while (false) |
| 5490 | #define GET_OR_DISTINCT(CLASS, ARGS) \ |
| 5491 | (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) |
| 5492 | |
| 5493 | /// parseDILocationFields: |
| 5494 | /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, |
| 5495 | /// isImplicitCode: true, atomGroup: 1, atomRank: 1) |
| 5496 | bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) { |
| 5497 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5498 | OPTIONAL(line, LineField, ); \ |
| 5499 | OPTIONAL(column, ColumnField, ); \ |
| 5500 | REQUIRED(scope, MDField, (/* AllowNull */ false)); \ |
| 5501 | OPTIONAL(inlinedAt, MDField, ); \ |
| 5502 | OPTIONAL(isImplicitCode, MDBoolField, (false)); \ |
| 5503 | OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \ |
| 5504 | OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); |
| 5505 | PARSE_MD_FIELDS(); |
| 5506 | #undef VISIT_MD_FIELDS |
| 5507 | |
| 5508 | Result = GET_OR_DISTINCT( |
| 5509 | DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val, |
| 5510 | isImplicitCode.Val, atomGroup.Val, atomRank.Val)); |
| 5511 | return false; |
| 5512 | } |
| 5513 | |
| 5514 | /// parseDIAssignID: |
| 5515 | /// ::= distinct !DIAssignID() |
| 5516 | bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) { |
| 5517 | if (!IsDistinct) |
| 5518 | return tokError(Msg: "missing 'distinct', required for !DIAssignID()" ); |
| 5519 | |
| 5520 | Lex.Lex(); |
| 5521 | |
| 5522 | // Now eat the parens. |
| 5523 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 5524 | return true; |
| 5525 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 5526 | return true; |
| 5527 | |
| 5528 | Result = DIAssignID::getDistinct(Context); |
| 5529 | return false; |
| 5530 | } |
| 5531 | |
| 5532 | /// parseGenericDINode: |
| 5533 | /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) |
| 5534 | bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) { |
| 5535 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5536 | REQUIRED(tag, DwarfTagField, ); \ |
| 5537 | OPTIONAL(, MDStringField, ); \ |
| 5538 | OPTIONAL(operands, MDFieldList, ); |
| 5539 | PARSE_MD_FIELDS(); |
| 5540 | #undef VISIT_MD_FIELDS |
| 5541 | |
| 5542 | Result = GET_OR_DISTINCT(GenericDINode, |
| 5543 | (Context, tag.Val, header.Val, operands.Val)); |
| 5544 | return false; |
| 5545 | } |
| 5546 | |
| 5547 | /// parseDISubrangeType: |
| 5548 | /// ::= !DISubrangeType(name: "whatever", file: !0, |
| 5549 | /// line: 7, scope: !1, baseType: !2, size: 32, |
| 5550 | /// align: 32, flags: 0, lowerBound: !3 |
| 5551 | /// upperBound: !4, stride: !5, bias: !6) |
| 5552 | bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) { |
| 5553 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5554 | OPTIONAL(name, MDStringField, ); \ |
| 5555 | OPTIONAL(file, MDField, ); \ |
| 5556 | OPTIONAL(line, LineField, ); \ |
| 5557 | OPTIONAL(scope, MDField, ); \ |
| 5558 | OPTIONAL(baseType, MDField, ); \ |
| 5559 | OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5560 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5561 | OPTIONAL(flags, DIFlagField, ); \ |
| 5562 | OPTIONAL(lowerBound, MDSignedOrMDField, ); \ |
| 5563 | OPTIONAL(upperBound, MDSignedOrMDField, ); \ |
| 5564 | OPTIONAL(stride, MDSignedOrMDField, ); \ |
| 5565 | OPTIONAL(bias, MDSignedOrMDField, ); |
| 5566 | PARSE_MD_FIELDS(); |
| 5567 | #undef VISIT_MD_FIELDS |
| 5568 | |
| 5569 | auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { |
| 5570 | if (Bound.isMDSignedField()) |
| 5571 | return ConstantAsMetadata::get(C: ConstantInt::getSigned( |
| 5572 | Ty: Type::getInt64Ty(C&: Context), V: Bound.getMDSignedValue())); |
| 5573 | if (Bound.isMDField()) |
| 5574 | return Bound.getMDFieldValue(); |
| 5575 | return nullptr; |
| 5576 | }; |
| 5577 | |
| 5578 | Metadata *LowerBound = convToMetadata(lowerBound); |
| 5579 | Metadata *UpperBound = convToMetadata(upperBound); |
| 5580 | Metadata *Stride = convToMetadata(stride); |
| 5581 | Metadata *Bias = convToMetadata(bias); |
| 5582 | |
| 5583 | Result = GET_OR_DISTINCT( |
| 5584 | DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val, |
| 5585 | size.getValueAsMetadata(Context), align.Val, flags.Val, |
| 5586 | baseType.Val, LowerBound, UpperBound, Stride, Bias)); |
| 5587 | |
| 5588 | return false; |
| 5589 | } |
| 5590 | |
| 5591 | /// parseDISubrange: |
| 5592 | /// ::= !DISubrange(count: 30, lowerBound: 2) |
| 5593 | /// ::= !DISubrange(count: !node, lowerBound: 2) |
| 5594 | /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) |
| 5595 | bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) { |
| 5596 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5597 | OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ |
| 5598 | OPTIONAL(lowerBound, MDSignedOrMDField, ); \ |
| 5599 | OPTIONAL(upperBound, MDSignedOrMDField, ); \ |
| 5600 | OPTIONAL(stride, MDSignedOrMDField, ); |
| 5601 | PARSE_MD_FIELDS(); |
| 5602 | #undef VISIT_MD_FIELDS |
| 5603 | |
| 5604 | Metadata *Count = nullptr; |
| 5605 | Metadata *LowerBound = nullptr; |
| 5606 | Metadata *UpperBound = nullptr; |
| 5607 | Metadata *Stride = nullptr; |
| 5608 | |
| 5609 | auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * { |
| 5610 | if (Bound.isMDSignedField()) |
| 5611 | return ConstantAsMetadata::get(C: ConstantInt::getSigned( |
| 5612 | Ty: Type::getInt64Ty(C&: Context), V: Bound.getMDSignedValue())); |
| 5613 | if (Bound.isMDField()) |
| 5614 | return Bound.getMDFieldValue(); |
| 5615 | return nullptr; |
| 5616 | }; |
| 5617 | |
| 5618 | Count = convToMetadata(count); |
| 5619 | LowerBound = convToMetadata(lowerBound); |
| 5620 | UpperBound = convToMetadata(upperBound); |
| 5621 | Stride = convToMetadata(stride); |
| 5622 | |
| 5623 | Result = GET_OR_DISTINCT(DISubrange, |
| 5624 | (Context, Count, LowerBound, UpperBound, Stride)); |
| 5625 | |
| 5626 | return false; |
| 5627 | } |
| 5628 | |
| 5629 | /// parseDIGenericSubrange: |
| 5630 | /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride: |
| 5631 | /// !node3) |
| 5632 | bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) { |
| 5633 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5634 | OPTIONAL(count, MDSignedOrMDField, ); \ |
| 5635 | OPTIONAL(lowerBound, MDSignedOrMDField, ); \ |
| 5636 | OPTIONAL(upperBound, MDSignedOrMDField, ); \ |
| 5637 | OPTIONAL(stride, MDSignedOrMDField, ); |
| 5638 | PARSE_MD_FIELDS(); |
| 5639 | #undef VISIT_MD_FIELDS |
| 5640 | |
| 5641 | auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * { |
| 5642 | if (Bound.isMDSignedField()) |
| 5643 | return DIExpression::get( |
| 5644 | Context, Elements: {dwarf::DW_OP_consts, |
| 5645 | static_cast<uint64_t>(Bound.getMDSignedValue())}); |
| 5646 | if (Bound.isMDField()) |
| 5647 | return Bound.getMDFieldValue(); |
| 5648 | return nullptr; |
| 5649 | }; |
| 5650 | |
| 5651 | Metadata *Count = ConvToMetadata(count); |
| 5652 | Metadata *LowerBound = ConvToMetadata(lowerBound); |
| 5653 | Metadata *UpperBound = ConvToMetadata(upperBound); |
| 5654 | Metadata *Stride = ConvToMetadata(stride); |
| 5655 | |
| 5656 | Result = GET_OR_DISTINCT(DIGenericSubrange, |
| 5657 | (Context, Count, LowerBound, UpperBound, Stride)); |
| 5658 | |
| 5659 | return false; |
| 5660 | } |
| 5661 | |
| 5662 | /// parseDIEnumerator: |
| 5663 | /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") |
| 5664 | bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) { |
| 5665 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5666 | REQUIRED(name, MDStringField, ); \ |
| 5667 | REQUIRED(value, MDAPSIntField, ); \ |
| 5668 | OPTIONAL(isUnsigned, MDBoolField, (false)); |
| 5669 | PARSE_MD_FIELDS(); |
| 5670 | #undef VISIT_MD_FIELDS |
| 5671 | |
| 5672 | if (isUnsigned.Val && value.Val.isNegative()) |
| 5673 | return tokError(Msg: "unsigned enumerator with negative value" ); |
| 5674 | |
| 5675 | APSInt Value(value.Val); |
| 5676 | // Add a leading zero so that unsigned values with the msb set are not |
| 5677 | // mistaken for negative values when used for signed enumerators. |
| 5678 | if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) |
| 5679 | Value = Value.zext(width: Value.getBitWidth() + 1); |
| 5680 | |
| 5681 | Result = |
| 5682 | GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); |
| 5683 | |
| 5684 | return false; |
| 5685 | } |
| 5686 | |
| 5687 | /// parseDIBasicType: |
| 5688 | /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, |
| 5689 | /// encoding: DW_ATE_encoding, flags: 0) |
| 5690 | bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) { |
| 5691 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5692 | OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ |
| 5693 | OPTIONAL(name, MDStringField, ); \ |
| 5694 | OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5695 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5696 | OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5697 | OPTIONAL(encoding, DwarfAttEncodingField, ); \ |
| 5698 | OPTIONAL(, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5699 | OPTIONAL(flags, DIFlagField, ); |
| 5700 | PARSE_MD_FIELDS(); |
| 5701 | #undef VISIT_MD_FIELDS |
| 5702 | |
| 5703 | Result = GET_OR_DISTINCT( |
| 5704 | DIBasicType, |
| 5705 | (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val, |
| 5706 | encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val)); |
| 5707 | return false; |
| 5708 | } |
| 5709 | |
| 5710 | /// parseDIFixedPointType: |
| 5711 | /// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32, |
| 5712 | /// align: 32, encoding: DW_ATE_signed_fixed, |
| 5713 | /// flags: 0, kind: Rational, factor: 3, numerator: 1, |
| 5714 | /// denominator: 8) |
| 5715 | bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) { |
| 5716 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5717 | OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ |
| 5718 | OPTIONAL(name, MDStringField, ); \ |
| 5719 | OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5720 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5721 | OPTIONAL(encoding, DwarfAttEncodingField, ); \ |
| 5722 | OPTIONAL(flags, DIFlagField, ); \ |
| 5723 | OPTIONAL(kind, FixedPointKindField, ); \ |
| 5724 | OPTIONAL(factor, MDSignedField, ); \ |
| 5725 | OPTIONAL(numerator, MDAPSIntField, ); \ |
| 5726 | OPTIONAL(denominator, MDAPSIntField, ); |
| 5727 | PARSE_MD_FIELDS(); |
| 5728 | #undef VISIT_MD_FIELDS |
| 5729 | |
| 5730 | Result = GET_OR_DISTINCT(DIFixedPointType, |
| 5731 | (Context, tag.Val, name.Val, |
| 5732 | size.getValueAsMetadata(Context), align.Val, |
| 5733 | encoding.Val, flags.Val, kind.Val, factor.Val, |
| 5734 | numerator.Val, denominator.Val)); |
| 5735 | return false; |
| 5736 | } |
| 5737 | |
| 5738 | /// parseDIStringType: |
| 5739 | /// ::= !DIStringType(name: "character(4)", size: 32, align: 32) |
| 5740 | bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) { |
| 5741 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5742 | OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \ |
| 5743 | OPTIONAL(name, MDStringField, ); \ |
| 5744 | OPTIONAL(stringLength, MDField, ); \ |
| 5745 | OPTIONAL(stringLengthExpression, MDField, ); \ |
| 5746 | OPTIONAL(stringLocationExpression, MDField, ); \ |
| 5747 | OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5748 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5749 | OPTIONAL(encoding, DwarfAttEncodingField, ); |
| 5750 | PARSE_MD_FIELDS(); |
| 5751 | #undef VISIT_MD_FIELDS |
| 5752 | |
| 5753 | Result = GET_OR_DISTINCT( |
| 5754 | DIStringType, |
| 5755 | (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val, |
| 5756 | stringLocationExpression.Val, size.getValueAsMetadata(Context), |
| 5757 | align.Val, encoding.Val)); |
| 5758 | return false; |
| 5759 | } |
| 5760 | |
| 5761 | /// parseDIDerivedType: |
| 5762 | /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, |
| 5763 | /// line: 7, scope: !1, baseType: !2, size: 32, |
| 5764 | /// align: 32, offset: 0, flags: 0, extraData: !3, |
| 5765 | /// dwarfAddressSpace: 3, ptrAuthKey: 1, |
| 5766 | /// ptrAuthIsAddressDiscriminated: true, |
| 5767 | /// ptrAuthExtraDiscriminator: 0x1234, |
| 5768 | /// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1 |
| 5769 | /// ) |
| 5770 | bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) { |
| 5771 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5772 | REQUIRED(tag, DwarfTagField, ); \ |
| 5773 | OPTIONAL(name, MDStringField, ); \ |
| 5774 | OPTIONAL(file, MDField, ); \ |
| 5775 | OPTIONAL(line, LineField, ); \ |
| 5776 | OPTIONAL(scope, MDField, ); \ |
| 5777 | REQUIRED(baseType, MDField, ); \ |
| 5778 | OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5779 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5780 | OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5781 | OPTIONAL(flags, DIFlagField, ); \ |
| 5782 | OPTIONAL(, MDField, ); \ |
| 5783 | OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \ |
| 5784 | OPTIONAL(annotations, MDField, ); \ |
| 5785 | OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \ |
| 5786 | OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \ |
| 5787 | OPTIONAL(, MDUnsignedField, (0, 0xffff)); \ |
| 5788 | OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \ |
| 5789 | OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, ); |
| 5790 | PARSE_MD_FIELDS(); |
| 5791 | #undef VISIT_MD_FIELDS |
| 5792 | |
| 5793 | std::optional<unsigned> DWARFAddressSpace; |
| 5794 | if (dwarfAddressSpace.Val != UINT32_MAX) |
| 5795 | DWARFAddressSpace = dwarfAddressSpace.Val; |
| 5796 | std::optional<DIDerivedType::PtrAuthData> PtrAuthData; |
| 5797 | if (ptrAuthKey.Val) |
| 5798 | PtrAuthData.emplace( |
| 5799 | args: (unsigned)ptrAuthKey.Val, args&: ptrAuthIsAddressDiscriminated.Val, |
| 5800 | args: (unsigned)ptrAuthExtraDiscriminator.Val, args&: ptrAuthIsaPointer.Val, |
| 5801 | args&: ptrAuthAuthenticatesNullValues.Val); |
| 5802 | |
| 5803 | Result = GET_OR_DISTINCT( |
| 5804 | DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, |
| 5805 | baseType.Val, size.getValueAsMetadata(Context), align.Val, |
| 5806 | offset.getValueAsMetadata(Context), DWARFAddressSpace, |
| 5807 | PtrAuthData, flags.Val, extraData.Val, annotations.Val)); |
| 5808 | return false; |
| 5809 | } |
| 5810 | |
| 5811 | bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) { |
| 5812 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5813 | REQUIRED(tag, DwarfTagField, ); \ |
| 5814 | OPTIONAL(name, MDStringField, ); \ |
| 5815 | OPTIONAL(file, MDField, ); \ |
| 5816 | OPTIONAL(line, LineField, ); \ |
| 5817 | OPTIONAL(scope, MDField, ); \ |
| 5818 | OPTIONAL(baseType, MDField, ); \ |
| 5819 | OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5820 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5821 | OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \ |
| 5822 | OPTIONAL(flags, DIFlagField, ); \ |
| 5823 | OPTIONAL(elements, MDField, ); \ |
| 5824 | OPTIONAL(runtimeLang, DwarfLangField, ); \ |
| 5825 | OPTIONAL(enumKind, DwarfEnumKindField, ); \ |
| 5826 | OPTIONAL(vtableHolder, MDField, ); \ |
| 5827 | OPTIONAL(templateParams, MDField, ); \ |
| 5828 | OPTIONAL(identifier, MDStringField, ); \ |
| 5829 | OPTIONAL(discriminator, MDField, ); \ |
| 5830 | OPTIONAL(dataLocation, MDField, ); \ |
| 5831 | OPTIONAL(associated, MDField, ); \ |
| 5832 | OPTIONAL(allocated, MDField, ); \ |
| 5833 | OPTIONAL(rank, MDSignedOrMDField, ); \ |
| 5834 | OPTIONAL(annotations, MDField, ); \ |
| 5835 | OPTIONAL(, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5836 | OPTIONAL(specification, MDField, ); \ |
| 5837 | OPTIONAL(bitStride, MDField, ); |
| 5838 | PARSE_MD_FIELDS(); |
| 5839 | #undef VISIT_MD_FIELDS |
| 5840 | |
| 5841 | Metadata *Rank = nullptr; |
| 5842 | if (rank.isMDSignedField()) |
| 5843 | Rank = ConstantAsMetadata::get(C: ConstantInt::getSigned( |
| 5844 | Ty: Type::getInt64Ty(C&: Context), V: rank.getMDSignedValue())); |
| 5845 | else if (rank.isMDField()) |
| 5846 | Rank = rank.getMDFieldValue(); |
| 5847 | |
| 5848 | std::optional<unsigned> EnumKind; |
| 5849 | if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid) |
| 5850 | EnumKind = enumKind.Val; |
| 5851 | |
| 5852 | // If this has an identifier try to build an ODR type. |
| 5853 | if (identifier.Val) |
| 5854 | if (auto *CT = DICompositeType::buildODRType( |
| 5855 | Context, Identifier&: *identifier.Val, Tag: tag.Val, Name: name.Val, File: file.Val, Line: line.Val, |
| 5856 | Scope: scope.Val, BaseType: baseType.Val, SizeInBits: size.getValueAsMetadata(Context), |
| 5857 | AlignInBits: align.Val, OffsetInBits: offset.getValueAsMetadata(Context), Specification: specification.Val, |
| 5858 | NumExtraInhabitants: num_extra_inhabitants.Val, Flags: flags.Val, Elements: elements.Val, RuntimeLang: runtimeLang.Val, |
| 5859 | EnumKind, VTableHolder: vtableHolder.Val, TemplateParams: templateParams.Val, Discriminator: discriminator.Val, |
| 5860 | DataLocation: dataLocation.Val, Associated: associated.Val, Allocated: allocated.Val, Rank, |
| 5861 | Annotations: annotations.Val, BitStride: bitStride.Val)) { |
| 5862 | Result = CT; |
| 5863 | return false; |
| 5864 | } |
| 5865 | |
| 5866 | // Create a new node, and save it in the context if it belongs in the type |
| 5867 | // map. |
| 5868 | Result = GET_OR_DISTINCT( |
| 5869 | DICompositeType, |
| 5870 | (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, |
| 5871 | size.getValueAsMetadata(Context), align.Val, |
| 5872 | offset.getValueAsMetadata(Context), flags.Val, elements.Val, |
| 5873 | runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val, |
| 5874 | identifier.Val, discriminator.Val, dataLocation.Val, associated.Val, |
| 5875 | allocated.Val, Rank, annotations.Val, specification.Val, |
| 5876 | num_extra_inhabitants.Val, bitStride.Val)); |
| 5877 | return false; |
| 5878 | } |
| 5879 | |
| 5880 | bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) { |
| 5881 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5882 | OPTIONAL(flags, DIFlagField, ); \ |
| 5883 | OPTIONAL(cc, DwarfCCField, ); \ |
| 5884 | REQUIRED(types, MDField, ); |
| 5885 | PARSE_MD_FIELDS(); |
| 5886 | #undef VISIT_MD_FIELDS |
| 5887 | |
| 5888 | Result = GET_OR_DISTINCT(DISubroutineType, |
| 5889 | (Context, flags.Val, cc.Val, types.Val)); |
| 5890 | return false; |
| 5891 | } |
| 5892 | |
| 5893 | /// parseDIFileType: |
| 5894 | /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", |
| 5895 | /// checksumkind: CSK_MD5, |
| 5896 | /// checksum: "000102030405060708090a0b0c0d0e0f", |
| 5897 | /// source: "source file contents") |
| 5898 | bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) { |
| 5899 | // The default constructed value for checksumkind is required, but will never |
| 5900 | // be used, as the parser checks if the field was actually Seen before using |
| 5901 | // the Val. |
| 5902 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5903 | REQUIRED(filename, MDStringField, ); \ |
| 5904 | REQUIRED(directory, MDStringField, ); \ |
| 5905 | OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ |
| 5906 | OPTIONAL(checksum, MDStringField, ); \ |
| 5907 | OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty)); |
| 5908 | PARSE_MD_FIELDS(); |
| 5909 | #undef VISIT_MD_FIELDS |
| 5910 | |
| 5911 | std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; |
| 5912 | if (checksumkind.Seen && checksum.Seen) |
| 5913 | OptChecksum.emplace(args&: checksumkind.Val, args&: checksum.Val); |
| 5914 | else if (checksumkind.Seen || checksum.Seen) |
| 5915 | return tokError(Msg: "'checksumkind' and 'checksum' must be provided together" ); |
| 5916 | |
| 5917 | MDString *Source = nullptr; |
| 5918 | if (source.Seen) |
| 5919 | Source = source.Val; |
| 5920 | Result = GET_OR_DISTINCT( |
| 5921 | DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source)); |
| 5922 | return false; |
| 5923 | } |
| 5924 | |
| 5925 | /// parseDICompileUnit: |
| 5926 | /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", |
| 5927 | /// isOptimized: true, flags: "-O2", runtimeVersion: 1, |
| 5928 | /// splitDebugFilename: "abc.debug", |
| 5929 | /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, |
| 5930 | /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, |
| 5931 | /// sysroot: "/", sdk: "MacOSX.sdk") |
| 5932 | bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) { |
| 5933 | if (!IsDistinct) |
| 5934 | return tokError(Msg: "missing 'distinct', required for !DICompileUnit" ); |
| 5935 | |
| 5936 | LocTy Loc = Lex.getLoc(); |
| 5937 | |
| 5938 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 5939 | REQUIRED(file, MDField, (/* AllowNull */ false)); \ |
| 5940 | OPTIONAL(language, DwarfLangField, ); \ |
| 5941 | OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \ |
| 5942 | OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5943 | OPTIONAL(producer, MDStringField, ); \ |
| 5944 | OPTIONAL(isOptimized, MDBoolField, ); \ |
| 5945 | OPTIONAL(flags, MDStringField, ); \ |
| 5946 | OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ |
| 5947 | OPTIONAL(splitDebugFilename, MDStringField, ); \ |
| 5948 | OPTIONAL(emissionKind, EmissionKindField, ); \ |
| 5949 | OPTIONAL(enums, MDField, ); \ |
| 5950 | OPTIONAL(retainedTypes, MDField, ); \ |
| 5951 | OPTIONAL(globals, MDField, ); \ |
| 5952 | OPTIONAL(imports, MDField, ); \ |
| 5953 | OPTIONAL(macros, MDField, ); \ |
| 5954 | OPTIONAL(dwoId, MDUnsignedField, ); \ |
| 5955 | OPTIONAL(splitDebugInlining, MDBoolField, = true); \ |
| 5956 | OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ |
| 5957 | OPTIONAL(nameTableKind, NameTableKindField, ); \ |
| 5958 | OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ |
| 5959 | OPTIONAL(sysroot, MDStringField, ); \ |
| 5960 | OPTIONAL(sdk, MDStringField, ); |
| 5961 | PARSE_MD_FIELDS(); |
| 5962 | #undef VISIT_MD_FIELDS |
| 5963 | |
| 5964 | if (!language.Seen && !sourceLanguageName.Seen) |
| 5965 | return error(L: Loc, Msg: "missing one of 'language' or 'sourceLanguageName', " |
| 5966 | "required for !DICompileUnit" ); |
| 5967 | |
| 5968 | if (language.Seen && sourceLanguageName.Seen) |
| 5969 | return error(L: Loc, Msg: "can only specify one of 'language' and " |
| 5970 | "'sourceLanguageName' on !DICompileUnit" ); |
| 5971 | |
| 5972 | if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen) |
| 5973 | return error(L: Loc, Msg: "'sourceLanguageVersion' requires an associated " |
| 5974 | "'sourceLanguageName' on !DICompileUnit" ); |
| 5975 | |
| 5976 | Result = DICompileUnit::getDistinct( |
| 5977 | Context, |
| 5978 | SourceLanguage: language.Seen ? DISourceLanguageName(language.Val) |
| 5979 | : DISourceLanguageName(sourceLanguageName.Val, |
| 5980 | sourceLanguageVersion.Val), |
| 5981 | File: file.Val, Producer: producer.Val, IsOptimized: isOptimized.Val, Flags: flags.Val, RuntimeVersion: runtimeVersion.Val, |
| 5982 | SplitDebugFilename: splitDebugFilename.Val, EmissionKind: emissionKind.Val, EnumTypes: enums.Val, RetainedTypes: retainedTypes.Val, |
| 5983 | GlobalVariables: globals.Val, ImportedEntities: imports.Val, Macros: macros.Val, DWOId: dwoId.Val, SplitDebugInlining: splitDebugInlining.Val, |
| 5984 | DebugInfoForProfiling: debugInfoForProfiling.Val, NameTableKind: nameTableKind.Val, RangesBaseAddress: rangesBaseAddress.Val, |
| 5985 | SysRoot: sysroot.Val, SDK: sdk.Val); |
| 5986 | return false; |
| 5987 | } |
| 5988 | |
| 5989 | /// parseDISubprogram: |
| 5990 | /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", |
| 5991 | /// file: !1, line: 7, type: !2, isLocal: false, |
| 5992 | /// isDefinition: true, scopeLine: 8, containingType: !3, |
| 5993 | /// virtuality: DW_VIRTUALTIY_pure_virtual, |
| 5994 | /// virtualIndex: 10, thisAdjustment: 4, flags: 11, |
| 5995 | /// spFlags: 10, isOptimized: false, templateParams: !4, |
| 5996 | /// declaration: !5, retainedNodes: !6, thrownTypes: !7, |
| 5997 | /// annotations: !8) |
| 5998 | bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) { |
| 5999 | auto Loc = Lex.getLoc(); |
| 6000 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6001 | OPTIONAL(scope, MDField, ); \ |
| 6002 | OPTIONAL(name, MDStringField, ); \ |
| 6003 | OPTIONAL(linkageName, MDStringField, ); \ |
| 6004 | OPTIONAL(file, MDField, ); \ |
| 6005 | OPTIONAL(line, LineField, ); \ |
| 6006 | OPTIONAL(type, MDField, ); \ |
| 6007 | OPTIONAL(isLocal, MDBoolField, ); \ |
| 6008 | OPTIONAL(isDefinition, MDBoolField, (true)); \ |
| 6009 | OPTIONAL(scopeLine, LineField, ); \ |
| 6010 | OPTIONAL(containingType, MDField, ); \ |
| 6011 | OPTIONAL(virtuality, DwarfVirtualityField, ); \ |
| 6012 | OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ |
| 6013 | OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ |
| 6014 | OPTIONAL(flags, DIFlagField, ); \ |
| 6015 | OPTIONAL(spFlags, DISPFlagField, ); \ |
| 6016 | OPTIONAL(isOptimized, MDBoolField, ); \ |
| 6017 | OPTIONAL(unit, MDField, ); \ |
| 6018 | OPTIONAL(templateParams, MDField, ); \ |
| 6019 | OPTIONAL(declaration, MDField, ); \ |
| 6020 | OPTIONAL(retainedNodes, MDField, ); \ |
| 6021 | OPTIONAL(thrownTypes, MDField, ); \ |
| 6022 | OPTIONAL(annotations, MDField, ); \ |
| 6023 | OPTIONAL(targetFuncName, MDStringField, ); \ |
| 6024 | OPTIONAL(keyInstructions, MDBoolField, ); |
| 6025 | PARSE_MD_FIELDS(); |
| 6026 | #undef VISIT_MD_FIELDS |
| 6027 | |
| 6028 | // An explicit spFlags field takes precedence over individual fields in |
| 6029 | // older IR versions. |
| 6030 | DISubprogram::DISPFlags SPFlags = |
| 6031 | spFlags.Seen ? spFlags.Val |
| 6032 | : DISubprogram::toSPFlags(IsLocalToUnit: isLocal.Val, IsDefinition: isDefinition.Val, |
| 6033 | IsOptimized: isOptimized.Val, Virtuality: virtuality.Val); |
| 6034 | if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) |
| 6035 | return error( |
| 6036 | L: Loc, |
| 6037 | Msg: "missing 'distinct', required for !DISubprogram that is a Definition" ); |
| 6038 | Result = GET_OR_DISTINCT( |
| 6039 | DISubprogram, |
| 6040 | (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, |
| 6041 | type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, |
| 6042 | thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, |
| 6043 | declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val, |
| 6044 | targetFuncName.Val, keyInstructions.Val)); |
| 6045 | return false; |
| 6046 | } |
| 6047 | |
| 6048 | /// parseDILexicalBlock: |
| 6049 | /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) |
| 6050 | bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) { |
| 6051 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6052 | REQUIRED(scope, MDField, (/* AllowNull */ false)); \ |
| 6053 | OPTIONAL(file, MDField, ); \ |
| 6054 | OPTIONAL(line, LineField, ); \ |
| 6055 | OPTIONAL(column, ColumnField, ); |
| 6056 | PARSE_MD_FIELDS(); |
| 6057 | #undef VISIT_MD_FIELDS |
| 6058 | |
| 6059 | Result = GET_OR_DISTINCT( |
| 6060 | DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); |
| 6061 | return false; |
| 6062 | } |
| 6063 | |
| 6064 | /// parseDILexicalBlockFile: |
| 6065 | /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) |
| 6066 | bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { |
| 6067 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6068 | REQUIRED(scope, MDField, (/* AllowNull */ false)); \ |
| 6069 | OPTIONAL(file, MDField, ); \ |
| 6070 | REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); |
| 6071 | PARSE_MD_FIELDS(); |
| 6072 | #undef VISIT_MD_FIELDS |
| 6073 | |
| 6074 | Result = GET_OR_DISTINCT(DILexicalBlockFile, |
| 6075 | (Context, scope.Val, file.Val, discriminator.Val)); |
| 6076 | return false; |
| 6077 | } |
| 6078 | |
| 6079 | /// parseDICommonBlock: |
| 6080 | /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) |
| 6081 | bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) { |
| 6082 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6083 | REQUIRED(scope, MDField, ); \ |
| 6084 | OPTIONAL(declaration, MDField, ); \ |
| 6085 | OPTIONAL(name, MDStringField, ); \ |
| 6086 | OPTIONAL(file, MDField, ); \ |
| 6087 | OPTIONAL(line, LineField, ); |
| 6088 | PARSE_MD_FIELDS(); |
| 6089 | #undef VISIT_MD_FIELDS |
| 6090 | |
| 6091 | Result = GET_OR_DISTINCT(DICommonBlock, |
| 6092 | (Context, scope.Val, declaration.Val, name.Val, |
| 6093 | file.Val, line.Val)); |
| 6094 | return false; |
| 6095 | } |
| 6096 | |
| 6097 | /// parseDINamespace: |
| 6098 | /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) |
| 6099 | bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) { |
| 6100 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6101 | REQUIRED(scope, MDField, ); \ |
| 6102 | OPTIONAL(name, MDStringField, ); \ |
| 6103 | OPTIONAL(exportSymbols, MDBoolField, ); |
| 6104 | PARSE_MD_FIELDS(); |
| 6105 | #undef VISIT_MD_FIELDS |
| 6106 | |
| 6107 | Result = GET_OR_DISTINCT(DINamespace, |
| 6108 | (Context, scope.Val, name.Val, exportSymbols.Val)); |
| 6109 | return false; |
| 6110 | } |
| 6111 | |
| 6112 | /// parseDIMacro: |
| 6113 | /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: |
| 6114 | /// "SomeValue") |
| 6115 | bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) { |
| 6116 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6117 | REQUIRED(type, DwarfMacinfoTypeField, ); \ |
| 6118 | OPTIONAL(line, LineField, ); \ |
| 6119 | REQUIRED(name, MDStringField, ); \ |
| 6120 | OPTIONAL(value, MDStringField, ); |
| 6121 | PARSE_MD_FIELDS(); |
| 6122 | #undef VISIT_MD_FIELDS |
| 6123 | |
| 6124 | Result = GET_OR_DISTINCT(DIMacro, |
| 6125 | (Context, type.Val, line.Val, name.Val, value.Val)); |
| 6126 | return false; |
| 6127 | } |
| 6128 | |
| 6129 | /// parseDIMacroFile: |
| 6130 | /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) |
| 6131 | bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) { |
| 6132 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6133 | OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ |
| 6134 | OPTIONAL(line, LineField, ); \ |
| 6135 | REQUIRED(file, MDField, ); \ |
| 6136 | OPTIONAL(nodes, MDField, ); |
| 6137 | PARSE_MD_FIELDS(); |
| 6138 | #undef VISIT_MD_FIELDS |
| 6139 | |
| 6140 | Result = GET_OR_DISTINCT(DIMacroFile, |
| 6141 | (Context, type.Val, line.Val, file.Val, nodes.Val)); |
| 6142 | return false; |
| 6143 | } |
| 6144 | |
| 6145 | /// parseDIModule: |
| 6146 | /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: |
| 6147 | /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", |
| 6148 | /// file: !1, line: 4, isDecl: false) |
| 6149 | bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) { |
| 6150 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6151 | REQUIRED(scope, MDField, ); \ |
| 6152 | REQUIRED(name, MDStringField, ); \ |
| 6153 | OPTIONAL(configMacros, MDStringField, ); \ |
| 6154 | OPTIONAL(includePath, MDStringField, ); \ |
| 6155 | OPTIONAL(apinotes, MDStringField, ); \ |
| 6156 | OPTIONAL(file, MDField, ); \ |
| 6157 | OPTIONAL(line, LineField, ); \ |
| 6158 | OPTIONAL(isDecl, MDBoolField, ); |
| 6159 | PARSE_MD_FIELDS(); |
| 6160 | #undef VISIT_MD_FIELDS |
| 6161 | |
| 6162 | Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, |
| 6163 | configMacros.Val, includePath.Val, |
| 6164 | apinotes.Val, line.Val, isDecl.Val)); |
| 6165 | return false; |
| 6166 | } |
| 6167 | |
| 6168 | /// parseDITemplateTypeParameter: |
| 6169 | /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) |
| 6170 | bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { |
| 6171 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6172 | OPTIONAL(name, MDStringField, ); \ |
| 6173 | REQUIRED(type, MDField, ); \ |
| 6174 | OPTIONAL(defaulted, MDBoolField, ); |
| 6175 | PARSE_MD_FIELDS(); |
| 6176 | #undef VISIT_MD_FIELDS |
| 6177 | |
| 6178 | Result = GET_OR_DISTINCT(DITemplateTypeParameter, |
| 6179 | (Context, name.Val, type.Val, defaulted.Val)); |
| 6180 | return false; |
| 6181 | } |
| 6182 | |
| 6183 | /// parseDITemplateValueParameter: |
| 6184 | /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, |
| 6185 | /// name: "V", type: !1, defaulted: false, |
| 6186 | /// value: i32 7) |
| 6187 | bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { |
| 6188 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6189 | OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ |
| 6190 | OPTIONAL(name, MDStringField, ); \ |
| 6191 | OPTIONAL(type, MDField, ); \ |
| 6192 | OPTIONAL(defaulted, MDBoolField, ); \ |
| 6193 | REQUIRED(value, MDField, ); |
| 6194 | |
| 6195 | PARSE_MD_FIELDS(); |
| 6196 | #undef VISIT_MD_FIELDS |
| 6197 | |
| 6198 | Result = GET_OR_DISTINCT( |
| 6199 | DITemplateValueParameter, |
| 6200 | (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); |
| 6201 | return false; |
| 6202 | } |
| 6203 | |
| 6204 | /// parseDIGlobalVariable: |
| 6205 | /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", |
| 6206 | /// file: !1, line: 7, type: !2, isLocal: false, |
| 6207 | /// isDefinition: true, templateParams: !3, |
| 6208 | /// declaration: !4, align: 8) |
| 6209 | bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { |
| 6210 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6211 | OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \ |
| 6212 | OPTIONAL(scope, MDField, ); \ |
| 6213 | OPTIONAL(linkageName, MDStringField, ); \ |
| 6214 | OPTIONAL(file, MDField, ); \ |
| 6215 | OPTIONAL(line, LineField, ); \ |
| 6216 | OPTIONAL(type, MDField, ); \ |
| 6217 | OPTIONAL(isLocal, MDBoolField, ); \ |
| 6218 | OPTIONAL(isDefinition, MDBoolField, (true)); \ |
| 6219 | OPTIONAL(templateParams, MDField, ); \ |
| 6220 | OPTIONAL(declaration, MDField, ); \ |
| 6221 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 6222 | OPTIONAL(annotations, MDField, ); |
| 6223 | PARSE_MD_FIELDS(); |
| 6224 | #undef VISIT_MD_FIELDS |
| 6225 | |
| 6226 | Result = |
| 6227 | GET_OR_DISTINCT(DIGlobalVariable, |
| 6228 | (Context, scope.Val, name.Val, linkageName.Val, file.Val, |
| 6229 | line.Val, type.Val, isLocal.Val, isDefinition.Val, |
| 6230 | declaration.Val, templateParams.Val, align.Val, |
| 6231 | annotations.Val)); |
| 6232 | return false; |
| 6233 | } |
| 6234 | |
| 6235 | /// parseDILocalVariable: |
| 6236 | /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", |
| 6237 | /// file: !1, line: 7, type: !2, arg: 2, flags: 7, |
| 6238 | /// align: 8) |
| 6239 | /// ::= !DILocalVariable(scope: !0, name: "foo", |
| 6240 | /// file: !1, line: 7, type: !2, arg: 2, flags: 7, |
| 6241 | /// align: 8) |
| 6242 | bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) { |
| 6243 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6244 | REQUIRED(scope, MDField, (/* AllowNull */ false)); \ |
| 6245 | OPTIONAL(name, MDStringField, ); \ |
| 6246 | OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ |
| 6247 | OPTIONAL(file, MDField, ); \ |
| 6248 | OPTIONAL(line, LineField, ); \ |
| 6249 | OPTIONAL(type, MDField, ); \ |
| 6250 | OPTIONAL(flags, DIFlagField, ); \ |
| 6251 | OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ |
| 6252 | OPTIONAL(annotations, MDField, ); |
| 6253 | PARSE_MD_FIELDS(); |
| 6254 | #undef VISIT_MD_FIELDS |
| 6255 | |
| 6256 | Result = GET_OR_DISTINCT(DILocalVariable, |
| 6257 | (Context, scope.Val, name.Val, file.Val, line.Val, |
| 6258 | type.Val, arg.Val, flags.Val, align.Val, |
| 6259 | annotations.Val)); |
| 6260 | return false; |
| 6261 | } |
| 6262 | |
| 6263 | /// parseDILabel: |
| 6264 | /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4) |
| 6265 | bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) { |
| 6266 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6267 | REQUIRED(scope, MDField, (/* AllowNull */ false)); \ |
| 6268 | REQUIRED(name, MDStringField, ); \ |
| 6269 | REQUIRED(file, MDField, ); \ |
| 6270 | REQUIRED(line, LineField, ); \ |
| 6271 | OPTIONAL(column, ColumnField, ); \ |
| 6272 | OPTIONAL(isArtificial, MDBoolField, ); \ |
| 6273 | OPTIONAL(coroSuspendIdx, MDUnsignedField, ); |
| 6274 | PARSE_MD_FIELDS(); |
| 6275 | #undef VISIT_MD_FIELDS |
| 6276 | |
| 6277 | std::optional<unsigned> CoroSuspendIdx = |
| 6278 | coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val) |
| 6279 | : std::nullopt; |
| 6280 | |
| 6281 | Result = GET_OR_DISTINCT(DILabel, |
| 6282 | (Context, scope.Val, name.Val, file.Val, line.Val, |
| 6283 | column.Val, isArtificial.Val, CoroSuspendIdx)); |
| 6284 | return false; |
| 6285 | } |
| 6286 | |
| 6287 | /// parseDIExpressionBody: |
| 6288 | /// ::= (0, 7, -1) |
| 6289 | bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) { |
| 6290 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 6291 | return true; |
| 6292 | |
| 6293 | SmallVector<uint64_t, 8> Elements; |
| 6294 | if (Lex.getKind() != lltok::rparen) |
| 6295 | do { |
| 6296 | if (Lex.getKind() == lltok::DwarfOp) { |
| 6297 | if (unsigned Op = dwarf::getOperationEncoding(OperationEncodingString: Lex.getStrVal())) { |
| 6298 | Lex.Lex(); |
| 6299 | Elements.push_back(Elt: Op); |
| 6300 | continue; |
| 6301 | } |
| 6302 | return tokError(Msg: Twine("invalid DWARF op '" ) + Lex.getStrVal() + "'" ); |
| 6303 | } |
| 6304 | |
| 6305 | if (Lex.getKind() == lltok::DwarfAttEncoding) { |
| 6306 | if (unsigned Op = dwarf::getAttributeEncoding(EncodingString: Lex.getStrVal())) { |
| 6307 | Lex.Lex(); |
| 6308 | Elements.push_back(Elt: Op); |
| 6309 | continue; |
| 6310 | } |
| 6311 | return tokError(Msg: Twine("invalid DWARF attribute encoding '" ) + |
| 6312 | Lex.getStrVal() + "'" ); |
| 6313 | } |
| 6314 | |
| 6315 | if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) |
| 6316 | return tokError(Msg: "expected unsigned integer" ); |
| 6317 | |
| 6318 | auto &U = Lex.getAPSIntVal(); |
| 6319 | if (U.ugt(UINT64_MAX)) |
| 6320 | return tokError(Msg: "element too large, limit is " + Twine(UINT64_MAX)); |
| 6321 | Elements.push_back(Elt: U.getZExtValue()); |
| 6322 | Lex.Lex(); |
| 6323 | } while (EatIfPresent(T: lltok::comma)); |
| 6324 | |
| 6325 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 6326 | return true; |
| 6327 | |
| 6328 | Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); |
| 6329 | return false; |
| 6330 | } |
| 6331 | |
| 6332 | /// parseDIExpression: |
| 6333 | /// ::= !DIExpression(0, 7, -1) |
| 6334 | bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) { |
| 6335 | assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name" ); |
| 6336 | assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'" ); |
| 6337 | Lex.Lex(); |
| 6338 | |
| 6339 | return parseDIExpressionBody(Result, IsDistinct); |
| 6340 | } |
| 6341 | |
| 6342 | /// ParseDIArgList: |
| 6343 | /// ::= !DIArgList(i32 7, i64 %0) |
| 6344 | bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) { |
| 6345 | assert(PFS && "Expected valid function state" ); |
| 6346 | assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name" ); |
| 6347 | Lex.Lex(); |
| 6348 | |
| 6349 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 6350 | return true; |
| 6351 | |
| 6352 | SmallVector<ValueAsMetadata *, 4> Args; |
| 6353 | if (Lex.getKind() != lltok::rparen) |
| 6354 | do { |
| 6355 | Metadata *MD; |
| 6356 | if (parseValueAsMetadata(MD, TypeMsg: "expected value-as-metadata operand" , PFS)) |
| 6357 | return true; |
| 6358 | Args.push_back(Elt: dyn_cast<ValueAsMetadata>(Val: MD)); |
| 6359 | } while (EatIfPresent(T: lltok::comma)); |
| 6360 | |
| 6361 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 6362 | return true; |
| 6363 | |
| 6364 | MD = DIArgList::get(Context, Args); |
| 6365 | return false; |
| 6366 | } |
| 6367 | |
| 6368 | /// parseDIGlobalVariableExpression: |
| 6369 | /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) |
| 6370 | bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result, |
| 6371 | bool IsDistinct) { |
| 6372 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6373 | REQUIRED(var, MDField, ); \ |
| 6374 | REQUIRED(expr, MDField, ); |
| 6375 | PARSE_MD_FIELDS(); |
| 6376 | #undef VISIT_MD_FIELDS |
| 6377 | |
| 6378 | Result = |
| 6379 | GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); |
| 6380 | return false; |
| 6381 | } |
| 6382 | |
| 6383 | /// parseDIObjCProperty: |
| 6384 | /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", |
| 6385 | /// getter: "getFoo", attributes: 7, type: !2) |
| 6386 | bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) { |
| 6387 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6388 | OPTIONAL(name, MDStringField, ); \ |
| 6389 | OPTIONAL(file, MDField, ); \ |
| 6390 | OPTIONAL(line, LineField, ); \ |
| 6391 | OPTIONAL(setter, MDStringField, ); \ |
| 6392 | OPTIONAL(getter, MDStringField, ); \ |
| 6393 | OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ |
| 6394 | OPTIONAL(type, MDField, ); |
| 6395 | PARSE_MD_FIELDS(); |
| 6396 | #undef VISIT_MD_FIELDS |
| 6397 | |
| 6398 | Result = GET_OR_DISTINCT(DIObjCProperty, |
| 6399 | (Context, name.Val, file.Val, line.Val, getter.Val, |
| 6400 | setter.Val, attributes.Val, type.Val)); |
| 6401 | return false; |
| 6402 | } |
| 6403 | |
| 6404 | /// parseDIImportedEntity: |
| 6405 | /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, |
| 6406 | /// line: 7, name: "foo", elements: !2) |
| 6407 | bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) { |
| 6408 | #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ |
| 6409 | REQUIRED(tag, DwarfTagField, ); \ |
| 6410 | REQUIRED(scope, MDField, ); \ |
| 6411 | OPTIONAL(entity, MDField, ); \ |
| 6412 | OPTIONAL(file, MDField, ); \ |
| 6413 | OPTIONAL(line, LineField, ); \ |
| 6414 | OPTIONAL(name, MDStringField, ); \ |
| 6415 | OPTIONAL(elements, MDField, ); |
| 6416 | PARSE_MD_FIELDS(); |
| 6417 | #undef VISIT_MD_FIELDS |
| 6418 | |
| 6419 | Result = GET_OR_DISTINCT(DIImportedEntity, |
| 6420 | (Context, tag.Val, scope.Val, entity.Val, file.Val, |
| 6421 | line.Val, name.Val, elements.Val)); |
| 6422 | return false; |
| 6423 | } |
| 6424 | |
| 6425 | #undef PARSE_MD_FIELD |
| 6426 | #undef NOP_FIELD |
| 6427 | #undef REQUIRE_FIELD |
| 6428 | #undef DECLARE_FIELD |
| 6429 | |
| 6430 | /// parseMetadataAsValue |
| 6431 | /// ::= metadata i32 %local |
| 6432 | /// ::= metadata i32 @global |
| 6433 | /// ::= metadata i32 7 |
| 6434 | /// ::= metadata !0 |
| 6435 | /// ::= metadata !{...} |
| 6436 | /// ::= metadata !"string" |
| 6437 | bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) { |
| 6438 | // Note: the type 'metadata' has already been parsed. |
| 6439 | Metadata *MD; |
| 6440 | if (parseMetadata(MD, PFS: &PFS)) |
| 6441 | return true; |
| 6442 | |
| 6443 | V = MetadataAsValue::get(Context, MD); |
| 6444 | return false; |
| 6445 | } |
| 6446 | |
| 6447 | /// parseValueAsMetadata |
| 6448 | /// ::= i32 %local |
| 6449 | /// ::= i32 @global |
| 6450 | /// ::= i32 7 |
| 6451 | bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, |
| 6452 | PerFunctionState *PFS) { |
| 6453 | Type *Ty; |
| 6454 | LocTy Loc; |
| 6455 | if (parseType(Result&: Ty, Msg: TypeMsg, Loc)) |
| 6456 | return true; |
| 6457 | if (Ty->isMetadataTy()) |
| 6458 | return error(L: Loc, Msg: "invalid metadata-value-metadata roundtrip" ); |
| 6459 | |
| 6460 | Value *V; |
| 6461 | if (parseValue(Ty, V, PFS)) |
| 6462 | return true; |
| 6463 | |
| 6464 | MD = ValueAsMetadata::get(V); |
| 6465 | return false; |
| 6466 | } |
| 6467 | |
| 6468 | /// parseMetadata |
| 6469 | /// ::= i32 %local |
| 6470 | /// ::= i32 @global |
| 6471 | /// ::= i32 7 |
| 6472 | /// ::= !42 |
| 6473 | /// ::= !{...} |
| 6474 | /// ::= !"string" |
| 6475 | /// ::= !DILocation(...) |
| 6476 | bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) { |
| 6477 | if (Lex.getKind() == lltok::MetadataVar) { |
| 6478 | // DIArgLists are a special case, as they are a list of ValueAsMetadata and |
| 6479 | // so parsing this requires a Function State. |
| 6480 | if (Lex.getStrVal() == "DIArgList" ) { |
| 6481 | Metadata *AL; |
| 6482 | if (parseDIArgList(MD&: AL, PFS)) |
| 6483 | return true; |
| 6484 | MD = AL; |
| 6485 | return false; |
| 6486 | } |
| 6487 | MDNode *N; |
| 6488 | if (parseSpecializedMDNode(N)) { |
| 6489 | return true; |
| 6490 | } |
| 6491 | MD = N; |
| 6492 | return false; |
| 6493 | } |
| 6494 | |
| 6495 | // ValueAsMetadata: |
| 6496 | // <type> <value> |
| 6497 | if (Lex.getKind() != lltok::exclaim) |
| 6498 | return parseValueAsMetadata(MD, TypeMsg: "expected metadata operand" , PFS); |
| 6499 | |
| 6500 | // '!'. |
| 6501 | assert(Lex.getKind() == lltok::exclaim && "Expected '!' here" ); |
| 6502 | Lex.Lex(); |
| 6503 | |
| 6504 | // MDString: |
| 6505 | // ::= '!' STRINGCONSTANT |
| 6506 | if (Lex.getKind() == lltok::StringConstant) { |
| 6507 | MDString *S; |
| 6508 | if (parseMDString(Result&: S)) |
| 6509 | return true; |
| 6510 | MD = S; |
| 6511 | return false; |
| 6512 | } |
| 6513 | |
| 6514 | // MDNode: |
| 6515 | // !{ ... } |
| 6516 | // !7 |
| 6517 | MDNode *N; |
| 6518 | if (parseMDNodeTail(N)) |
| 6519 | return true; |
| 6520 | MD = N; |
| 6521 | return false; |
| 6522 | } |
| 6523 | |
| 6524 | //===----------------------------------------------------------------------===// |
| 6525 | // Function Parsing. |
| 6526 | //===----------------------------------------------------------------------===// |
| 6527 | |
| 6528 | bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V, |
| 6529 | PerFunctionState *PFS) { |
| 6530 | if (Ty->isFunctionTy()) |
| 6531 | return error(L: ID.Loc, Msg: "functions are not values, refer to them as pointers" ); |
| 6532 | |
| 6533 | switch (ID.Kind) { |
| 6534 | case ValID::t_LocalID: |
| 6535 | if (!PFS) |
| 6536 | return error(L: ID.Loc, Msg: "invalid use of function-local name" ); |
| 6537 | V = PFS->getVal(ID: ID.UIntVal, Ty, Loc: ID.Loc); |
| 6538 | return V == nullptr; |
| 6539 | case ValID::t_LocalName: |
| 6540 | if (!PFS) |
| 6541 | return error(L: ID.Loc, Msg: "invalid use of function-local name" ); |
| 6542 | V = PFS->getVal(Name: ID.StrVal, Ty, Loc: ID.Loc); |
| 6543 | return V == nullptr; |
| 6544 | case ValID::t_InlineAsm: { |
| 6545 | if (!ID.FTy) |
| 6546 | return error(L: ID.Loc, Msg: "invalid type for inline asm constraint string" ); |
| 6547 | if (Error Err = InlineAsm::verify(Ty: ID.FTy, Constraints: ID.StrVal2)) |
| 6548 | return error(L: ID.Loc, Msg: toString(E: std::move(Err))); |
| 6549 | V = InlineAsm::get( |
| 6550 | Ty: ID.FTy, AsmString: ID.StrVal, Constraints: ID.StrVal2, hasSideEffects: ID.UIntVal & 1, isAlignStack: (ID.UIntVal >> 1) & 1, |
| 6551 | asmDialect: InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), canThrow: (ID.UIntVal >> 3) & 1); |
| 6552 | return false; |
| 6553 | } |
| 6554 | case ValID::t_GlobalName: |
| 6555 | V = getGlobalVal(Name: ID.StrVal, Ty, Loc: ID.Loc); |
| 6556 | if (V && ID.NoCFI) |
| 6557 | V = NoCFIValue::get(GV: cast<GlobalValue>(Val: V)); |
| 6558 | return V == nullptr; |
| 6559 | case ValID::t_GlobalID: |
| 6560 | V = getGlobalVal(ID: ID.UIntVal, Ty, Loc: ID.Loc); |
| 6561 | if (V && ID.NoCFI) |
| 6562 | V = NoCFIValue::get(GV: cast<GlobalValue>(Val: V)); |
| 6563 | return V == nullptr; |
| 6564 | case ValID::t_APSInt: |
| 6565 | if (!Ty->isIntegerTy()) |
| 6566 | return error(L: ID.Loc, Msg: "integer constant must have integer type" ); |
| 6567 | ID.APSIntVal = ID.APSIntVal.extOrTrunc(width: Ty->getPrimitiveSizeInBits()); |
| 6568 | V = ConstantInt::get(Context, V: ID.APSIntVal); |
| 6569 | return false; |
| 6570 | case ValID::t_APFloat: |
| 6571 | if (!Ty->isFloatingPointTy() || |
| 6572 | !ConstantFP::isValueValidForType(Ty, V: ID.APFloatVal)) |
| 6573 | return error(L: ID.Loc, Msg: "floating point constant invalid for type" ); |
| 6574 | |
| 6575 | // The lexer has no type info, so builds all half, bfloat, float, and double |
| 6576 | // FP constants as double. Fix this here. Long double does not need this. |
| 6577 | if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { |
| 6578 | // Check for signaling before potentially converting and losing that info. |
| 6579 | bool IsSNAN = ID.APFloatVal.isSignaling(); |
| 6580 | bool Ignored; |
| 6581 | if (Ty->isHalfTy()) |
| 6582 | ID.APFloatVal.convert(ToSemantics: APFloat::IEEEhalf(), RM: APFloat::rmNearestTiesToEven, |
| 6583 | losesInfo: &Ignored); |
| 6584 | else if (Ty->isBFloatTy()) |
| 6585 | ID.APFloatVal.convert(ToSemantics: APFloat::BFloat(), RM: APFloat::rmNearestTiesToEven, |
| 6586 | losesInfo: &Ignored); |
| 6587 | else if (Ty->isFloatTy()) |
| 6588 | ID.APFloatVal.convert(ToSemantics: APFloat::IEEEsingle(), RM: APFloat::rmNearestTiesToEven, |
| 6589 | losesInfo: &Ignored); |
| 6590 | if (IsSNAN) { |
| 6591 | // The convert call above may quiet an SNaN, so manufacture another |
| 6592 | // SNaN. The bitcast works because the payload (significand) parameter |
| 6593 | // is truncated to fit. |
| 6594 | APInt Payload = ID.APFloatVal.bitcastToAPInt(); |
| 6595 | ID.APFloatVal = APFloat::getSNaN(Sem: ID.APFloatVal.getSemantics(), |
| 6596 | Negative: ID.APFloatVal.isNegative(), payload: &Payload); |
| 6597 | } |
| 6598 | } |
| 6599 | V = ConstantFP::get(Context, V: ID.APFloatVal); |
| 6600 | |
| 6601 | if (V->getType() != Ty) |
| 6602 | return error(L: ID.Loc, Msg: "floating point constant does not have type '" + |
| 6603 | getTypeString(T: Ty) + "'" ); |
| 6604 | |
| 6605 | return false; |
| 6606 | case ValID::t_Null: |
| 6607 | if (!Ty->isPointerTy()) |
| 6608 | return error(L: ID.Loc, Msg: "null must be a pointer type" ); |
| 6609 | V = ConstantPointerNull::get(T: cast<PointerType>(Val: Ty)); |
| 6610 | return false; |
| 6611 | case ValID::t_Undef: |
| 6612 | // FIXME: LabelTy should not be a first-class type. |
| 6613 | if (!Ty->isFirstClassType() || Ty->isLabelTy()) |
| 6614 | return error(L: ID.Loc, Msg: "invalid type for undef constant" ); |
| 6615 | V = UndefValue::get(T: Ty); |
| 6616 | return false; |
| 6617 | case ValID::t_EmptyArray: |
| 6618 | if (!Ty->isArrayTy() || cast<ArrayType>(Val: Ty)->getNumElements() != 0) |
| 6619 | return error(L: ID.Loc, Msg: "invalid empty array initializer" ); |
| 6620 | V = PoisonValue::get(T: Ty); |
| 6621 | return false; |
| 6622 | case ValID::t_Zero: |
| 6623 | // FIXME: LabelTy should not be a first-class type. |
| 6624 | if (!Ty->isFirstClassType() || Ty->isLabelTy()) |
| 6625 | return error(L: ID.Loc, Msg: "invalid type for null constant" ); |
| 6626 | if (auto *TETy = dyn_cast<TargetExtType>(Val: Ty)) |
| 6627 | if (!TETy->hasProperty(Prop: TargetExtType::HasZeroInit)) |
| 6628 | return error(L: ID.Loc, Msg: "invalid type for null constant" ); |
| 6629 | V = Constant::getNullValue(Ty); |
| 6630 | return false; |
| 6631 | case ValID::t_None: |
| 6632 | if (!Ty->isTokenTy()) |
| 6633 | return error(L: ID.Loc, Msg: "invalid type for none constant" ); |
| 6634 | V = Constant::getNullValue(Ty); |
| 6635 | return false; |
| 6636 | case ValID::t_Poison: |
| 6637 | // FIXME: LabelTy should not be a first-class type. |
| 6638 | if (!Ty->isFirstClassType() || Ty->isLabelTy()) |
| 6639 | return error(L: ID.Loc, Msg: "invalid type for poison constant" ); |
| 6640 | V = PoisonValue::get(T: Ty); |
| 6641 | return false; |
| 6642 | case ValID::t_Constant: |
| 6643 | if (ID.ConstantVal->getType() != Ty) |
| 6644 | return error(L: ID.Loc, Msg: "constant expression type mismatch: got type '" + |
| 6645 | getTypeString(T: ID.ConstantVal->getType()) + |
| 6646 | "' but expected '" + getTypeString(T: Ty) + "'" ); |
| 6647 | V = ID.ConstantVal; |
| 6648 | return false; |
| 6649 | case ValID::t_ConstantSplat: |
| 6650 | if (!Ty->isVectorTy()) |
| 6651 | return error(L: ID.Loc, Msg: "vector constant must have vector type" ); |
| 6652 | if (ID.ConstantVal->getType() != Ty->getScalarType()) |
| 6653 | return error(L: ID.Loc, Msg: "constant expression type mismatch: got type '" + |
| 6654 | getTypeString(T: ID.ConstantVal->getType()) + |
| 6655 | "' but expected '" + |
| 6656 | getTypeString(T: Ty->getScalarType()) + "'" ); |
| 6657 | V = ConstantVector::getSplat(EC: cast<VectorType>(Val: Ty)->getElementCount(), |
| 6658 | Elt: ID.ConstantVal); |
| 6659 | return false; |
| 6660 | case ValID::t_ConstantStruct: |
| 6661 | case ValID::t_PackedConstantStruct: |
| 6662 | if (StructType *ST = dyn_cast<StructType>(Val: Ty)) { |
| 6663 | if (ST->getNumElements() != ID.UIntVal) |
| 6664 | return error(L: ID.Loc, |
| 6665 | Msg: "initializer with struct type has wrong # elements" ); |
| 6666 | if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) |
| 6667 | return error(L: ID.Loc, Msg: "packed'ness of initializer and type don't match" ); |
| 6668 | |
| 6669 | // Verify that the elements are compatible with the structtype. |
| 6670 | for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) |
| 6671 | if (ID.ConstantStructElts[i]->getType() != ST->getElementType(N: i)) |
| 6672 | return error( |
| 6673 | L: ID.Loc, |
| 6674 | Msg: "element " + Twine(i) + |
| 6675 | " of struct initializer doesn't match struct element type" ); |
| 6676 | |
| 6677 | V = ConstantStruct::get( |
| 6678 | T: ST, V: ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); |
| 6679 | } else |
| 6680 | return error(L: ID.Loc, Msg: "constant expression type mismatch" ); |
| 6681 | return false; |
| 6682 | } |
| 6683 | llvm_unreachable("Invalid ValID" ); |
| 6684 | } |
| 6685 | |
| 6686 | bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { |
| 6687 | C = nullptr; |
| 6688 | ValID ID; |
| 6689 | auto Loc = Lex.getLoc(); |
| 6690 | if (parseValID(ID, /*PFS=*/nullptr)) |
| 6691 | return true; |
| 6692 | switch (ID.Kind) { |
| 6693 | case ValID::t_APSInt: |
| 6694 | case ValID::t_APFloat: |
| 6695 | case ValID::t_Undef: |
| 6696 | case ValID::t_Poison: |
| 6697 | case ValID::t_Zero: |
| 6698 | case ValID::t_Constant: |
| 6699 | case ValID::t_ConstantSplat: |
| 6700 | case ValID::t_ConstantStruct: |
| 6701 | case ValID::t_PackedConstantStruct: { |
| 6702 | Value *V; |
| 6703 | if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr)) |
| 6704 | return true; |
| 6705 | assert(isa<Constant>(V) && "Expected a constant value" ); |
| 6706 | C = cast<Constant>(Val: V); |
| 6707 | return false; |
| 6708 | } |
| 6709 | case ValID::t_Null: |
| 6710 | C = Constant::getNullValue(Ty); |
| 6711 | return false; |
| 6712 | default: |
| 6713 | return error(L: Loc, Msg: "expected a constant value" ); |
| 6714 | } |
| 6715 | } |
| 6716 | |
| 6717 | bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { |
| 6718 | V = nullptr; |
| 6719 | ValID ID; |
| 6720 | |
| 6721 | FileLoc Start = Lex.getTokLineColumnPos(); |
| 6722 | bool Ret = parseValID(ID, PFS, ExpectedTy: Ty) || convertValIDToValue(Ty, ID, V, PFS); |
| 6723 | FileLoc End = Lex.getPrevTokEndLineColumnPos(); |
| 6724 | if (!Ret && ParserContext) |
| 6725 | ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End)); |
| 6726 | return Ret; |
| 6727 | } |
| 6728 | |
| 6729 | bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { |
| 6730 | Type *Ty = nullptr; |
| 6731 | return parseType(Result&: Ty) || parseValue(Ty, V, PFS); |
| 6732 | } |
| 6733 | |
| 6734 | bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, |
| 6735 | PerFunctionState &PFS) { |
| 6736 | Value *V; |
| 6737 | Loc = Lex.getLoc(); |
| 6738 | if (parseTypeAndValue(V, PFS)) |
| 6739 | return true; |
| 6740 | if (!isa<BasicBlock>(Val: V)) |
| 6741 | return error(L: Loc, Msg: "expected a basic block" ); |
| 6742 | BB = cast<BasicBlock>(Val: V); |
| 6743 | return false; |
| 6744 | } |
| 6745 | |
| 6746 | bool isOldDbgFormatIntrinsic(StringRef Name) { |
| 6747 | // Exit early for the common (non-debug-intrinsic) case. |
| 6748 | // We can make this the only check when we begin supporting all "llvm.dbg" |
| 6749 | // intrinsics in the new debug info format. |
| 6750 | if (!Name.starts_with(Prefix: "llvm.dbg." )) |
| 6751 | return false; |
| 6752 | Intrinsic::ID FnID = Intrinsic::lookupIntrinsicID(Name); |
| 6753 | return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value || |
| 6754 | FnID == Intrinsic::dbg_assign; |
| 6755 | } |
| 6756 | |
| 6757 | /// FunctionHeader |
| 6758 | /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility |
| 6759 | /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName |
| 6760 | /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign |
| 6761 | /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn |
| 6762 | bool LLParser::(Function *&Fn, bool IsDefine, |
| 6763 | unsigned &FunctionNumber, |
| 6764 | SmallVectorImpl<unsigned> &UnnamedArgNums) { |
| 6765 | // parse the linkage. |
| 6766 | LocTy LinkageLoc = Lex.getLoc(); |
| 6767 | unsigned Linkage; |
| 6768 | unsigned Visibility; |
| 6769 | unsigned DLLStorageClass; |
| 6770 | bool DSOLocal; |
| 6771 | AttrBuilder RetAttrs(M->getContext()); |
| 6772 | unsigned CC; |
| 6773 | bool HasLinkage; |
| 6774 | Type *RetType = nullptr; |
| 6775 | LocTy RetTypeLoc = Lex.getLoc(); |
| 6776 | if (parseOptionalLinkage(Res&: Linkage, HasLinkage, Visibility, DLLStorageClass, |
| 6777 | DSOLocal) || |
| 6778 | parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) || |
| 6779 | parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/)) |
| 6780 | return true; |
| 6781 | |
| 6782 | // Verify that the linkage is ok. |
| 6783 | switch ((GlobalValue::LinkageTypes)Linkage) { |
| 6784 | case GlobalValue::ExternalLinkage: |
| 6785 | break; // always ok. |
| 6786 | case GlobalValue::ExternalWeakLinkage: |
| 6787 | if (IsDefine) |
| 6788 | return error(L: LinkageLoc, Msg: "invalid linkage for function definition" ); |
| 6789 | break; |
| 6790 | case GlobalValue::PrivateLinkage: |
| 6791 | case GlobalValue::InternalLinkage: |
| 6792 | case GlobalValue::AvailableExternallyLinkage: |
| 6793 | case GlobalValue::LinkOnceAnyLinkage: |
| 6794 | case GlobalValue::LinkOnceODRLinkage: |
| 6795 | case GlobalValue::WeakAnyLinkage: |
| 6796 | case GlobalValue::WeakODRLinkage: |
| 6797 | if (!IsDefine) |
| 6798 | return error(L: LinkageLoc, Msg: "invalid linkage for function declaration" ); |
| 6799 | break; |
| 6800 | case GlobalValue::AppendingLinkage: |
| 6801 | case GlobalValue::CommonLinkage: |
| 6802 | return error(L: LinkageLoc, Msg: "invalid function linkage type" ); |
| 6803 | } |
| 6804 | |
| 6805 | if (!isValidVisibilityForLinkage(V: Visibility, L: Linkage)) |
| 6806 | return error(L: LinkageLoc, |
| 6807 | Msg: "symbol with local linkage must have default visibility" ); |
| 6808 | |
| 6809 | if (!isValidDLLStorageClassForLinkage(S: DLLStorageClass, L: Linkage)) |
| 6810 | return error(L: LinkageLoc, |
| 6811 | Msg: "symbol with local linkage cannot have a DLL storage class" ); |
| 6812 | |
| 6813 | if (!FunctionType::isValidReturnType(RetTy: RetType)) |
| 6814 | return error(L: RetTypeLoc, Msg: "invalid function return type" ); |
| 6815 | |
| 6816 | LocTy NameLoc = Lex.getLoc(); |
| 6817 | |
| 6818 | std::string FunctionName; |
| 6819 | if (Lex.getKind() == lltok::GlobalVar) { |
| 6820 | FunctionName = Lex.getStrVal(); |
| 6821 | } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. |
| 6822 | FunctionNumber = Lex.getUIntVal(); |
| 6823 | if (checkValueID(Loc: NameLoc, Kind: "function" , Prefix: "@" , NextID: NumberedVals.getNext(), |
| 6824 | ID: FunctionNumber)) |
| 6825 | return true; |
| 6826 | } else { |
| 6827 | return tokError(Msg: "expected function name" ); |
| 6828 | } |
| 6829 | |
| 6830 | Lex.Lex(); |
| 6831 | |
| 6832 | if (Lex.getKind() != lltok::lparen) |
| 6833 | return tokError(Msg: "expected '(' in function argument list" ); |
| 6834 | |
| 6835 | SmallVector<ArgInfo, 8> ArgList; |
| 6836 | bool IsVarArg; |
| 6837 | AttrBuilder FuncAttrs(M->getContext()); |
| 6838 | std::vector<unsigned> FwdRefAttrGrps; |
| 6839 | LocTy BuiltinLoc; |
| 6840 | std::string Section; |
| 6841 | std::string Partition; |
| 6842 | MaybeAlign Alignment; |
| 6843 | std::string GC; |
| 6844 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; |
| 6845 | unsigned AddrSpace = 0; |
| 6846 | Constant *Prefix = nullptr; |
| 6847 | Constant *Prologue = nullptr; |
| 6848 | Constant *PersonalityFn = nullptr; |
| 6849 | Comdat *C; |
| 6850 | |
| 6851 | if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) || |
| 6852 | parseOptionalUnnamedAddr(UnnamedAddr) || |
| 6853 | parseOptionalProgramAddrSpace(AddrSpace) || |
| 6854 | parseFnAttributeValuePairs(B&: FuncAttrs, FwdRefAttrGrps, InAttrGrp: false, |
| 6855 | BuiltinLoc) || |
| 6856 | (EatIfPresent(T: lltok::kw_section) && parseStringConstant(Result&: Section)) || |
| 6857 | (EatIfPresent(T: lltok::kw_partition) && parseStringConstant(Result&: Partition)) || |
| 6858 | parseOptionalComdat(GlobalName: FunctionName, C) || |
| 6859 | parseOptionalAlignment(Alignment) || |
| 6860 | (EatIfPresent(T: lltok::kw_gc) && parseStringConstant(Result&: GC)) || |
| 6861 | (EatIfPresent(T: lltok::kw_prefix) && parseGlobalTypeAndValue(V&: Prefix)) || |
| 6862 | (EatIfPresent(T: lltok::kw_prologue) && parseGlobalTypeAndValue(V&: Prologue)) || |
| 6863 | (EatIfPresent(T: lltok::kw_personality) && |
| 6864 | parseGlobalTypeAndValue(V&: PersonalityFn))) |
| 6865 | return true; |
| 6866 | |
| 6867 | if (FuncAttrs.contains(A: Attribute::Builtin)) |
| 6868 | return error(L: BuiltinLoc, Msg: "'builtin' attribute not valid on function" ); |
| 6869 | |
| 6870 | // If the alignment was parsed as an attribute, move to the alignment field. |
| 6871 | if (MaybeAlign A = FuncAttrs.getAlignment()) { |
| 6872 | Alignment = A; |
| 6873 | FuncAttrs.removeAttribute(Val: Attribute::Alignment); |
| 6874 | } |
| 6875 | |
| 6876 | // Okay, if we got here, the function is syntactically valid. Convert types |
| 6877 | // and do semantic checks. |
| 6878 | std::vector<Type*> ParamTypeList; |
| 6879 | SmallVector<AttributeSet, 8> Attrs; |
| 6880 | |
| 6881 | for (const ArgInfo &Arg : ArgList) { |
| 6882 | ParamTypeList.push_back(x: Arg.Ty); |
| 6883 | Attrs.push_back(Elt: Arg.Attrs); |
| 6884 | } |
| 6885 | |
| 6886 | AttributeList PAL = |
| 6887 | AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FuncAttrs), |
| 6888 | RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs: Attrs); |
| 6889 | |
| 6890 | if (PAL.hasParamAttr(ArgNo: 0, Kind: Attribute::StructRet) && !RetType->isVoidTy()) |
| 6891 | return error(L: RetTypeLoc, Msg: "functions with 'sret' argument must return void" ); |
| 6892 | |
| 6893 | FunctionType *FT = FunctionType::get(Result: RetType, Params: ParamTypeList, isVarArg: IsVarArg); |
| 6894 | PointerType *PFT = PointerType::get(C&: Context, AddressSpace: AddrSpace); |
| 6895 | |
| 6896 | Fn = nullptr; |
| 6897 | GlobalValue *FwdFn = nullptr; |
| 6898 | if (!FunctionName.empty()) { |
| 6899 | // If this was a definition of a forward reference, remove the definition |
| 6900 | // from the forward reference table and fill in the forward ref. |
| 6901 | auto FRVI = ForwardRefVals.find(x: FunctionName); |
| 6902 | if (FRVI != ForwardRefVals.end()) { |
| 6903 | FwdFn = FRVI->second.first; |
| 6904 | if (FwdFn->getType() != PFT) |
| 6905 | return error(L: FRVI->second.second, |
| 6906 | Msg: "invalid forward reference to " |
| 6907 | "function '" + |
| 6908 | FunctionName + |
| 6909 | "' with wrong type: " |
| 6910 | "expected '" + |
| 6911 | getTypeString(T: PFT) + "' but was '" + |
| 6912 | getTypeString(T: FwdFn->getType()) + "'" ); |
| 6913 | ForwardRefVals.erase(position: FRVI); |
| 6914 | } else if ((Fn = M->getFunction(Name: FunctionName))) { |
| 6915 | // Reject redefinitions. |
| 6916 | return error(L: NameLoc, |
| 6917 | Msg: "invalid redefinition of function '" + FunctionName + "'" ); |
| 6918 | } else if (M->getNamedValue(Name: FunctionName)) { |
| 6919 | return error(L: NameLoc, Msg: "redefinition of function '@" + FunctionName + "'" ); |
| 6920 | } |
| 6921 | |
| 6922 | } else { |
| 6923 | // Handle @"", where a name is syntactically specified, but semantically |
| 6924 | // missing. |
| 6925 | if (FunctionNumber == (unsigned)-1) |
| 6926 | FunctionNumber = NumberedVals.getNext(); |
| 6927 | |
| 6928 | // If this is a definition of a forward referenced function, make sure the |
| 6929 | // types agree. |
| 6930 | auto I = ForwardRefValIDs.find(x: FunctionNumber); |
| 6931 | if (I != ForwardRefValIDs.end()) { |
| 6932 | FwdFn = I->second.first; |
| 6933 | if (FwdFn->getType() != PFT) |
| 6934 | return error(L: NameLoc, Msg: "type of definition and forward reference of '@" + |
| 6935 | Twine(FunctionNumber) + |
| 6936 | "' disagree: " |
| 6937 | "expected '" + |
| 6938 | getTypeString(T: PFT) + "' but was '" + |
| 6939 | getTypeString(T: FwdFn->getType()) + "'" ); |
| 6940 | ForwardRefValIDs.erase(position: I); |
| 6941 | } |
| 6942 | } |
| 6943 | |
| 6944 | Fn = Function::Create(Ty: FT, Linkage: GlobalValue::ExternalLinkage, AddrSpace, |
| 6945 | N: FunctionName, M); |
| 6946 | |
| 6947 | assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS" ); |
| 6948 | |
| 6949 | if (FunctionName.empty()) |
| 6950 | NumberedVals.add(ID: FunctionNumber, V: Fn); |
| 6951 | |
| 6952 | Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); |
| 6953 | maybeSetDSOLocal(DSOLocal, GV&: *Fn); |
| 6954 | Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); |
| 6955 | Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); |
| 6956 | Fn->setCallingConv(CC); |
| 6957 | Fn->setAttributes(PAL); |
| 6958 | Fn->setUnnamedAddr(UnnamedAddr); |
| 6959 | if (Alignment) |
| 6960 | Fn->setAlignment(*Alignment); |
| 6961 | Fn->setSection(Section); |
| 6962 | Fn->setPartition(Partition); |
| 6963 | Fn->setComdat(C); |
| 6964 | Fn->setPersonalityFn(PersonalityFn); |
| 6965 | if (!GC.empty()) Fn->setGC(GC); |
| 6966 | Fn->setPrefixData(Prefix); |
| 6967 | Fn->setPrologueData(Prologue); |
| 6968 | ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; |
| 6969 | |
| 6970 | // Add all of the arguments we parsed to the function. |
| 6971 | Function::arg_iterator ArgIt = Fn->arg_begin(); |
| 6972 | for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { |
| 6973 | if (ParserContext && ArgList[i].IdentLoc) |
| 6974 | ParserContext->addInstructionOrArgumentLocation( |
| 6975 | &*ArgIt, ArgList[i].IdentLoc.value()); |
| 6976 | // If the argument has a name, insert it into the argument symbol table. |
| 6977 | if (ArgList[i].Name.empty()) continue; |
| 6978 | |
| 6979 | // Set the name, if it conflicted, it will be auto-renamed. |
| 6980 | ArgIt->setName(ArgList[i].Name); |
| 6981 | |
| 6982 | if (ArgIt->getName() != ArgList[i].Name) |
| 6983 | return error(L: ArgList[i].Loc, |
| 6984 | Msg: "redefinition of argument '%" + ArgList[i].Name + "'" ); |
| 6985 | } |
| 6986 | |
| 6987 | if (FwdFn) { |
| 6988 | FwdFn->replaceAllUsesWith(V: Fn); |
| 6989 | FwdFn->eraseFromParent(); |
| 6990 | } |
| 6991 | |
| 6992 | if (IsDefine) |
| 6993 | return false; |
| 6994 | |
| 6995 | // Check the declaration has no block address forward references. |
| 6996 | ValID ID; |
| 6997 | if (FunctionName.empty()) { |
| 6998 | ID.Kind = ValID::t_GlobalID; |
| 6999 | ID.UIntVal = FunctionNumber; |
| 7000 | } else { |
| 7001 | ID.Kind = ValID::t_GlobalName; |
| 7002 | ID.StrVal = FunctionName; |
| 7003 | } |
| 7004 | auto Blocks = ForwardRefBlockAddresses.find(x: ID); |
| 7005 | if (Blocks != ForwardRefBlockAddresses.end()) |
| 7006 | return error(L: Blocks->first.Loc, |
| 7007 | Msg: "cannot take blockaddress inside a declaration" ); |
| 7008 | return false; |
| 7009 | } |
| 7010 | |
| 7011 | bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { |
| 7012 | ValID ID; |
| 7013 | if (FunctionNumber == -1) { |
| 7014 | ID.Kind = ValID::t_GlobalName; |
| 7015 | ID.StrVal = std::string(F.getName()); |
| 7016 | } else { |
| 7017 | ID.Kind = ValID::t_GlobalID; |
| 7018 | ID.UIntVal = FunctionNumber; |
| 7019 | } |
| 7020 | |
| 7021 | auto Blocks = P.ForwardRefBlockAddresses.find(x: ID); |
| 7022 | if (Blocks == P.ForwardRefBlockAddresses.end()) |
| 7023 | return false; |
| 7024 | |
| 7025 | for (const auto &I : Blocks->second) { |
| 7026 | const ValID &BBID = I.first; |
| 7027 | GlobalValue *GV = I.second; |
| 7028 | |
| 7029 | assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && |
| 7030 | "Expected local id or name" ); |
| 7031 | BasicBlock *BB; |
| 7032 | if (BBID.Kind == ValID::t_LocalName) |
| 7033 | BB = getBB(Name: BBID.StrVal, Loc: BBID.Loc); |
| 7034 | else |
| 7035 | BB = getBB(ID: BBID.UIntVal, Loc: BBID.Loc); |
| 7036 | if (!BB) |
| 7037 | return P.error(L: BBID.Loc, Msg: "referenced value is not a basic block" ); |
| 7038 | |
| 7039 | Value *ResolvedVal = BlockAddress::get(F: &F, BB); |
| 7040 | ResolvedVal = P.checkValidVariableType(Loc: BBID.Loc, Name: BBID.StrVal, Ty: GV->getType(), |
| 7041 | Val: ResolvedVal); |
| 7042 | if (!ResolvedVal) |
| 7043 | return true; |
| 7044 | GV->replaceAllUsesWith(V: ResolvedVal); |
| 7045 | GV->eraseFromParent(); |
| 7046 | } |
| 7047 | |
| 7048 | P.ForwardRefBlockAddresses.erase(position: Blocks); |
| 7049 | return false; |
| 7050 | } |
| 7051 | |
| 7052 | /// parseFunctionBody |
| 7053 | /// ::= '{' BasicBlock+ UseListOrderDirective* '}' |
| 7054 | bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber, |
| 7055 | ArrayRef<unsigned> UnnamedArgNums) { |
| 7056 | if (Lex.getKind() != lltok::lbrace) |
| 7057 | return tokError(Msg: "expected '{' in function body" ); |
| 7058 | Lex.Lex(); // eat the {. |
| 7059 | |
| 7060 | PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums); |
| 7061 | |
| 7062 | // Resolve block addresses and allow basic blocks to be forward-declared |
| 7063 | // within this function. |
| 7064 | if (PFS.resolveForwardRefBlockAddresses()) |
| 7065 | return true; |
| 7066 | SaveAndRestore ScopeExit(BlockAddressPFS, &PFS); |
| 7067 | |
| 7068 | // We need at least one basic block. |
| 7069 | if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) |
| 7070 | return tokError(Msg: "function body requires at least one basic block" ); |
| 7071 | |
| 7072 | while (Lex.getKind() != lltok::rbrace && |
| 7073 | Lex.getKind() != lltok::kw_uselistorder) |
| 7074 | if (parseBasicBlock(PFS)) |
| 7075 | return true; |
| 7076 | |
| 7077 | while (Lex.getKind() != lltok::rbrace) |
| 7078 | if (parseUseListOrder(PFS: &PFS)) |
| 7079 | return true; |
| 7080 | |
| 7081 | // Eat the }. |
| 7082 | Lex.Lex(); |
| 7083 | |
| 7084 | // Verify function is ok. |
| 7085 | return PFS.finishFunction(); |
| 7086 | } |
| 7087 | |
| 7088 | /// parseBasicBlock |
| 7089 | /// ::= (LabelStr|LabelID)? Instruction* |
| 7090 | bool LLParser::parseBasicBlock(PerFunctionState &PFS) { |
| 7091 | FileLoc BBStart(Lex.getTokLineColumnPos()); |
| 7092 | |
| 7093 | // If this basic block starts out with a name, remember it. |
| 7094 | std::string Name; |
| 7095 | int NameID = -1; |
| 7096 | LocTy NameLoc = Lex.getLoc(); |
| 7097 | if (Lex.getKind() == lltok::LabelStr) { |
| 7098 | Name = Lex.getStrVal(); |
| 7099 | Lex.Lex(); |
| 7100 | } else if (Lex.getKind() == lltok::LabelID) { |
| 7101 | NameID = Lex.getUIntVal(); |
| 7102 | Lex.Lex(); |
| 7103 | } |
| 7104 | |
| 7105 | BasicBlock *BB = PFS.defineBB(Name, NameID, Loc: NameLoc); |
| 7106 | if (!BB) |
| 7107 | return true; |
| 7108 | |
| 7109 | std::string NameStr; |
| 7110 | |
| 7111 | // Parse the instructions and debug values in this block until we get a |
| 7112 | // terminator. |
| 7113 | Instruction *Inst; |
| 7114 | auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); }; |
| 7115 | using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>; |
| 7116 | SmallVector<DbgRecordPtr> TrailingDbgRecord; |
| 7117 | do { |
| 7118 | // Handle debug records first - there should always be an instruction |
| 7119 | // following the debug records, i.e. they cannot appear after the block |
| 7120 | // terminator. |
| 7121 | while (Lex.getKind() == lltok::hash) { |
| 7122 | if (SeenOldDbgInfoFormat) |
| 7123 | return error(L: Lex.getLoc(), Msg: "debug record should not appear in a module " |
| 7124 | "containing debug info intrinsics" ); |
| 7125 | SeenNewDbgInfoFormat = true; |
| 7126 | Lex.Lex(); |
| 7127 | |
| 7128 | DbgRecord *DR; |
| 7129 | if (parseDebugRecord(DR, PFS)) |
| 7130 | return true; |
| 7131 | TrailingDbgRecord.emplace_back(Args&: DR, Args&: DeleteDbgRecord); |
| 7132 | } |
| 7133 | |
| 7134 | FileLoc InstStart(Lex.getTokLineColumnPos()); |
| 7135 | // This instruction may have three possibilities for a name: a) none |
| 7136 | // specified, b) name specified "%foo =", c) number specified: "%4 =". |
| 7137 | LocTy NameLoc = Lex.getLoc(); |
| 7138 | int NameID = -1; |
| 7139 | NameStr = "" ; |
| 7140 | |
| 7141 | if (Lex.getKind() == lltok::LocalVarID) { |
| 7142 | NameID = Lex.getUIntVal(); |
| 7143 | Lex.Lex(); |
| 7144 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after instruction id" )) |
| 7145 | return true; |
| 7146 | } else if (Lex.getKind() == lltok::LocalVar) { |
| 7147 | NameStr = Lex.getStrVal(); |
| 7148 | Lex.Lex(); |
| 7149 | if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after instruction name" )) |
| 7150 | return true; |
| 7151 | } |
| 7152 | |
| 7153 | switch (parseInstruction(Inst, BB, PFS)) { |
| 7154 | default: |
| 7155 | llvm_unreachable("Unknown parseInstruction result!" ); |
| 7156 | case InstError: return true; |
| 7157 | case InstNormal: |
| 7158 | Inst->insertInto(ParentBB: BB, It: BB->end()); |
| 7159 | |
| 7160 | // With a normal result, we check to see if the instruction is followed by |
| 7161 | // a comma and metadata. |
| 7162 | if (EatIfPresent(T: lltok::comma)) |
| 7163 | if (parseInstructionMetadata(Inst&: *Inst)) |
| 7164 | return true; |
| 7165 | break; |
| 7166 | case InstExtraComma: |
| 7167 | Inst->insertInto(ParentBB: BB, It: BB->end()); |
| 7168 | |
| 7169 | // If the instruction parser ate an extra comma at the end of it, it |
| 7170 | // *must* be followed by metadata. |
| 7171 | if (parseInstructionMetadata(Inst&: *Inst)) |
| 7172 | return true; |
| 7173 | break; |
| 7174 | } |
| 7175 | |
| 7176 | // Set the name on the instruction. |
| 7177 | if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) |
| 7178 | return true; |
| 7179 | |
| 7180 | // Attach any preceding debug values to this instruction. |
| 7181 | for (DbgRecordPtr &DR : TrailingDbgRecord) |
| 7182 | BB->insertDbgRecordBefore(DR: DR.release(), Here: Inst->getIterator()); |
| 7183 | TrailingDbgRecord.clear(); |
| 7184 | if (ParserContext) { |
| 7185 | ParserContext->addInstructionOrArgumentLocation( |
| 7186 | Inst, FileLocRange(InstStart, Lex.getPrevTokEndLineColumnPos())); |
| 7187 | } |
| 7188 | } while (!Inst->isTerminator()); |
| 7189 | |
| 7190 | if (ParserContext) |
| 7191 | ParserContext->addBlockLocation( |
| 7192 | BB, FileLocRange(BBStart, Lex.getPrevTokEndLineColumnPos())); |
| 7193 | |
| 7194 | assert(TrailingDbgRecord.empty() && |
| 7195 | "All debug values should have been attached to an instruction." ); |
| 7196 | |
| 7197 | return false; |
| 7198 | } |
| 7199 | |
| 7200 | /// parseDebugRecord |
| 7201 | /// ::= #dbg_label '(' MDNode ')' |
| 7202 | /// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ',' |
| 7203 | /// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')' |
| 7204 | bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) { |
| 7205 | using RecordKind = DbgRecord::Kind; |
| 7206 | using LocType = DbgVariableRecord::LocationType; |
| 7207 | LocTy DVRLoc = Lex.getLoc(); |
| 7208 | if (Lex.getKind() != lltok::DbgRecordType) |
| 7209 | return error(L: DVRLoc, Msg: "expected debug record type here" ); |
| 7210 | RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal()) |
| 7211 | .Case(S: "declare" , Value: RecordKind::ValueKind) |
| 7212 | .Case(S: "value" , Value: RecordKind::ValueKind) |
| 7213 | .Case(S: "assign" , Value: RecordKind::ValueKind) |
| 7214 | .Case(S: "label" , Value: RecordKind::LabelKind) |
| 7215 | .Case(S: "declare_value" , Value: RecordKind::ValueKind); |
| 7216 | |
| 7217 | // Parsing labels is trivial; parse here and early exit, otherwise go into the |
| 7218 | // full DbgVariableRecord processing stage. |
| 7219 | if (RecordType == RecordKind::LabelKind) { |
| 7220 | Lex.Lex(); |
| 7221 | if (parseToken(T: lltok::lparen, ErrMsg: "Expected '(' here" )) |
| 7222 | return true; |
| 7223 | MDNode *Label; |
| 7224 | if (parseMDNode(N&: Label)) |
| 7225 | return true; |
| 7226 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7227 | return true; |
| 7228 | MDNode *DbgLoc; |
| 7229 | if (parseMDNode(N&: DbgLoc)) |
| 7230 | return true; |
| 7231 | if (parseToken(T: lltok::rparen, ErrMsg: "Expected ')' here" )) |
| 7232 | return true; |
| 7233 | DR = DbgLabelRecord::createUnresolvedDbgLabelRecord(Label, DL: DbgLoc); |
| 7234 | return false; |
| 7235 | } |
| 7236 | |
| 7237 | LocType ValueType = StringSwitch<LocType>(Lex.getStrVal()) |
| 7238 | .Case(S: "declare" , Value: LocType::Declare) |
| 7239 | .Case(S: "value" , Value: LocType::Value) |
| 7240 | .Case(S: "assign" , Value: LocType::Assign) |
| 7241 | .Case(S: "declare_value" , Value: LocType::DeclareValue); |
| 7242 | |
| 7243 | Lex.Lex(); |
| 7244 | if (parseToken(T: lltok::lparen, ErrMsg: "Expected '(' here" )) |
| 7245 | return true; |
| 7246 | |
| 7247 | // Parse Value field. |
| 7248 | Metadata *ValLocMD; |
| 7249 | if (parseMetadata(MD&: ValLocMD, PFS: &PFS)) |
| 7250 | return true; |
| 7251 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7252 | return true; |
| 7253 | |
| 7254 | // Parse Variable field. |
| 7255 | MDNode *Variable; |
| 7256 | if (parseMDNode(N&: Variable)) |
| 7257 | return true; |
| 7258 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7259 | return true; |
| 7260 | |
| 7261 | // Parse Expression field. |
| 7262 | MDNode *Expression; |
| 7263 | if (parseMDNode(N&: Expression)) |
| 7264 | return true; |
| 7265 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7266 | return true; |
| 7267 | |
| 7268 | // Parse additional fields for #dbg_assign. |
| 7269 | MDNode *AssignID = nullptr; |
| 7270 | Metadata *AddressLocation = nullptr; |
| 7271 | MDNode *AddressExpression = nullptr; |
| 7272 | if (ValueType == LocType::Assign) { |
| 7273 | // Parse DIAssignID. |
| 7274 | if (parseMDNode(N&: AssignID)) |
| 7275 | return true; |
| 7276 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7277 | return true; |
| 7278 | |
| 7279 | // Parse address ValueAsMetadata. |
| 7280 | if (parseMetadata(MD&: AddressLocation, PFS: &PFS)) |
| 7281 | return true; |
| 7282 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7283 | return true; |
| 7284 | |
| 7285 | // Parse address DIExpression. |
| 7286 | if (parseMDNode(N&: AddressExpression)) |
| 7287 | return true; |
| 7288 | if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here" )) |
| 7289 | return true; |
| 7290 | } |
| 7291 | |
| 7292 | /// Parse DILocation. |
| 7293 | MDNode *DebugLoc; |
| 7294 | if (parseMDNode(N&: DebugLoc)) |
| 7295 | return true; |
| 7296 | |
| 7297 | if (parseToken(T: lltok::rparen, ErrMsg: "Expected ')' here" )) |
| 7298 | return true; |
| 7299 | DR = DbgVariableRecord::createUnresolvedDbgVariableRecord( |
| 7300 | Type: ValueType, Val: ValLocMD, Variable, Expression, AssignID, Address: AddressLocation, |
| 7301 | AddressExpression, DI: DebugLoc); |
| 7302 | return false; |
| 7303 | } |
| 7304 | //===----------------------------------------------------------------------===// |
| 7305 | // Instruction Parsing. |
| 7306 | //===----------------------------------------------------------------------===// |
| 7307 | |
| 7308 | /// parseInstruction - parse one of the many different instructions. |
| 7309 | /// |
| 7310 | int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, |
| 7311 | PerFunctionState &PFS) { |
| 7312 | lltok::Kind Token = Lex.getKind(); |
| 7313 | if (Token == lltok::Eof) |
| 7314 | return tokError(Msg: "found end of file when expecting more instructions" ); |
| 7315 | LocTy Loc = Lex.getLoc(); |
| 7316 | unsigned KeywordVal = Lex.getUIntVal(); |
| 7317 | Lex.Lex(); // Eat the keyword. |
| 7318 | |
| 7319 | switch (Token) { |
| 7320 | default: |
| 7321 | return error(L: Loc, Msg: "expected instruction opcode" ); |
| 7322 | // Terminator Instructions. |
| 7323 | case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; |
| 7324 | case lltok::kw_ret: |
| 7325 | return parseRet(Inst, BB, PFS); |
| 7326 | case lltok::kw_br: |
| 7327 | return parseBr(Inst, PFS); |
| 7328 | case lltok::kw_switch: |
| 7329 | return parseSwitch(Inst, PFS); |
| 7330 | case lltok::kw_indirectbr: |
| 7331 | return parseIndirectBr(Inst, PFS); |
| 7332 | case lltok::kw_invoke: |
| 7333 | return parseInvoke(Inst, PFS); |
| 7334 | case lltok::kw_resume: |
| 7335 | return parseResume(Inst, PFS); |
| 7336 | case lltok::kw_cleanupret: |
| 7337 | return parseCleanupRet(Inst, PFS); |
| 7338 | case lltok::kw_catchret: |
| 7339 | return parseCatchRet(Inst, PFS); |
| 7340 | case lltok::kw_catchswitch: |
| 7341 | return parseCatchSwitch(Inst, PFS); |
| 7342 | case lltok::kw_catchpad: |
| 7343 | return parseCatchPad(Inst, PFS); |
| 7344 | case lltok::kw_cleanuppad: |
| 7345 | return parseCleanupPad(Inst, PFS); |
| 7346 | case lltok::kw_callbr: |
| 7347 | return parseCallBr(Inst, PFS); |
| 7348 | // Unary Operators. |
| 7349 | case lltok::kw_fneg: { |
| 7350 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 7351 | int Res = parseUnaryOp(Inst, PFS, Opc: KeywordVal, /*IsFP*/ true); |
| 7352 | if (Res != 0) |
| 7353 | return Res; |
| 7354 | if (FMF.any()) |
| 7355 | Inst->setFastMathFlags(FMF); |
| 7356 | return false; |
| 7357 | } |
| 7358 | // Binary Operators. |
| 7359 | case lltok::kw_add: |
| 7360 | case lltok::kw_sub: |
| 7361 | case lltok::kw_mul: |
| 7362 | case lltok::kw_shl: { |
| 7363 | bool NUW = EatIfPresent(T: lltok::kw_nuw); |
| 7364 | bool NSW = EatIfPresent(T: lltok::kw_nsw); |
| 7365 | if (!NUW) NUW = EatIfPresent(T: lltok::kw_nuw); |
| 7366 | |
| 7367 | if (parseArithmetic(Inst, PFS, Opc: KeywordVal, /*IsFP*/ false)) |
| 7368 | return true; |
| 7369 | |
| 7370 | if (NUW) cast<BinaryOperator>(Val: Inst)->setHasNoUnsignedWrap(true); |
| 7371 | if (NSW) cast<BinaryOperator>(Val: Inst)->setHasNoSignedWrap(true); |
| 7372 | return false; |
| 7373 | } |
| 7374 | case lltok::kw_fadd: |
| 7375 | case lltok::kw_fsub: |
| 7376 | case lltok::kw_fmul: |
| 7377 | case lltok::kw_fdiv: |
| 7378 | case lltok::kw_frem: { |
| 7379 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 7380 | int Res = parseArithmetic(Inst, PFS, Opc: KeywordVal, /*IsFP*/ true); |
| 7381 | if (Res != 0) |
| 7382 | return Res; |
| 7383 | if (FMF.any()) |
| 7384 | Inst->setFastMathFlags(FMF); |
| 7385 | return 0; |
| 7386 | } |
| 7387 | |
| 7388 | case lltok::kw_sdiv: |
| 7389 | case lltok::kw_udiv: |
| 7390 | case lltok::kw_lshr: |
| 7391 | case lltok::kw_ashr: { |
| 7392 | bool Exact = EatIfPresent(T: lltok::kw_exact); |
| 7393 | |
| 7394 | if (parseArithmetic(Inst, PFS, Opc: KeywordVal, /*IsFP*/ false)) |
| 7395 | return true; |
| 7396 | if (Exact) cast<BinaryOperator>(Val: Inst)->setIsExact(true); |
| 7397 | return false; |
| 7398 | } |
| 7399 | |
| 7400 | case lltok::kw_urem: |
| 7401 | case lltok::kw_srem: |
| 7402 | return parseArithmetic(Inst, PFS, Opc: KeywordVal, |
| 7403 | /*IsFP*/ false); |
| 7404 | case lltok::kw_or: { |
| 7405 | bool Disjoint = EatIfPresent(T: lltok::kw_disjoint); |
| 7406 | if (parseLogical(Inst, PFS, Opc: KeywordVal)) |
| 7407 | return true; |
| 7408 | if (Disjoint) |
| 7409 | cast<PossiblyDisjointInst>(Val: Inst)->setIsDisjoint(true); |
| 7410 | return false; |
| 7411 | } |
| 7412 | case lltok::kw_and: |
| 7413 | case lltok::kw_xor: |
| 7414 | return parseLogical(Inst, PFS, Opc: KeywordVal); |
| 7415 | case lltok::kw_icmp: { |
| 7416 | bool SameSign = EatIfPresent(T: lltok::kw_samesign); |
| 7417 | if (parseCompare(Inst, PFS, Opc: KeywordVal)) |
| 7418 | return true; |
| 7419 | if (SameSign) |
| 7420 | cast<ICmpInst>(Val: Inst)->setSameSign(); |
| 7421 | return false; |
| 7422 | } |
| 7423 | case lltok::kw_fcmp: { |
| 7424 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 7425 | int Res = parseCompare(Inst, PFS, Opc: KeywordVal); |
| 7426 | if (Res != 0) |
| 7427 | return Res; |
| 7428 | if (FMF.any()) |
| 7429 | Inst->setFastMathFlags(FMF); |
| 7430 | return 0; |
| 7431 | } |
| 7432 | |
| 7433 | // Casts. |
| 7434 | case lltok::kw_uitofp: |
| 7435 | case lltok::kw_zext: { |
| 7436 | bool NonNeg = EatIfPresent(T: lltok::kw_nneg); |
| 7437 | bool Res = parseCast(Inst, PFS, Opc: KeywordVal); |
| 7438 | if (Res != 0) |
| 7439 | return Res; |
| 7440 | if (NonNeg) |
| 7441 | Inst->setNonNeg(); |
| 7442 | return 0; |
| 7443 | } |
| 7444 | case lltok::kw_trunc: { |
| 7445 | bool NUW = EatIfPresent(T: lltok::kw_nuw); |
| 7446 | bool NSW = EatIfPresent(T: lltok::kw_nsw); |
| 7447 | if (!NUW) |
| 7448 | NUW = EatIfPresent(T: lltok::kw_nuw); |
| 7449 | if (parseCast(Inst, PFS, Opc: KeywordVal)) |
| 7450 | return true; |
| 7451 | if (NUW) |
| 7452 | cast<TruncInst>(Val: Inst)->setHasNoUnsignedWrap(true); |
| 7453 | if (NSW) |
| 7454 | cast<TruncInst>(Val: Inst)->setHasNoSignedWrap(true); |
| 7455 | return false; |
| 7456 | } |
| 7457 | case lltok::kw_sext: |
| 7458 | case lltok::kw_bitcast: |
| 7459 | case lltok::kw_addrspacecast: |
| 7460 | case lltok::kw_sitofp: |
| 7461 | case lltok::kw_fptoui: |
| 7462 | case lltok::kw_fptosi: |
| 7463 | case lltok::kw_inttoptr: |
| 7464 | case lltok::kw_ptrtoaddr: |
| 7465 | case lltok::kw_ptrtoint: |
| 7466 | return parseCast(Inst, PFS, Opc: KeywordVal); |
| 7467 | case lltok::kw_fptrunc: |
| 7468 | case lltok::kw_fpext: { |
| 7469 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 7470 | if (parseCast(Inst, PFS, Opc: KeywordVal)) |
| 7471 | return true; |
| 7472 | if (FMF.any()) |
| 7473 | Inst->setFastMathFlags(FMF); |
| 7474 | return false; |
| 7475 | } |
| 7476 | |
| 7477 | // Other. |
| 7478 | case lltok::kw_select: { |
| 7479 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 7480 | int Res = parseSelect(Inst, PFS); |
| 7481 | if (Res != 0) |
| 7482 | return Res; |
| 7483 | if (FMF.any()) { |
| 7484 | if (!isa<FPMathOperator>(Val: Inst)) |
| 7485 | return error(L: Loc, Msg: "fast-math-flags specified for select without " |
| 7486 | "floating-point scalar or vector return type" ); |
| 7487 | Inst->setFastMathFlags(FMF); |
| 7488 | } |
| 7489 | return 0; |
| 7490 | } |
| 7491 | case lltok::kw_va_arg: |
| 7492 | return parseVAArg(Inst, PFS); |
| 7493 | case lltok::kw_extractelement: |
| 7494 | return parseExtractElement(Inst, PFS); |
| 7495 | case lltok::kw_insertelement: |
| 7496 | return parseInsertElement(Inst, PFS); |
| 7497 | case lltok::kw_shufflevector: |
| 7498 | return parseShuffleVector(Inst, PFS); |
| 7499 | case lltok::kw_phi: { |
| 7500 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 7501 | int Res = parsePHI(Inst, PFS); |
| 7502 | if (Res != 0) |
| 7503 | return Res; |
| 7504 | if (FMF.any()) { |
| 7505 | if (!isa<FPMathOperator>(Val: Inst)) |
| 7506 | return error(L: Loc, Msg: "fast-math-flags specified for phi without " |
| 7507 | "floating-point scalar or vector return type" ); |
| 7508 | Inst->setFastMathFlags(FMF); |
| 7509 | } |
| 7510 | return 0; |
| 7511 | } |
| 7512 | case lltok::kw_landingpad: |
| 7513 | return parseLandingPad(Inst, PFS); |
| 7514 | case lltok::kw_freeze: |
| 7515 | return parseFreeze(I&: Inst, PFS); |
| 7516 | // Call. |
| 7517 | case lltok::kw_call: |
| 7518 | return parseCall(Inst, PFS, TCK: CallInst::TCK_None); |
| 7519 | case lltok::kw_tail: |
| 7520 | return parseCall(Inst, PFS, TCK: CallInst::TCK_Tail); |
| 7521 | case lltok::kw_musttail: |
| 7522 | return parseCall(Inst, PFS, TCK: CallInst::TCK_MustTail); |
| 7523 | case lltok::kw_notail: |
| 7524 | return parseCall(Inst, PFS, TCK: CallInst::TCK_NoTail); |
| 7525 | // Memory. |
| 7526 | case lltok::kw_alloca: |
| 7527 | return parseAlloc(Inst, PFS); |
| 7528 | case lltok::kw_load: |
| 7529 | return parseLoad(Inst, PFS); |
| 7530 | case lltok::kw_store: |
| 7531 | return parseStore(Inst, PFS); |
| 7532 | case lltok::kw_cmpxchg: |
| 7533 | return parseCmpXchg(Inst, PFS); |
| 7534 | case lltok::kw_atomicrmw: |
| 7535 | return parseAtomicRMW(Inst, PFS); |
| 7536 | case lltok::kw_fence: |
| 7537 | return parseFence(Inst, PFS); |
| 7538 | case lltok::kw_getelementptr: |
| 7539 | return parseGetElementPtr(Inst, PFS); |
| 7540 | case lltok::kw_extractvalue: |
| 7541 | return parseExtractValue(Inst, PFS); |
| 7542 | case lltok::kw_insertvalue: |
| 7543 | return parseInsertValue(Inst, PFS); |
| 7544 | } |
| 7545 | } |
| 7546 | |
| 7547 | /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. |
| 7548 | bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { |
| 7549 | if (Opc == Instruction::FCmp) { |
| 7550 | switch (Lex.getKind()) { |
| 7551 | default: |
| 7552 | return tokError(Msg: "expected fcmp predicate (e.g. 'oeq')" ); |
| 7553 | case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; |
| 7554 | case lltok::kw_one: P = CmpInst::FCMP_ONE; break; |
| 7555 | case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; |
| 7556 | case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; |
| 7557 | case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; |
| 7558 | case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; |
| 7559 | case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; |
| 7560 | case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; |
| 7561 | case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; |
| 7562 | case lltok::kw_une: P = CmpInst::FCMP_UNE; break; |
| 7563 | case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; |
| 7564 | case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; |
| 7565 | case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; |
| 7566 | case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; |
| 7567 | case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; |
| 7568 | case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; |
| 7569 | } |
| 7570 | } else { |
| 7571 | switch (Lex.getKind()) { |
| 7572 | default: |
| 7573 | return tokError(Msg: "expected icmp predicate (e.g. 'eq')" ); |
| 7574 | case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; |
| 7575 | case lltok::kw_ne: P = CmpInst::ICMP_NE; break; |
| 7576 | case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; |
| 7577 | case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; |
| 7578 | case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; |
| 7579 | case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; |
| 7580 | case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; |
| 7581 | case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; |
| 7582 | case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; |
| 7583 | case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; |
| 7584 | } |
| 7585 | } |
| 7586 | Lex.Lex(); |
| 7587 | return false; |
| 7588 | } |
| 7589 | |
| 7590 | //===----------------------------------------------------------------------===// |
| 7591 | // Terminator Instructions. |
| 7592 | //===----------------------------------------------------------------------===// |
| 7593 | |
| 7594 | /// parseRet - parse a return instruction. |
| 7595 | /// ::= 'ret' void (',' !dbg, !1)* |
| 7596 | /// ::= 'ret' TypeAndValue (',' !dbg, !1)* |
| 7597 | bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, |
| 7598 | PerFunctionState &PFS) { |
| 7599 | SMLoc TypeLoc = Lex.getLoc(); |
| 7600 | Type *Ty = nullptr; |
| 7601 | if (parseType(Result&: Ty, AllowVoid: true /*void allowed*/)) |
| 7602 | return true; |
| 7603 | |
| 7604 | Type *ResType = PFS.getFunction().getReturnType(); |
| 7605 | |
| 7606 | if (Ty->isVoidTy()) { |
| 7607 | if (!ResType->isVoidTy()) |
| 7608 | return error(L: TypeLoc, Msg: "value doesn't match function result type '" + |
| 7609 | getTypeString(T: ResType) + "'" ); |
| 7610 | |
| 7611 | Inst = ReturnInst::Create(C&: Context); |
| 7612 | return false; |
| 7613 | } |
| 7614 | |
| 7615 | Value *RV; |
| 7616 | if (parseValue(Ty, V&: RV, PFS)) |
| 7617 | return true; |
| 7618 | |
| 7619 | if (ResType != RV->getType()) |
| 7620 | return error(L: TypeLoc, Msg: "value doesn't match function result type '" + |
| 7621 | getTypeString(T: ResType) + "'" ); |
| 7622 | |
| 7623 | Inst = ReturnInst::Create(C&: Context, retVal: RV); |
| 7624 | return false; |
| 7625 | } |
| 7626 | |
| 7627 | /// parseBr |
| 7628 | /// ::= 'br' TypeAndValue |
| 7629 | /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue |
| 7630 | bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { |
| 7631 | LocTy Loc, Loc2; |
| 7632 | Value *Op0; |
| 7633 | BasicBlock *Op1, *Op2; |
| 7634 | if (parseTypeAndValue(V&: Op0, Loc, PFS)) |
| 7635 | return true; |
| 7636 | |
| 7637 | if (BasicBlock *BB = dyn_cast<BasicBlock>(Val: Op0)) { |
| 7638 | Inst = BranchInst::Create(IfTrue: BB); |
| 7639 | return false; |
| 7640 | } |
| 7641 | |
| 7642 | if (Op0->getType() != Type::getInt1Ty(C&: Context)) |
| 7643 | return error(L: Loc, Msg: "branch condition must have 'i1' type" ); |
| 7644 | |
| 7645 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' after branch condition" ) || |
| 7646 | parseTypeAndBasicBlock(BB&: Op1, Loc, PFS) || |
| 7647 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after true destination" ) || |
| 7648 | parseTypeAndBasicBlock(BB&: Op2, Loc&: Loc2, PFS)) |
| 7649 | return true; |
| 7650 | |
| 7651 | Inst = BranchInst::Create(IfTrue: Op1, IfFalse: Op2, Cond: Op0); |
| 7652 | return false; |
| 7653 | } |
| 7654 | |
| 7655 | /// parseSwitch |
| 7656 | /// Instruction |
| 7657 | /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' |
| 7658 | /// JumpTable |
| 7659 | /// ::= (TypeAndValue ',' TypeAndValue)* |
| 7660 | bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { |
| 7661 | LocTy CondLoc, BBLoc; |
| 7662 | Value *Cond; |
| 7663 | BasicBlock *DefaultBB; |
| 7664 | if (parseTypeAndValue(V&: Cond, Loc&: CondLoc, PFS) || |
| 7665 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after switch condition" ) || |
| 7666 | parseTypeAndBasicBlock(BB&: DefaultBB, Loc&: BBLoc, PFS) || |
| 7667 | parseToken(T: lltok::lsquare, ErrMsg: "expected '[' with switch table" )) |
| 7668 | return true; |
| 7669 | |
| 7670 | if (!Cond->getType()->isIntegerTy()) |
| 7671 | return error(L: CondLoc, Msg: "switch condition must have integer type" ); |
| 7672 | |
| 7673 | // parse the jump table pairs. |
| 7674 | SmallPtrSet<Value*, 32> SeenCases; |
| 7675 | SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; |
| 7676 | while (Lex.getKind() != lltok::rsquare) { |
| 7677 | Value *Constant; |
| 7678 | BasicBlock *DestBB; |
| 7679 | |
| 7680 | if (parseTypeAndValue(V&: Constant, Loc&: CondLoc, PFS) || |
| 7681 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after case value" ) || |
| 7682 | parseTypeAndBasicBlock(BB&: DestBB, PFS)) |
| 7683 | return true; |
| 7684 | |
| 7685 | if (!SeenCases.insert(Ptr: Constant).second) |
| 7686 | return error(L: CondLoc, Msg: "duplicate case value in switch" ); |
| 7687 | if (!isa<ConstantInt>(Val: Constant)) |
| 7688 | return error(L: CondLoc, Msg: "case value is not a constant integer" ); |
| 7689 | |
| 7690 | Table.push_back(Elt: std::make_pair(x: cast<ConstantInt>(Val: Constant), y&: DestBB)); |
| 7691 | } |
| 7692 | |
| 7693 | Lex.Lex(); // Eat the ']'. |
| 7694 | |
| 7695 | SwitchInst *SI = SwitchInst::Create(Value: Cond, Default: DefaultBB, NumCases: Table.size()); |
| 7696 | for (const auto &[OnVal, Dest] : Table) |
| 7697 | SI->addCase(OnVal, Dest); |
| 7698 | Inst = SI; |
| 7699 | return false; |
| 7700 | } |
| 7701 | |
| 7702 | /// parseIndirectBr |
| 7703 | /// Instruction |
| 7704 | /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' |
| 7705 | bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { |
| 7706 | LocTy AddrLoc; |
| 7707 | Value *Address; |
| 7708 | if (parseTypeAndValue(V&: Address, Loc&: AddrLoc, PFS) || |
| 7709 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after indirectbr address" ) || |
| 7710 | parseToken(T: lltok::lsquare, ErrMsg: "expected '[' with indirectbr" )) |
| 7711 | return true; |
| 7712 | |
| 7713 | if (!Address->getType()->isPointerTy()) |
| 7714 | return error(L: AddrLoc, Msg: "indirectbr address must have pointer type" ); |
| 7715 | |
| 7716 | // parse the destination list. |
| 7717 | SmallVector<BasicBlock*, 16> DestList; |
| 7718 | |
| 7719 | if (Lex.getKind() != lltok::rsquare) { |
| 7720 | BasicBlock *DestBB; |
| 7721 | if (parseTypeAndBasicBlock(BB&: DestBB, PFS)) |
| 7722 | return true; |
| 7723 | DestList.push_back(Elt: DestBB); |
| 7724 | |
| 7725 | while (EatIfPresent(T: lltok::comma)) { |
| 7726 | if (parseTypeAndBasicBlock(BB&: DestBB, PFS)) |
| 7727 | return true; |
| 7728 | DestList.push_back(Elt: DestBB); |
| 7729 | } |
| 7730 | } |
| 7731 | |
| 7732 | if (parseToken(T: lltok::rsquare, ErrMsg: "expected ']' at end of block list" )) |
| 7733 | return true; |
| 7734 | |
| 7735 | IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests: DestList.size()); |
| 7736 | for (BasicBlock *Dest : DestList) |
| 7737 | IBI->addDestination(Dest); |
| 7738 | Inst = IBI; |
| 7739 | return false; |
| 7740 | } |
| 7741 | |
| 7742 | // If RetType is a non-function pointer type, then this is the short syntax |
| 7743 | // for the call, which means that RetType is just the return type. Infer the |
| 7744 | // rest of the function argument types from the arguments that are present. |
| 7745 | bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList, |
| 7746 | FunctionType *&FuncTy) { |
| 7747 | FuncTy = dyn_cast<FunctionType>(Val: RetType); |
| 7748 | if (!FuncTy) { |
| 7749 | // Pull out the types of all of the arguments... |
| 7750 | SmallVector<Type *, 8> ParamTypes; |
| 7751 | ParamTypes.reserve(N: ArgList.size()); |
| 7752 | for (const ParamInfo &Arg : ArgList) |
| 7753 | ParamTypes.push_back(Elt: Arg.V->getType()); |
| 7754 | |
| 7755 | if (!FunctionType::isValidReturnType(RetTy: RetType)) |
| 7756 | return true; |
| 7757 | |
| 7758 | FuncTy = FunctionType::get(Result: RetType, Params: ParamTypes, isVarArg: false); |
| 7759 | } |
| 7760 | return false; |
| 7761 | } |
| 7762 | |
| 7763 | /// parseInvoke |
| 7764 | /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList |
| 7765 | /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue |
| 7766 | bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { |
| 7767 | LocTy CallLoc = Lex.getLoc(); |
| 7768 | AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); |
| 7769 | std::vector<unsigned> FwdRefAttrGrps; |
| 7770 | LocTy NoBuiltinLoc; |
| 7771 | unsigned CC; |
| 7772 | unsigned InvokeAddrSpace; |
| 7773 | Type *RetType = nullptr; |
| 7774 | LocTy RetTypeLoc; |
| 7775 | ValID CalleeID; |
| 7776 | SmallVector<ParamInfo, 16> ArgList; |
| 7777 | SmallVector<OperandBundleDef, 2> BundleList; |
| 7778 | |
| 7779 | BasicBlock *NormalBB, *UnwindBB; |
| 7780 | if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) || |
| 7781 | parseOptionalProgramAddrSpace(AddrSpace&: InvokeAddrSpace) || |
| 7782 | parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/) || |
| 7783 | parseValID(ID&: CalleeID, PFS: &PFS) || parseParameterList(ArgList, PFS) || |
| 7784 | parseFnAttributeValuePairs(B&: FnAttrs, FwdRefAttrGrps, InAttrGrp: false, |
| 7785 | BuiltinLoc&: NoBuiltinLoc) || |
| 7786 | parseOptionalOperandBundles(BundleList, PFS) || |
| 7787 | parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in invoke" ) || |
| 7788 | parseTypeAndBasicBlock(BB&: NormalBB, PFS) || |
| 7789 | parseToken(T: lltok::kw_unwind, ErrMsg: "expected 'unwind' in invoke" ) || |
| 7790 | parseTypeAndBasicBlock(BB&: UnwindBB, PFS)) |
| 7791 | return true; |
| 7792 | |
| 7793 | // If RetType is a non-function pointer type, then this is the short syntax |
| 7794 | // for the call, which means that RetType is just the return type. Infer the |
| 7795 | // rest of the function argument types from the arguments that are present. |
| 7796 | FunctionType *Ty; |
| 7797 | if (resolveFunctionType(RetType, ArgList, FuncTy&: Ty)) |
| 7798 | return error(L: RetTypeLoc, Msg: "Invalid result type for LLVM function" ); |
| 7799 | |
| 7800 | CalleeID.FTy = Ty; |
| 7801 | |
| 7802 | // Look up the callee. |
| 7803 | Value *Callee; |
| 7804 | if (convertValIDToValue(Ty: PointerType::get(C&: Context, AddressSpace: InvokeAddrSpace), ID&: CalleeID, |
| 7805 | V&: Callee, PFS: &PFS)) |
| 7806 | return true; |
| 7807 | |
| 7808 | // Set up the Attribute for the function. |
| 7809 | SmallVector<Value *, 8> Args; |
| 7810 | SmallVector<AttributeSet, 8> ArgAttrs; |
| 7811 | |
| 7812 | // Loop through FunctionType's arguments and ensure they are specified |
| 7813 | // correctly. Also, gather any parameter attributes. |
| 7814 | FunctionType::param_iterator I = Ty->param_begin(); |
| 7815 | FunctionType::param_iterator E = Ty->param_end(); |
| 7816 | for (const ParamInfo &Arg : ArgList) { |
| 7817 | Type *ExpectedTy = nullptr; |
| 7818 | if (I != E) { |
| 7819 | ExpectedTy = *I++; |
| 7820 | } else if (!Ty->isVarArg()) { |
| 7821 | return error(L: Arg.Loc, Msg: "too many arguments specified" ); |
| 7822 | } |
| 7823 | |
| 7824 | if (ExpectedTy && ExpectedTy != Arg.V->getType()) |
| 7825 | return error(L: Arg.Loc, Msg: "argument is not of expected type '" + |
| 7826 | getTypeString(T: ExpectedTy) + "'" ); |
| 7827 | Args.push_back(Elt: Arg.V); |
| 7828 | ArgAttrs.push_back(Elt: Arg.Attrs); |
| 7829 | } |
| 7830 | |
| 7831 | if (I != E) |
| 7832 | return error(L: CallLoc, Msg: "not enough parameters specified for call" ); |
| 7833 | |
| 7834 | // Finish off the Attribute and check them |
| 7835 | AttributeList PAL = |
| 7836 | AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FnAttrs), |
| 7837 | RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs); |
| 7838 | |
| 7839 | InvokeInst *II = |
| 7840 | InvokeInst::Create(Ty, Func: Callee, IfNormal: NormalBB, IfException: UnwindBB, Args, Bundles: BundleList); |
| 7841 | II->setCallingConv(CC); |
| 7842 | II->setAttributes(PAL); |
| 7843 | ForwardRefAttrGroups[II] = FwdRefAttrGrps; |
| 7844 | Inst = II; |
| 7845 | return false; |
| 7846 | } |
| 7847 | |
| 7848 | /// parseResume |
| 7849 | /// ::= 'resume' TypeAndValue |
| 7850 | bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { |
| 7851 | Value *Exn; LocTy ExnLoc; |
| 7852 | if (parseTypeAndValue(V&: Exn, Loc&: ExnLoc, PFS)) |
| 7853 | return true; |
| 7854 | |
| 7855 | ResumeInst *RI = ResumeInst::Create(Exn); |
| 7856 | Inst = RI; |
| 7857 | return false; |
| 7858 | } |
| 7859 | |
| 7860 | bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, |
| 7861 | PerFunctionState &PFS) { |
| 7862 | if (parseToken(T: lltok::lsquare, ErrMsg: "expected '[' in catchpad/cleanuppad" )) |
| 7863 | return true; |
| 7864 | |
| 7865 | while (Lex.getKind() != lltok::rsquare) { |
| 7866 | // If this isn't the first argument, we need a comma. |
| 7867 | if (!Args.empty() && |
| 7868 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in argument list" )) |
| 7869 | return true; |
| 7870 | |
| 7871 | // parse the argument. |
| 7872 | LocTy ArgLoc; |
| 7873 | Type *ArgTy = nullptr; |
| 7874 | if (parseType(Result&: ArgTy, Loc&: ArgLoc)) |
| 7875 | return true; |
| 7876 | |
| 7877 | Value *V; |
| 7878 | if (ArgTy->isMetadataTy()) { |
| 7879 | if (parseMetadataAsValue(V, PFS)) |
| 7880 | return true; |
| 7881 | } else { |
| 7882 | if (parseValue(Ty: ArgTy, V, PFS)) |
| 7883 | return true; |
| 7884 | } |
| 7885 | Args.push_back(Elt: V); |
| 7886 | } |
| 7887 | |
| 7888 | Lex.Lex(); // Lex the ']'. |
| 7889 | return false; |
| 7890 | } |
| 7891 | |
| 7892 | /// parseCleanupRet |
| 7893 | /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) |
| 7894 | bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { |
| 7895 | Value *CleanupPad = nullptr; |
| 7896 | |
| 7897 | if (parseToken(T: lltok::kw_from, ErrMsg: "expected 'from' after cleanupret" )) |
| 7898 | return true; |
| 7899 | |
| 7900 | if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: CleanupPad, PFS)) |
| 7901 | return true; |
| 7902 | |
| 7903 | if (parseToken(T: lltok::kw_unwind, ErrMsg: "expected 'unwind' in cleanupret" )) |
| 7904 | return true; |
| 7905 | |
| 7906 | BasicBlock *UnwindBB = nullptr; |
| 7907 | if (Lex.getKind() == lltok::kw_to) { |
| 7908 | Lex.Lex(); |
| 7909 | if (parseToken(T: lltok::kw_caller, ErrMsg: "expected 'caller' in cleanupret" )) |
| 7910 | return true; |
| 7911 | } else { |
| 7912 | if (parseTypeAndBasicBlock(BB&: UnwindBB, PFS)) { |
| 7913 | return true; |
| 7914 | } |
| 7915 | } |
| 7916 | |
| 7917 | Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); |
| 7918 | return false; |
| 7919 | } |
| 7920 | |
| 7921 | /// parseCatchRet |
| 7922 | /// ::= 'catchret' from Parent Value 'to' TypeAndValue |
| 7923 | bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { |
| 7924 | Value *CatchPad = nullptr; |
| 7925 | |
| 7926 | if (parseToken(T: lltok::kw_from, ErrMsg: "expected 'from' after catchret" )) |
| 7927 | return true; |
| 7928 | |
| 7929 | if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: CatchPad, PFS)) |
| 7930 | return true; |
| 7931 | |
| 7932 | BasicBlock *BB; |
| 7933 | if (parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in catchret" ) || |
| 7934 | parseTypeAndBasicBlock(BB, PFS)) |
| 7935 | return true; |
| 7936 | |
| 7937 | Inst = CatchReturnInst::Create(CatchPad, BB); |
| 7938 | return false; |
| 7939 | } |
| 7940 | |
| 7941 | /// parseCatchSwitch |
| 7942 | /// ::= 'catchswitch' within Parent |
| 7943 | bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { |
| 7944 | Value *ParentPad; |
| 7945 | |
| 7946 | if (parseToken(T: lltok::kw_within, ErrMsg: "expected 'within' after catchswitch" )) |
| 7947 | return true; |
| 7948 | |
| 7949 | if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && |
| 7950 | Lex.getKind() != lltok::LocalVarID) |
| 7951 | return tokError(Msg: "expected scope value for catchswitch" ); |
| 7952 | |
| 7953 | if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: ParentPad, PFS)) |
| 7954 | return true; |
| 7955 | |
| 7956 | if (parseToken(T: lltok::lsquare, ErrMsg: "expected '[' with catchswitch labels" )) |
| 7957 | return true; |
| 7958 | |
| 7959 | SmallVector<BasicBlock *, 32> Table; |
| 7960 | do { |
| 7961 | BasicBlock *DestBB; |
| 7962 | if (parseTypeAndBasicBlock(BB&: DestBB, PFS)) |
| 7963 | return true; |
| 7964 | Table.push_back(Elt: DestBB); |
| 7965 | } while (EatIfPresent(T: lltok::comma)); |
| 7966 | |
| 7967 | if (parseToken(T: lltok::rsquare, ErrMsg: "expected ']' after catchswitch labels" )) |
| 7968 | return true; |
| 7969 | |
| 7970 | if (parseToken(T: lltok::kw_unwind, ErrMsg: "expected 'unwind' after catchswitch scope" )) |
| 7971 | return true; |
| 7972 | |
| 7973 | BasicBlock *UnwindBB = nullptr; |
| 7974 | if (EatIfPresent(T: lltok::kw_to)) { |
| 7975 | if (parseToken(T: lltok::kw_caller, ErrMsg: "expected 'caller' in catchswitch" )) |
| 7976 | return true; |
| 7977 | } else { |
| 7978 | if (parseTypeAndBasicBlock(BB&: UnwindBB, PFS)) |
| 7979 | return true; |
| 7980 | } |
| 7981 | |
| 7982 | auto *CatchSwitch = |
| 7983 | CatchSwitchInst::Create(ParentPad, UnwindDest: UnwindBB, NumHandlers: Table.size()); |
| 7984 | for (BasicBlock *DestBB : Table) |
| 7985 | CatchSwitch->addHandler(Dest: DestBB); |
| 7986 | Inst = CatchSwitch; |
| 7987 | return false; |
| 7988 | } |
| 7989 | |
| 7990 | /// parseCatchPad |
| 7991 | /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue |
| 7992 | bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { |
| 7993 | Value *CatchSwitch = nullptr; |
| 7994 | |
| 7995 | if (parseToken(T: lltok::kw_within, ErrMsg: "expected 'within' after catchpad" )) |
| 7996 | return true; |
| 7997 | |
| 7998 | if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) |
| 7999 | return tokError(Msg: "expected scope value for catchpad" ); |
| 8000 | |
| 8001 | if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: CatchSwitch, PFS)) |
| 8002 | return true; |
| 8003 | |
| 8004 | SmallVector<Value *, 8> Args; |
| 8005 | if (parseExceptionArgs(Args, PFS)) |
| 8006 | return true; |
| 8007 | |
| 8008 | Inst = CatchPadInst::Create(CatchSwitch, Args); |
| 8009 | return false; |
| 8010 | } |
| 8011 | |
| 8012 | /// parseCleanupPad |
| 8013 | /// ::= 'cleanuppad' within Parent ParamList |
| 8014 | bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { |
| 8015 | Value *ParentPad = nullptr; |
| 8016 | |
| 8017 | if (parseToken(T: lltok::kw_within, ErrMsg: "expected 'within' after cleanuppad" )) |
| 8018 | return true; |
| 8019 | |
| 8020 | if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && |
| 8021 | Lex.getKind() != lltok::LocalVarID) |
| 8022 | return tokError(Msg: "expected scope value for cleanuppad" ); |
| 8023 | |
| 8024 | if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: ParentPad, PFS)) |
| 8025 | return true; |
| 8026 | |
| 8027 | SmallVector<Value *, 8> Args; |
| 8028 | if (parseExceptionArgs(Args, PFS)) |
| 8029 | return true; |
| 8030 | |
| 8031 | Inst = CleanupPadInst::Create(ParentPad, Args); |
| 8032 | return false; |
| 8033 | } |
| 8034 | |
| 8035 | //===----------------------------------------------------------------------===// |
| 8036 | // Unary Operators. |
| 8037 | //===----------------------------------------------------------------------===// |
| 8038 | |
| 8039 | /// parseUnaryOp |
| 8040 | /// ::= UnaryOp TypeAndValue ',' Value |
| 8041 | /// |
| 8042 | /// If IsFP is false, then any integer operand is allowed, if it is true, any fp |
| 8043 | /// operand is allowed. |
| 8044 | bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, |
| 8045 | unsigned Opc, bool IsFP) { |
| 8046 | LocTy Loc; Value *LHS; |
| 8047 | if (parseTypeAndValue(V&: LHS, Loc, PFS)) |
| 8048 | return true; |
| 8049 | |
| 8050 | bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() |
| 8051 | : LHS->getType()->isIntOrIntVectorTy(); |
| 8052 | |
| 8053 | if (!Valid) |
| 8054 | return error(L: Loc, Msg: "invalid operand type for instruction" ); |
| 8055 | |
| 8056 | Inst = UnaryOperator::Create(Op: (Instruction::UnaryOps)Opc, S: LHS); |
| 8057 | return false; |
| 8058 | } |
| 8059 | |
| 8060 | /// parseCallBr |
| 8061 | /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList |
| 8062 | /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue |
| 8063 | /// '[' LabelList ']' |
| 8064 | bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { |
| 8065 | LocTy CallLoc = Lex.getLoc(); |
| 8066 | AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); |
| 8067 | std::vector<unsigned> FwdRefAttrGrps; |
| 8068 | LocTy NoBuiltinLoc; |
| 8069 | unsigned CC; |
| 8070 | Type *RetType = nullptr; |
| 8071 | LocTy RetTypeLoc; |
| 8072 | ValID CalleeID; |
| 8073 | SmallVector<ParamInfo, 16> ArgList; |
| 8074 | SmallVector<OperandBundleDef, 2> BundleList; |
| 8075 | |
| 8076 | BasicBlock *DefaultDest; |
| 8077 | if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) || |
| 8078 | parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/) || |
| 8079 | parseValID(ID&: CalleeID, PFS: &PFS) || parseParameterList(ArgList, PFS) || |
| 8080 | parseFnAttributeValuePairs(B&: FnAttrs, FwdRefAttrGrps, InAttrGrp: false, |
| 8081 | BuiltinLoc&: NoBuiltinLoc) || |
| 8082 | parseOptionalOperandBundles(BundleList, PFS) || |
| 8083 | parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in callbr" ) || |
| 8084 | parseTypeAndBasicBlock(BB&: DefaultDest, PFS) || |
| 8085 | parseToken(T: lltok::lsquare, ErrMsg: "expected '[' in callbr" )) |
| 8086 | return true; |
| 8087 | |
| 8088 | // parse the destination list. |
| 8089 | SmallVector<BasicBlock *, 16> IndirectDests; |
| 8090 | |
| 8091 | if (Lex.getKind() != lltok::rsquare) { |
| 8092 | BasicBlock *DestBB; |
| 8093 | if (parseTypeAndBasicBlock(BB&: DestBB, PFS)) |
| 8094 | return true; |
| 8095 | IndirectDests.push_back(Elt: DestBB); |
| 8096 | |
| 8097 | while (EatIfPresent(T: lltok::comma)) { |
| 8098 | if (parseTypeAndBasicBlock(BB&: DestBB, PFS)) |
| 8099 | return true; |
| 8100 | IndirectDests.push_back(Elt: DestBB); |
| 8101 | } |
| 8102 | } |
| 8103 | |
| 8104 | if (parseToken(T: lltok::rsquare, ErrMsg: "expected ']' at end of block list" )) |
| 8105 | return true; |
| 8106 | |
| 8107 | // If RetType is a non-function pointer type, then this is the short syntax |
| 8108 | // for the call, which means that RetType is just the return type. Infer the |
| 8109 | // rest of the function argument types from the arguments that are present. |
| 8110 | FunctionType *Ty; |
| 8111 | if (resolveFunctionType(RetType, ArgList, FuncTy&: Ty)) |
| 8112 | return error(L: RetTypeLoc, Msg: "Invalid result type for LLVM function" ); |
| 8113 | |
| 8114 | CalleeID.FTy = Ty; |
| 8115 | |
| 8116 | // Look up the callee. |
| 8117 | Value *Callee; |
| 8118 | if (convertValIDToValue(Ty: PointerType::getUnqual(C&: Context), ID&: CalleeID, V&: Callee, |
| 8119 | PFS: &PFS)) |
| 8120 | return true; |
| 8121 | |
| 8122 | // Set up the Attribute for the function. |
| 8123 | SmallVector<Value *, 8> Args; |
| 8124 | SmallVector<AttributeSet, 8> ArgAttrs; |
| 8125 | |
| 8126 | // Loop through FunctionType's arguments and ensure they are specified |
| 8127 | // correctly. Also, gather any parameter attributes. |
| 8128 | FunctionType::param_iterator I = Ty->param_begin(); |
| 8129 | FunctionType::param_iterator E = Ty->param_end(); |
| 8130 | for (const ParamInfo &Arg : ArgList) { |
| 8131 | Type *ExpectedTy = nullptr; |
| 8132 | if (I != E) { |
| 8133 | ExpectedTy = *I++; |
| 8134 | } else if (!Ty->isVarArg()) { |
| 8135 | return error(L: Arg.Loc, Msg: "too many arguments specified" ); |
| 8136 | } |
| 8137 | |
| 8138 | if (ExpectedTy && ExpectedTy != Arg.V->getType()) |
| 8139 | return error(L: Arg.Loc, Msg: "argument is not of expected type '" + |
| 8140 | getTypeString(T: ExpectedTy) + "'" ); |
| 8141 | Args.push_back(Elt: Arg.V); |
| 8142 | ArgAttrs.push_back(Elt: Arg.Attrs); |
| 8143 | } |
| 8144 | |
| 8145 | if (I != E) |
| 8146 | return error(L: CallLoc, Msg: "not enough parameters specified for call" ); |
| 8147 | |
| 8148 | // Finish off the Attribute and check them |
| 8149 | AttributeList PAL = |
| 8150 | AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FnAttrs), |
| 8151 | RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs); |
| 8152 | |
| 8153 | CallBrInst *CBI = |
| 8154 | CallBrInst::Create(Ty, Func: Callee, DefaultDest, IndirectDests, Args, |
| 8155 | Bundles: BundleList); |
| 8156 | CBI->setCallingConv(CC); |
| 8157 | CBI->setAttributes(PAL); |
| 8158 | ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; |
| 8159 | Inst = CBI; |
| 8160 | return false; |
| 8161 | } |
| 8162 | |
| 8163 | //===----------------------------------------------------------------------===// |
| 8164 | // Binary Operators. |
| 8165 | //===----------------------------------------------------------------------===// |
| 8166 | |
| 8167 | /// parseArithmetic |
| 8168 | /// ::= ArithmeticOps TypeAndValue ',' Value |
| 8169 | /// |
| 8170 | /// If IsFP is false, then any integer operand is allowed, if it is true, any fp |
| 8171 | /// operand is allowed. |
| 8172 | bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, |
| 8173 | unsigned Opc, bool IsFP) { |
| 8174 | LocTy Loc; Value *LHS, *RHS; |
| 8175 | if (parseTypeAndValue(V&: LHS, Loc, PFS) || |
| 8176 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in arithmetic operation" ) || |
| 8177 | parseValue(Ty: LHS->getType(), V&: RHS, PFS)) |
| 8178 | return true; |
| 8179 | |
| 8180 | bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() |
| 8181 | : LHS->getType()->isIntOrIntVectorTy(); |
| 8182 | |
| 8183 | if (!Valid) |
| 8184 | return error(L: Loc, Msg: "invalid operand type for instruction" ); |
| 8185 | |
| 8186 | Inst = BinaryOperator::Create(Op: (Instruction::BinaryOps)Opc, S1: LHS, S2: RHS); |
| 8187 | return false; |
| 8188 | } |
| 8189 | |
| 8190 | /// parseLogical |
| 8191 | /// ::= ArithmeticOps TypeAndValue ',' Value { |
| 8192 | bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, |
| 8193 | unsigned Opc) { |
| 8194 | LocTy Loc; Value *LHS, *RHS; |
| 8195 | if (parseTypeAndValue(V&: LHS, Loc, PFS) || |
| 8196 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in logical operation" ) || |
| 8197 | parseValue(Ty: LHS->getType(), V&: RHS, PFS)) |
| 8198 | return true; |
| 8199 | |
| 8200 | if (!LHS->getType()->isIntOrIntVectorTy()) |
| 8201 | return error(L: Loc, |
| 8202 | Msg: "instruction requires integer or integer vector operands" ); |
| 8203 | |
| 8204 | Inst = BinaryOperator::Create(Op: (Instruction::BinaryOps)Opc, S1: LHS, S2: RHS); |
| 8205 | return false; |
| 8206 | } |
| 8207 | |
| 8208 | /// parseCompare |
| 8209 | /// ::= 'icmp' IPredicates TypeAndValue ',' Value |
| 8210 | /// ::= 'fcmp' FPredicates TypeAndValue ',' Value |
| 8211 | bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, |
| 8212 | unsigned Opc) { |
| 8213 | // parse the integer/fp comparison predicate. |
| 8214 | LocTy Loc; |
| 8215 | unsigned Pred; |
| 8216 | Value *LHS, *RHS; |
| 8217 | if (parseCmpPredicate(P&: Pred, Opc) || parseTypeAndValue(V&: LHS, Loc, PFS) || |
| 8218 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after compare value" ) || |
| 8219 | parseValue(Ty: LHS->getType(), V&: RHS, PFS)) |
| 8220 | return true; |
| 8221 | |
| 8222 | if (Opc == Instruction::FCmp) { |
| 8223 | if (!LHS->getType()->isFPOrFPVectorTy()) |
| 8224 | return error(L: Loc, Msg: "fcmp requires floating point operands" ); |
| 8225 | Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); |
| 8226 | } else { |
| 8227 | assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!" ); |
| 8228 | if (!LHS->getType()->isIntOrIntVectorTy() && |
| 8229 | !LHS->getType()->isPtrOrPtrVectorTy()) |
| 8230 | return error(L: Loc, Msg: "icmp requires integer operands" ); |
| 8231 | Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); |
| 8232 | } |
| 8233 | return false; |
| 8234 | } |
| 8235 | |
| 8236 | //===----------------------------------------------------------------------===// |
| 8237 | // Other Instructions. |
| 8238 | //===----------------------------------------------------------------------===// |
| 8239 | |
| 8240 | /// parseCast |
| 8241 | /// ::= CastOpc TypeAndValue 'to' Type |
| 8242 | bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, |
| 8243 | unsigned Opc) { |
| 8244 | LocTy Loc; |
| 8245 | Value *Op; |
| 8246 | Type *DestTy = nullptr; |
| 8247 | if (parseTypeAndValue(V&: Op, Loc, PFS) || |
| 8248 | parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' after cast value" ) || |
| 8249 | parseType(Result&: DestTy)) |
| 8250 | return true; |
| 8251 | |
| 8252 | if (!CastInst::castIsValid(op: (Instruction::CastOps)Opc, S: Op, DstTy: DestTy)) |
| 8253 | return error(L: Loc, Msg: "invalid cast opcode for cast from '" + |
| 8254 | getTypeString(T: Op->getType()) + "' to '" + |
| 8255 | getTypeString(T: DestTy) + "'" ); |
| 8256 | Inst = CastInst::Create((Instruction::CastOps)Opc, S: Op, Ty: DestTy); |
| 8257 | return false; |
| 8258 | } |
| 8259 | |
| 8260 | /// parseSelect |
| 8261 | /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue |
| 8262 | bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { |
| 8263 | LocTy Loc; |
| 8264 | Value *Op0, *Op1, *Op2; |
| 8265 | if (parseTypeAndValue(V&: Op0, Loc, PFS) || |
| 8266 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after select condition" ) || |
| 8267 | parseTypeAndValue(V&: Op1, PFS) || |
| 8268 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after select value" ) || |
| 8269 | parseTypeAndValue(V&: Op2, PFS)) |
| 8270 | return true; |
| 8271 | |
| 8272 | if (const char *Reason = SelectInst::areInvalidOperands(Cond: Op0, True: Op1, False: Op2)) |
| 8273 | return error(L: Loc, Msg: Reason); |
| 8274 | |
| 8275 | Inst = SelectInst::Create(C: Op0, S1: Op1, S2: Op2); |
| 8276 | return false; |
| 8277 | } |
| 8278 | |
| 8279 | /// parseVAArg |
| 8280 | /// ::= 'va_arg' TypeAndValue ',' Type |
| 8281 | bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { |
| 8282 | Value *Op; |
| 8283 | Type *EltTy = nullptr; |
| 8284 | LocTy TypeLoc; |
| 8285 | if (parseTypeAndValue(V&: Op, PFS) || |
| 8286 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after vaarg operand" ) || |
| 8287 | parseType(Result&: EltTy, Loc&: TypeLoc)) |
| 8288 | return true; |
| 8289 | |
| 8290 | if (!EltTy->isFirstClassType()) |
| 8291 | return error(L: TypeLoc, Msg: "va_arg requires operand with first class type" ); |
| 8292 | |
| 8293 | Inst = new VAArgInst(Op, EltTy); |
| 8294 | return false; |
| 8295 | } |
| 8296 | |
| 8297 | /// parseExtractElement |
| 8298 | /// ::= 'extractelement' TypeAndValue ',' TypeAndValue |
| 8299 | bool LLParser::(Instruction *&Inst, PerFunctionState &PFS) { |
| 8300 | LocTy Loc; |
| 8301 | Value *Op0, *Op1; |
| 8302 | if (parseTypeAndValue(V&: Op0, Loc, PFS) || |
| 8303 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after extract value" ) || |
| 8304 | parseTypeAndValue(V&: Op1, PFS)) |
| 8305 | return true; |
| 8306 | |
| 8307 | if (!ExtractElementInst::isValidOperands(Vec: Op0, Idx: Op1)) |
| 8308 | return error(L: Loc, Msg: "invalid extractelement operands" ); |
| 8309 | |
| 8310 | Inst = ExtractElementInst::Create(Vec: Op0, Idx: Op1); |
| 8311 | return false; |
| 8312 | } |
| 8313 | |
| 8314 | /// parseInsertElement |
| 8315 | /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue |
| 8316 | bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { |
| 8317 | LocTy Loc; |
| 8318 | Value *Op0, *Op1, *Op2; |
| 8319 | if (parseTypeAndValue(V&: Op0, Loc, PFS) || |
| 8320 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after insertelement value" ) || |
| 8321 | parseTypeAndValue(V&: Op1, PFS) || |
| 8322 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after insertelement value" ) || |
| 8323 | parseTypeAndValue(V&: Op2, PFS)) |
| 8324 | return true; |
| 8325 | |
| 8326 | if (!InsertElementInst::isValidOperands(Vec: Op0, NewElt: Op1, Idx: Op2)) |
| 8327 | return error(L: Loc, Msg: "invalid insertelement operands" ); |
| 8328 | |
| 8329 | Inst = InsertElementInst::Create(Vec: Op0, NewElt: Op1, Idx: Op2); |
| 8330 | return false; |
| 8331 | } |
| 8332 | |
| 8333 | /// parseShuffleVector |
| 8334 | /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue |
| 8335 | bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { |
| 8336 | LocTy Loc; |
| 8337 | Value *Op0, *Op1, *Op2; |
| 8338 | if (parseTypeAndValue(V&: Op0, Loc, PFS) || |
| 8339 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after shuffle mask" ) || |
| 8340 | parseTypeAndValue(V&: Op1, PFS) || |
| 8341 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after shuffle value" ) || |
| 8342 | parseTypeAndValue(V&: Op2, PFS)) |
| 8343 | return true; |
| 8344 | |
| 8345 | if (!ShuffleVectorInst::isValidOperands(V1: Op0, V2: Op1, Mask: Op2)) |
| 8346 | return error(L: Loc, Msg: "invalid shufflevector operands" ); |
| 8347 | |
| 8348 | Inst = new ShuffleVectorInst(Op0, Op1, Op2); |
| 8349 | return false; |
| 8350 | } |
| 8351 | |
| 8352 | /// parsePHI |
| 8353 | /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* |
| 8354 | int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { |
| 8355 | Type *Ty = nullptr; LocTy TypeLoc; |
| 8356 | Value *Op0, *Op1; |
| 8357 | |
| 8358 | if (parseType(Result&: Ty, Loc&: TypeLoc)) |
| 8359 | return true; |
| 8360 | |
| 8361 | if (!Ty->isFirstClassType()) |
| 8362 | return error(L: TypeLoc, Msg: "phi node must have first class type" ); |
| 8363 | |
| 8364 | bool First = true; |
| 8365 | bool = false; |
| 8366 | SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; |
| 8367 | |
| 8368 | while (true) { |
| 8369 | if (First) { |
| 8370 | if (Lex.getKind() != lltok::lsquare) |
| 8371 | break; |
| 8372 | First = false; |
| 8373 | } else if (!EatIfPresent(T: lltok::comma)) |
| 8374 | break; |
| 8375 | |
| 8376 | if (Lex.getKind() == lltok::MetadataVar) { |
| 8377 | AteExtraComma = true; |
| 8378 | break; |
| 8379 | } |
| 8380 | |
| 8381 | if (parseToken(T: lltok::lsquare, ErrMsg: "expected '[' in phi value list" ) || |
| 8382 | parseValue(Ty, V&: Op0, PFS) || |
| 8383 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after insertelement value" ) || |
| 8384 | parseValue(Ty: Type::getLabelTy(C&: Context), V&: Op1, PFS) || |
| 8385 | parseToken(T: lltok::rsquare, ErrMsg: "expected ']' in phi value list" )) |
| 8386 | return true; |
| 8387 | |
| 8388 | PHIVals.push_back(Elt: std::make_pair(x&: Op0, y: cast<BasicBlock>(Val: Op1))); |
| 8389 | } |
| 8390 | |
| 8391 | PHINode *PN = PHINode::Create(Ty, NumReservedValues: PHIVals.size()); |
| 8392 | for (const auto &[Val, BB] : PHIVals) |
| 8393 | PN->addIncoming(V: Val, BB); |
| 8394 | Inst = PN; |
| 8395 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 8396 | } |
| 8397 | |
| 8398 | /// parseLandingPad |
| 8399 | /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ |
| 8400 | /// Clause |
| 8401 | /// ::= 'catch' TypeAndValue |
| 8402 | /// ::= 'filter' |
| 8403 | /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* |
| 8404 | bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { |
| 8405 | Type *Ty = nullptr; LocTy TyLoc; |
| 8406 | |
| 8407 | if (parseType(Result&: Ty, Loc&: TyLoc)) |
| 8408 | return true; |
| 8409 | |
| 8410 | std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(RetTy: Ty, NumReservedClauses: 0)); |
| 8411 | LP->setCleanup(EatIfPresent(T: lltok::kw_cleanup)); |
| 8412 | |
| 8413 | while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ |
| 8414 | LandingPadInst::ClauseType CT; |
| 8415 | if (EatIfPresent(T: lltok::kw_catch)) |
| 8416 | CT = LandingPadInst::Catch; |
| 8417 | else if (EatIfPresent(T: lltok::kw_filter)) |
| 8418 | CT = LandingPadInst::Filter; |
| 8419 | else |
| 8420 | return tokError(Msg: "expected 'catch' or 'filter' clause type" ); |
| 8421 | |
| 8422 | Value *V; |
| 8423 | LocTy VLoc; |
| 8424 | if (parseTypeAndValue(V, Loc&: VLoc, PFS)) |
| 8425 | return true; |
| 8426 | |
| 8427 | // A 'catch' type expects a non-array constant. A filter clause expects an |
| 8428 | // array constant. |
| 8429 | if (CT == LandingPadInst::Catch) { |
| 8430 | if (isa<ArrayType>(Val: V->getType())) |
| 8431 | return error(L: VLoc, Msg: "'catch' clause has an invalid type" ); |
| 8432 | } else { |
| 8433 | if (!isa<ArrayType>(Val: V->getType())) |
| 8434 | return error(L: VLoc, Msg: "'filter' clause has an invalid type" ); |
| 8435 | } |
| 8436 | |
| 8437 | Constant *CV = dyn_cast<Constant>(Val: V); |
| 8438 | if (!CV) |
| 8439 | return error(L: VLoc, Msg: "clause argument must be a constant" ); |
| 8440 | LP->addClause(ClauseVal: CV); |
| 8441 | } |
| 8442 | |
| 8443 | Inst = LP.release(); |
| 8444 | return false; |
| 8445 | } |
| 8446 | |
| 8447 | /// parseFreeze |
| 8448 | /// ::= 'freeze' Type Value |
| 8449 | bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { |
| 8450 | LocTy Loc; |
| 8451 | Value *Op; |
| 8452 | if (parseTypeAndValue(V&: Op, Loc, PFS)) |
| 8453 | return true; |
| 8454 | |
| 8455 | Inst = new FreezeInst(Op); |
| 8456 | return false; |
| 8457 | } |
| 8458 | |
| 8459 | /// parseCall |
| 8460 | /// ::= 'call' OptionalFastMathFlags OptionalCallingConv |
| 8461 | /// OptionalAttrs Type Value ParameterList OptionalAttrs |
| 8462 | /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv |
| 8463 | /// OptionalAttrs Type Value ParameterList OptionalAttrs |
| 8464 | /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv |
| 8465 | /// OptionalAttrs Type Value ParameterList OptionalAttrs |
| 8466 | /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv |
| 8467 | /// OptionalAttrs Type Value ParameterList OptionalAttrs |
| 8468 | bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, |
| 8469 | CallInst::TailCallKind TCK) { |
| 8470 | AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); |
| 8471 | std::vector<unsigned> FwdRefAttrGrps; |
| 8472 | LocTy BuiltinLoc; |
| 8473 | unsigned CallAddrSpace; |
| 8474 | unsigned CC; |
| 8475 | Type *RetType = nullptr; |
| 8476 | LocTy RetTypeLoc; |
| 8477 | ValID CalleeID; |
| 8478 | SmallVector<ParamInfo, 16> ArgList; |
| 8479 | SmallVector<OperandBundleDef, 2> BundleList; |
| 8480 | LocTy CallLoc = Lex.getLoc(); |
| 8481 | |
| 8482 | if (TCK != CallInst::TCK_None && |
| 8483 | parseToken(T: lltok::kw_call, |
| 8484 | ErrMsg: "expected 'tail call', 'musttail call', or 'notail call'" )) |
| 8485 | return true; |
| 8486 | |
| 8487 | FastMathFlags FMF = EatFastMathFlagsIfPresent(); |
| 8488 | |
| 8489 | if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) || |
| 8490 | parseOptionalProgramAddrSpace(AddrSpace&: CallAddrSpace) || |
| 8491 | parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/) || |
| 8492 | parseValID(ID&: CalleeID, PFS: &PFS) || |
| 8493 | parseParameterList(ArgList, PFS, IsMustTailCall: TCK == CallInst::TCK_MustTail, |
| 8494 | InVarArgsFunc: PFS.getFunction().isVarArg()) || |
| 8495 | parseFnAttributeValuePairs(B&: FnAttrs, FwdRefAttrGrps, InAttrGrp: false, BuiltinLoc) || |
| 8496 | parseOptionalOperandBundles(BundleList, PFS)) |
| 8497 | return true; |
| 8498 | |
| 8499 | // If RetType is a non-function pointer type, then this is the short syntax |
| 8500 | // for the call, which means that RetType is just the return type. Infer the |
| 8501 | // rest of the function argument types from the arguments that are present. |
| 8502 | FunctionType *Ty; |
| 8503 | if (resolveFunctionType(RetType, ArgList, FuncTy&: Ty)) |
| 8504 | return error(L: RetTypeLoc, Msg: "Invalid result type for LLVM function" ); |
| 8505 | |
| 8506 | CalleeID.FTy = Ty; |
| 8507 | |
| 8508 | // Look up the callee. |
| 8509 | Value *Callee; |
| 8510 | if (convertValIDToValue(Ty: PointerType::get(C&: Context, AddressSpace: CallAddrSpace), ID&: CalleeID, |
| 8511 | V&: Callee, PFS: &PFS)) |
| 8512 | return true; |
| 8513 | |
| 8514 | // Set up the Attribute for the function. |
| 8515 | SmallVector<AttributeSet, 8> Attrs; |
| 8516 | |
| 8517 | SmallVector<Value*, 8> Args; |
| 8518 | |
| 8519 | // Loop through FunctionType's arguments and ensure they are specified |
| 8520 | // correctly. Also, gather any parameter attributes. |
| 8521 | FunctionType::param_iterator I = Ty->param_begin(); |
| 8522 | FunctionType::param_iterator E = Ty->param_end(); |
| 8523 | for (const ParamInfo &Arg : ArgList) { |
| 8524 | Type *ExpectedTy = nullptr; |
| 8525 | if (I != E) { |
| 8526 | ExpectedTy = *I++; |
| 8527 | } else if (!Ty->isVarArg()) { |
| 8528 | return error(L: Arg.Loc, Msg: "too many arguments specified" ); |
| 8529 | } |
| 8530 | |
| 8531 | if (ExpectedTy && ExpectedTy != Arg.V->getType()) |
| 8532 | return error(L: Arg.Loc, Msg: "argument is not of expected type '" + |
| 8533 | getTypeString(T: ExpectedTy) + "'" ); |
| 8534 | Args.push_back(Elt: Arg.V); |
| 8535 | Attrs.push_back(Elt: Arg.Attrs); |
| 8536 | } |
| 8537 | |
| 8538 | if (I != E) |
| 8539 | return error(L: CallLoc, Msg: "not enough parameters specified for call" ); |
| 8540 | |
| 8541 | // Finish off the Attribute and check them |
| 8542 | AttributeList PAL = |
| 8543 | AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FnAttrs), |
| 8544 | RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs: Attrs); |
| 8545 | |
| 8546 | CallInst *CI = CallInst::Create(Ty, Func: Callee, Args, Bundles: BundleList); |
| 8547 | CI->setTailCallKind(TCK); |
| 8548 | CI->setCallingConv(CC); |
| 8549 | if (FMF.any()) { |
| 8550 | if (!isa<FPMathOperator>(Val: CI)) { |
| 8551 | CI->deleteValue(); |
| 8552 | return error(L: CallLoc, Msg: "fast-math-flags specified for call without " |
| 8553 | "floating-point scalar or vector return type" ); |
| 8554 | } |
| 8555 | CI->setFastMathFlags(FMF); |
| 8556 | } |
| 8557 | |
| 8558 | if (CalleeID.Kind == ValID::t_GlobalName && |
| 8559 | isOldDbgFormatIntrinsic(Name: CalleeID.StrVal)) { |
| 8560 | if (SeenNewDbgInfoFormat) { |
| 8561 | CI->deleteValue(); |
| 8562 | return error(L: CallLoc, Msg: "llvm.dbg intrinsic should not appear in a module " |
| 8563 | "using non-intrinsic debug info" ); |
| 8564 | } |
| 8565 | SeenOldDbgInfoFormat = true; |
| 8566 | } |
| 8567 | CI->setAttributes(PAL); |
| 8568 | ForwardRefAttrGroups[CI] = FwdRefAttrGrps; |
| 8569 | Inst = CI; |
| 8570 | return false; |
| 8571 | } |
| 8572 | |
| 8573 | //===----------------------------------------------------------------------===// |
| 8574 | // Memory Instructions. |
| 8575 | //===----------------------------------------------------------------------===// |
| 8576 | |
| 8577 | /// parseAlloc |
| 8578 | /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? |
| 8579 | /// (',' 'align' i32)? (',', 'addrspace(n))? |
| 8580 | int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { |
| 8581 | Value *Size = nullptr; |
| 8582 | LocTy SizeLoc, TyLoc, ASLoc; |
| 8583 | MaybeAlign Alignment; |
| 8584 | unsigned AddrSpace = 0; |
| 8585 | Type *Ty = nullptr; |
| 8586 | |
| 8587 | bool IsInAlloca = EatIfPresent(T: lltok::kw_inalloca); |
| 8588 | bool IsSwiftError = EatIfPresent(T: lltok::kw_swifterror); |
| 8589 | |
| 8590 | if (parseType(Result&: Ty, Loc&: TyLoc)) |
| 8591 | return true; |
| 8592 | |
| 8593 | if (Ty->isFunctionTy() || !PointerType::isValidElementType(ElemTy: Ty)) |
| 8594 | return error(L: TyLoc, Msg: "invalid type for alloca" ); |
| 8595 | |
| 8596 | bool = false; |
| 8597 | if (EatIfPresent(T: lltok::comma)) { |
| 8598 | if (Lex.getKind() == lltok::kw_align) { |
| 8599 | if (parseOptionalAlignment(Alignment)) |
| 8600 | return true; |
| 8601 | if (parseOptionalCommaAddrSpace(AddrSpace, Loc&: ASLoc, AteExtraComma)) |
| 8602 | return true; |
| 8603 | } else if (Lex.getKind() == lltok::kw_addrspace) { |
| 8604 | ASLoc = Lex.getLoc(); |
| 8605 | if (parseOptionalAddrSpace(AddrSpace)) |
| 8606 | return true; |
| 8607 | } else if (Lex.getKind() == lltok::MetadataVar) { |
| 8608 | AteExtraComma = true; |
| 8609 | } else { |
| 8610 | if (parseTypeAndValue(V&: Size, Loc&: SizeLoc, PFS)) |
| 8611 | return true; |
| 8612 | if (EatIfPresent(T: lltok::comma)) { |
| 8613 | if (Lex.getKind() == lltok::kw_align) { |
| 8614 | if (parseOptionalAlignment(Alignment)) |
| 8615 | return true; |
| 8616 | if (parseOptionalCommaAddrSpace(AddrSpace, Loc&: ASLoc, AteExtraComma)) |
| 8617 | return true; |
| 8618 | } else if (Lex.getKind() == lltok::kw_addrspace) { |
| 8619 | ASLoc = Lex.getLoc(); |
| 8620 | if (parseOptionalAddrSpace(AddrSpace)) |
| 8621 | return true; |
| 8622 | } else if (Lex.getKind() == lltok::MetadataVar) { |
| 8623 | AteExtraComma = true; |
| 8624 | } |
| 8625 | } |
| 8626 | } |
| 8627 | } |
| 8628 | |
| 8629 | if (Size && !Size->getType()->isIntegerTy()) |
| 8630 | return error(L: SizeLoc, Msg: "element count must have integer type" ); |
| 8631 | |
| 8632 | SmallPtrSet<Type *, 4> Visited; |
| 8633 | if (!Alignment && !Ty->isSized(Visited: &Visited)) |
| 8634 | return error(L: TyLoc, Msg: "Cannot allocate unsized type" ); |
| 8635 | if (!Alignment) |
| 8636 | Alignment = M->getDataLayout().getPrefTypeAlign(Ty); |
| 8637 | AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); |
| 8638 | AI->setUsedWithInAlloca(IsInAlloca); |
| 8639 | AI->setSwiftError(IsSwiftError); |
| 8640 | Inst = AI; |
| 8641 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 8642 | } |
| 8643 | |
| 8644 | /// parseLoad |
| 8645 | /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? |
| 8646 | /// ::= 'load' 'atomic' 'volatile'? TypeAndValue |
| 8647 | /// 'singlethread'? AtomicOrdering (',' 'align' i32)? |
| 8648 | int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { |
| 8649 | Value *Val; LocTy Loc; |
| 8650 | MaybeAlign Alignment; |
| 8651 | bool = false; |
| 8652 | bool isAtomic = false; |
| 8653 | AtomicOrdering Ordering = AtomicOrdering::NotAtomic; |
| 8654 | SyncScope::ID SSID = SyncScope::System; |
| 8655 | |
| 8656 | if (Lex.getKind() == lltok::kw_atomic) { |
| 8657 | isAtomic = true; |
| 8658 | Lex.Lex(); |
| 8659 | } |
| 8660 | |
| 8661 | bool isVolatile = false; |
| 8662 | if (Lex.getKind() == lltok::kw_volatile) { |
| 8663 | isVolatile = true; |
| 8664 | Lex.Lex(); |
| 8665 | } |
| 8666 | |
| 8667 | Type *Ty; |
| 8668 | LocTy ExplicitTypeLoc = Lex.getLoc(); |
| 8669 | if (parseType(Result&: Ty) || |
| 8670 | parseToken(T: lltok::comma, ErrMsg: "expected comma after load's type" ) || |
| 8671 | parseTypeAndValue(V&: Val, Loc, PFS) || |
| 8672 | parseScopeAndOrdering(IsAtomic: isAtomic, SSID, Ordering) || |
| 8673 | parseOptionalCommaAlign(Alignment, AteExtraComma)) |
| 8674 | return true; |
| 8675 | |
| 8676 | if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) |
| 8677 | return error(L: Loc, Msg: "load operand must be a pointer to a first class type" ); |
| 8678 | if (isAtomic && !Alignment) |
| 8679 | return error(L: Loc, Msg: "atomic load must have explicit non-zero alignment" ); |
| 8680 | if (Ordering == AtomicOrdering::Release || |
| 8681 | Ordering == AtomicOrdering::AcquireRelease) |
| 8682 | return error(L: Loc, Msg: "atomic load cannot use Release ordering" ); |
| 8683 | |
| 8684 | SmallPtrSet<Type *, 4> Visited; |
| 8685 | if (!Alignment && !Ty->isSized(Visited: &Visited)) |
| 8686 | return error(L: ExplicitTypeLoc, Msg: "loading unsized types is not allowed" ); |
| 8687 | if (!Alignment) |
| 8688 | Alignment = M->getDataLayout().getABITypeAlign(Ty); |
| 8689 | Inst = new LoadInst(Ty, Val, "" , isVolatile, *Alignment, Ordering, SSID); |
| 8690 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 8691 | } |
| 8692 | |
| 8693 | /// parseStore |
| 8694 | |
| 8695 | /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? |
| 8696 | /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue |
| 8697 | /// 'singlethread'? AtomicOrdering (',' 'align' i32)? |
| 8698 | int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { |
| 8699 | Value *Val, *Ptr; LocTy Loc, PtrLoc; |
| 8700 | MaybeAlign Alignment; |
| 8701 | bool = false; |
| 8702 | bool isAtomic = false; |
| 8703 | AtomicOrdering Ordering = AtomicOrdering::NotAtomic; |
| 8704 | SyncScope::ID SSID = SyncScope::System; |
| 8705 | |
| 8706 | if (Lex.getKind() == lltok::kw_atomic) { |
| 8707 | isAtomic = true; |
| 8708 | Lex.Lex(); |
| 8709 | } |
| 8710 | |
| 8711 | bool isVolatile = false; |
| 8712 | if (Lex.getKind() == lltok::kw_volatile) { |
| 8713 | isVolatile = true; |
| 8714 | Lex.Lex(); |
| 8715 | } |
| 8716 | |
| 8717 | if (parseTypeAndValue(V&: Val, Loc, PFS) || |
| 8718 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after store operand" ) || |
| 8719 | parseTypeAndValue(V&: Ptr, Loc&: PtrLoc, PFS) || |
| 8720 | parseScopeAndOrdering(IsAtomic: isAtomic, SSID, Ordering) || |
| 8721 | parseOptionalCommaAlign(Alignment, AteExtraComma)) |
| 8722 | return true; |
| 8723 | |
| 8724 | if (!Ptr->getType()->isPointerTy()) |
| 8725 | return error(L: PtrLoc, Msg: "store operand must be a pointer" ); |
| 8726 | if (!Val->getType()->isFirstClassType()) |
| 8727 | return error(L: Loc, Msg: "store operand must be a first class value" ); |
| 8728 | if (isAtomic && !Alignment) |
| 8729 | return error(L: Loc, Msg: "atomic store must have explicit non-zero alignment" ); |
| 8730 | if (Ordering == AtomicOrdering::Acquire || |
| 8731 | Ordering == AtomicOrdering::AcquireRelease) |
| 8732 | return error(L: Loc, Msg: "atomic store cannot use Acquire ordering" ); |
| 8733 | SmallPtrSet<Type *, 4> Visited; |
| 8734 | if (!Alignment && !Val->getType()->isSized(Visited: &Visited)) |
| 8735 | return error(L: Loc, Msg: "storing unsized types is not allowed" ); |
| 8736 | if (!Alignment) |
| 8737 | Alignment = M->getDataLayout().getABITypeAlign(Ty: Val->getType()); |
| 8738 | |
| 8739 | Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); |
| 8740 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 8741 | } |
| 8742 | |
| 8743 | /// parseCmpXchg |
| 8744 | /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' |
| 8745 | /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ',' |
| 8746 | /// 'Align'? |
| 8747 | int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { |
| 8748 | Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; |
| 8749 | bool = false; |
| 8750 | AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; |
| 8751 | AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; |
| 8752 | SyncScope::ID SSID = SyncScope::System; |
| 8753 | bool isVolatile = false; |
| 8754 | bool isWeak = false; |
| 8755 | MaybeAlign Alignment; |
| 8756 | |
| 8757 | if (EatIfPresent(T: lltok::kw_weak)) |
| 8758 | isWeak = true; |
| 8759 | |
| 8760 | if (EatIfPresent(T: lltok::kw_volatile)) |
| 8761 | isVolatile = true; |
| 8762 | |
| 8763 | if (parseTypeAndValue(V&: Ptr, Loc&: PtrLoc, PFS) || |
| 8764 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after cmpxchg address" ) || |
| 8765 | parseTypeAndValue(V&: Cmp, Loc&: CmpLoc, PFS) || |
| 8766 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after cmpxchg cmp operand" ) || |
| 8767 | parseTypeAndValue(V&: New, Loc&: NewLoc, PFS) || |
| 8768 | parseScopeAndOrdering(IsAtomic: true /*Always atomic*/, SSID, Ordering&: SuccessOrdering) || |
| 8769 | parseOrdering(Ordering&: FailureOrdering) || |
| 8770 | parseOptionalCommaAlign(Alignment, AteExtraComma)) |
| 8771 | return true; |
| 8772 | |
| 8773 | if (!AtomicCmpXchgInst::isValidSuccessOrdering(Ordering: SuccessOrdering)) |
| 8774 | return tokError(Msg: "invalid cmpxchg success ordering" ); |
| 8775 | if (!AtomicCmpXchgInst::isValidFailureOrdering(Ordering: FailureOrdering)) |
| 8776 | return tokError(Msg: "invalid cmpxchg failure ordering" ); |
| 8777 | if (!Ptr->getType()->isPointerTy()) |
| 8778 | return error(L: PtrLoc, Msg: "cmpxchg operand must be a pointer" ); |
| 8779 | if (Cmp->getType() != New->getType()) |
| 8780 | return error(L: NewLoc, Msg: "compare value and new value type do not match" ); |
| 8781 | if (!New->getType()->isFirstClassType()) |
| 8782 | return error(L: NewLoc, Msg: "cmpxchg operand must be a first class value" ); |
| 8783 | |
| 8784 | const Align DefaultAlignment( |
| 8785 | PFS.getFunction().getDataLayout().getTypeStoreSize( |
| 8786 | Ty: Cmp->getType())); |
| 8787 | |
| 8788 | AtomicCmpXchgInst *CXI = |
| 8789 | new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(u: DefaultAlignment), |
| 8790 | SuccessOrdering, FailureOrdering, SSID); |
| 8791 | CXI->setVolatile(isVolatile); |
| 8792 | CXI->setWeak(isWeak); |
| 8793 | |
| 8794 | Inst = CXI; |
| 8795 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 8796 | } |
| 8797 | |
| 8798 | /// parseAtomicRMW |
| 8799 | /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue |
| 8800 | /// 'singlethread'? AtomicOrdering |
| 8801 | int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { |
| 8802 | Value *Ptr, *Val; LocTy PtrLoc, ValLoc; |
| 8803 | bool = false; |
| 8804 | AtomicOrdering Ordering = AtomicOrdering::NotAtomic; |
| 8805 | SyncScope::ID SSID = SyncScope::System; |
| 8806 | bool isVolatile = false; |
| 8807 | bool IsFP = false; |
| 8808 | AtomicRMWInst::BinOp Operation; |
| 8809 | MaybeAlign Alignment; |
| 8810 | |
| 8811 | if (EatIfPresent(T: lltok::kw_volatile)) |
| 8812 | isVolatile = true; |
| 8813 | |
| 8814 | switch (Lex.getKind()) { |
| 8815 | default: |
| 8816 | return tokError(Msg: "expected binary operation in atomicrmw" ); |
| 8817 | case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; |
| 8818 | case lltok::kw_add: Operation = AtomicRMWInst::Add; break; |
| 8819 | case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; |
| 8820 | case lltok::kw_and: Operation = AtomicRMWInst::And; break; |
| 8821 | case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; |
| 8822 | case lltok::kw_or: Operation = AtomicRMWInst::Or; break; |
| 8823 | case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; |
| 8824 | case lltok::kw_max: Operation = AtomicRMWInst::Max; break; |
| 8825 | case lltok::kw_min: Operation = AtomicRMWInst::Min; break; |
| 8826 | case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; |
| 8827 | case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; |
| 8828 | case lltok::kw_uinc_wrap: |
| 8829 | Operation = AtomicRMWInst::UIncWrap; |
| 8830 | break; |
| 8831 | case lltok::kw_udec_wrap: |
| 8832 | Operation = AtomicRMWInst::UDecWrap; |
| 8833 | break; |
| 8834 | case lltok::kw_usub_cond: |
| 8835 | Operation = AtomicRMWInst::USubCond; |
| 8836 | break; |
| 8837 | case lltok::kw_usub_sat: |
| 8838 | Operation = AtomicRMWInst::USubSat; |
| 8839 | break; |
| 8840 | case lltok::kw_fadd: |
| 8841 | Operation = AtomicRMWInst::FAdd; |
| 8842 | IsFP = true; |
| 8843 | break; |
| 8844 | case lltok::kw_fsub: |
| 8845 | Operation = AtomicRMWInst::FSub; |
| 8846 | IsFP = true; |
| 8847 | break; |
| 8848 | case lltok::kw_fmax: |
| 8849 | Operation = AtomicRMWInst::FMax; |
| 8850 | IsFP = true; |
| 8851 | break; |
| 8852 | case lltok::kw_fmin: |
| 8853 | Operation = AtomicRMWInst::FMin; |
| 8854 | IsFP = true; |
| 8855 | break; |
| 8856 | case lltok::kw_fmaximum: |
| 8857 | Operation = AtomicRMWInst::FMaximum; |
| 8858 | IsFP = true; |
| 8859 | break; |
| 8860 | case lltok::kw_fminimum: |
| 8861 | Operation = AtomicRMWInst::FMinimum; |
| 8862 | IsFP = true; |
| 8863 | break; |
| 8864 | } |
| 8865 | Lex.Lex(); // Eat the operation. |
| 8866 | |
| 8867 | if (parseTypeAndValue(V&: Ptr, Loc&: PtrLoc, PFS) || |
| 8868 | parseToken(T: lltok::comma, ErrMsg: "expected ',' after atomicrmw address" ) || |
| 8869 | parseTypeAndValue(V&: Val, Loc&: ValLoc, PFS) || |
| 8870 | parseScopeAndOrdering(IsAtomic: true /*Always atomic*/, SSID, Ordering) || |
| 8871 | parseOptionalCommaAlign(Alignment, AteExtraComma)) |
| 8872 | return true; |
| 8873 | |
| 8874 | if (Ordering == AtomicOrdering::Unordered) |
| 8875 | return tokError(Msg: "atomicrmw cannot be unordered" ); |
| 8876 | if (!Ptr->getType()->isPointerTy()) |
| 8877 | return error(L: PtrLoc, Msg: "atomicrmw operand must be a pointer" ); |
| 8878 | if (Val->getType()->isScalableTy()) |
| 8879 | return error(L: ValLoc, Msg: "atomicrmw operand may not be scalable" ); |
| 8880 | |
| 8881 | if (Operation == AtomicRMWInst::Xchg) { |
| 8882 | if (!Val->getType()->isIntegerTy() && |
| 8883 | !Val->getType()->isFloatingPointTy() && |
| 8884 | !Val->getType()->isPointerTy()) { |
| 8885 | return error( |
| 8886 | L: ValLoc, |
| 8887 | Msg: "atomicrmw " + AtomicRMWInst::getOperationName(Op: Operation) + |
| 8888 | " operand must be an integer, floating point, or pointer type" ); |
| 8889 | } |
| 8890 | } else if (IsFP) { |
| 8891 | if (!Val->getType()->isFPOrFPVectorTy()) { |
| 8892 | return error(L: ValLoc, Msg: "atomicrmw " + |
| 8893 | AtomicRMWInst::getOperationName(Op: Operation) + |
| 8894 | " operand must be a floating point type" ); |
| 8895 | } |
| 8896 | } else { |
| 8897 | if (!Val->getType()->isIntegerTy()) { |
| 8898 | return error(L: ValLoc, Msg: "atomicrmw " + |
| 8899 | AtomicRMWInst::getOperationName(Op: Operation) + |
| 8900 | " operand must be an integer" ); |
| 8901 | } |
| 8902 | } |
| 8903 | |
| 8904 | unsigned Size = |
| 8905 | PFS.getFunction().getDataLayout().getTypeStoreSizeInBits( |
| 8906 | Ty: Val->getType()); |
| 8907 | if (Size < 8 || (Size & (Size - 1))) |
| 8908 | return error(L: ValLoc, Msg: "atomicrmw operand must be power-of-two byte-sized" |
| 8909 | " integer" ); |
| 8910 | const Align DefaultAlignment( |
| 8911 | PFS.getFunction().getDataLayout().getTypeStoreSize( |
| 8912 | Ty: Val->getType())); |
| 8913 | AtomicRMWInst *RMWI = |
| 8914 | new AtomicRMWInst(Operation, Ptr, Val, |
| 8915 | Alignment.value_or(u: DefaultAlignment), Ordering, SSID); |
| 8916 | RMWI->setVolatile(isVolatile); |
| 8917 | Inst = RMWI; |
| 8918 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 8919 | } |
| 8920 | |
| 8921 | /// parseFence |
| 8922 | /// ::= 'fence' 'singlethread'? AtomicOrdering |
| 8923 | int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { |
| 8924 | AtomicOrdering Ordering = AtomicOrdering::NotAtomic; |
| 8925 | SyncScope::ID SSID = SyncScope::System; |
| 8926 | if (parseScopeAndOrdering(IsAtomic: true /*Always atomic*/, SSID, Ordering)) |
| 8927 | return true; |
| 8928 | |
| 8929 | if (Ordering == AtomicOrdering::Unordered) |
| 8930 | return tokError(Msg: "fence cannot be unordered" ); |
| 8931 | if (Ordering == AtomicOrdering::Monotonic) |
| 8932 | return tokError(Msg: "fence cannot be monotonic" ); |
| 8933 | |
| 8934 | Inst = new FenceInst(Context, Ordering, SSID); |
| 8935 | return InstNormal; |
| 8936 | } |
| 8937 | |
| 8938 | /// parseGetElementPtr |
| 8939 | /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* |
| 8940 | int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { |
| 8941 | Value *Ptr = nullptr; |
| 8942 | Value *Val = nullptr; |
| 8943 | LocTy Loc, EltLoc; |
| 8944 | GEPNoWrapFlags NW; |
| 8945 | |
| 8946 | while (true) { |
| 8947 | if (EatIfPresent(T: lltok::kw_inbounds)) |
| 8948 | NW |= GEPNoWrapFlags::inBounds(); |
| 8949 | else if (EatIfPresent(T: lltok::kw_nusw)) |
| 8950 | NW |= GEPNoWrapFlags::noUnsignedSignedWrap(); |
| 8951 | else if (EatIfPresent(T: lltok::kw_nuw)) |
| 8952 | NW |= GEPNoWrapFlags::noUnsignedWrap(); |
| 8953 | else |
| 8954 | break; |
| 8955 | } |
| 8956 | |
| 8957 | Type *Ty = nullptr; |
| 8958 | if (parseType(Result&: Ty) || |
| 8959 | parseToken(T: lltok::comma, ErrMsg: "expected comma after getelementptr's type" ) || |
| 8960 | parseTypeAndValue(V&: Ptr, Loc, PFS)) |
| 8961 | return true; |
| 8962 | |
| 8963 | Type *BaseType = Ptr->getType(); |
| 8964 | PointerType *BasePointerType = dyn_cast<PointerType>(Val: BaseType->getScalarType()); |
| 8965 | if (!BasePointerType) |
| 8966 | return error(L: Loc, Msg: "base of getelementptr must be a pointer" ); |
| 8967 | |
| 8968 | SmallVector<Value*, 16> Indices; |
| 8969 | bool = false; |
| 8970 | // GEP returns a vector of pointers if at least one of parameters is a vector. |
| 8971 | // All vector parameters should have the same vector width. |
| 8972 | ElementCount GEPWidth = BaseType->isVectorTy() |
| 8973 | ? cast<VectorType>(Val: BaseType)->getElementCount() |
| 8974 | : ElementCount::getFixed(MinVal: 0); |
| 8975 | |
| 8976 | while (EatIfPresent(T: lltok::comma)) { |
| 8977 | if (Lex.getKind() == lltok::MetadataVar) { |
| 8978 | AteExtraComma = true; |
| 8979 | break; |
| 8980 | } |
| 8981 | if (parseTypeAndValue(V&: Val, Loc&: EltLoc, PFS)) |
| 8982 | return true; |
| 8983 | if (!Val->getType()->isIntOrIntVectorTy()) |
| 8984 | return error(L: EltLoc, Msg: "getelementptr index must be an integer" ); |
| 8985 | |
| 8986 | if (auto *ValVTy = dyn_cast<VectorType>(Val: Val->getType())) { |
| 8987 | ElementCount ValNumEl = ValVTy->getElementCount(); |
| 8988 | if (GEPWidth != ElementCount::getFixed(MinVal: 0) && GEPWidth != ValNumEl) |
| 8989 | return error( |
| 8990 | L: EltLoc, |
| 8991 | Msg: "getelementptr vector index has a wrong number of elements" ); |
| 8992 | GEPWidth = ValNumEl; |
| 8993 | } |
| 8994 | Indices.push_back(Elt: Val); |
| 8995 | } |
| 8996 | |
| 8997 | SmallPtrSet<Type*, 4> Visited; |
| 8998 | if (!Indices.empty() && !Ty->isSized(Visited: &Visited)) |
| 8999 | return error(L: Loc, Msg: "base element of getelementptr must be sized" ); |
| 9000 | |
| 9001 | auto *STy = dyn_cast<StructType>(Val: Ty); |
| 9002 | if (STy && STy->isScalableTy()) |
| 9003 | return error(L: Loc, Msg: "getelementptr cannot target structure that contains " |
| 9004 | "scalable vector type" ); |
| 9005 | |
| 9006 | if (!GetElementPtrInst::getIndexedType(Ty, IdxList: Indices)) |
| 9007 | return error(L: Loc, Msg: "invalid getelementptr indices" ); |
| 9008 | GetElementPtrInst *GEP = GetElementPtrInst::Create(PointeeType: Ty, Ptr, IdxList: Indices); |
| 9009 | Inst = GEP; |
| 9010 | GEP->setNoWrapFlags(NW); |
| 9011 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 9012 | } |
| 9013 | |
| 9014 | /// parseExtractValue |
| 9015 | /// ::= 'extractvalue' TypeAndValue (',' uint32)+ |
| 9016 | int LLParser::(Instruction *&Inst, PerFunctionState &PFS) { |
| 9017 | Value *Val; LocTy Loc; |
| 9018 | SmallVector<unsigned, 4> Indices; |
| 9019 | bool ; |
| 9020 | if (parseTypeAndValue(V&: Val, Loc, PFS) || |
| 9021 | parseIndexList(Indices, AteExtraComma)) |
| 9022 | return true; |
| 9023 | |
| 9024 | if (!Val->getType()->isAggregateType()) |
| 9025 | return error(L: Loc, Msg: "extractvalue operand must be aggregate type" ); |
| 9026 | |
| 9027 | if (!ExtractValueInst::getIndexedType(Agg: Val->getType(), Idxs: Indices)) |
| 9028 | return error(L: Loc, Msg: "invalid indices for extractvalue" ); |
| 9029 | Inst = ExtractValueInst::Create(Agg: Val, Idxs: Indices); |
| 9030 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 9031 | } |
| 9032 | |
| 9033 | /// parseInsertValue |
| 9034 | /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ |
| 9035 | int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { |
| 9036 | Value *Val0, *Val1; LocTy Loc0, Loc1; |
| 9037 | SmallVector<unsigned, 4> Indices; |
| 9038 | bool ; |
| 9039 | if (parseTypeAndValue(V&: Val0, Loc&: Loc0, PFS) || |
| 9040 | parseToken(T: lltok::comma, ErrMsg: "expected comma after insertvalue operand" ) || |
| 9041 | parseTypeAndValue(V&: Val1, Loc&: Loc1, PFS) || |
| 9042 | parseIndexList(Indices, AteExtraComma)) |
| 9043 | return true; |
| 9044 | |
| 9045 | if (!Val0->getType()->isAggregateType()) |
| 9046 | return error(L: Loc0, Msg: "insertvalue operand must be aggregate type" ); |
| 9047 | |
| 9048 | Type *IndexedType = ExtractValueInst::getIndexedType(Agg: Val0->getType(), Idxs: Indices); |
| 9049 | if (!IndexedType) |
| 9050 | return error(L: Loc0, Msg: "invalid indices for insertvalue" ); |
| 9051 | if (IndexedType != Val1->getType()) |
| 9052 | return error(L: Loc1, Msg: "insertvalue operand and field disagree in type: '" + |
| 9053 | getTypeString(T: Val1->getType()) + "' instead of '" + |
| 9054 | getTypeString(T: IndexedType) + "'" ); |
| 9055 | Inst = InsertValueInst::Create(Agg: Val0, Val: Val1, Idxs: Indices); |
| 9056 | return AteExtraComma ? InstExtraComma : InstNormal; |
| 9057 | } |
| 9058 | |
| 9059 | //===----------------------------------------------------------------------===// |
| 9060 | // Embedded metadata. |
| 9061 | //===----------------------------------------------------------------------===// |
| 9062 | |
| 9063 | /// parseMDNodeVector |
| 9064 | /// ::= { Element (',' Element)* } |
| 9065 | /// Element |
| 9066 | /// ::= 'null' | Metadata |
| 9067 | bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { |
| 9068 | if (parseToken(T: lltok::lbrace, ErrMsg: "expected '{' here" )) |
| 9069 | return true; |
| 9070 | |
| 9071 | // Check for an empty list. |
| 9072 | if (EatIfPresent(T: lltok::rbrace)) |
| 9073 | return false; |
| 9074 | |
| 9075 | do { |
| 9076 | if (EatIfPresent(T: lltok::kw_null)) { |
| 9077 | Elts.push_back(Elt: nullptr); |
| 9078 | continue; |
| 9079 | } |
| 9080 | |
| 9081 | Metadata *MD; |
| 9082 | if (parseMetadata(MD, PFS: nullptr)) |
| 9083 | return true; |
| 9084 | Elts.push_back(Elt: MD); |
| 9085 | } while (EatIfPresent(T: lltok::comma)); |
| 9086 | |
| 9087 | return parseToken(T: lltok::rbrace, ErrMsg: "expected end of metadata node" ); |
| 9088 | } |
| 9089 | |
| 9090 | //===----------------------------------------------------------------------===// |
| 9091 | // Use-list order directives. |
| 9092 | //===----------------------------------------------------------------------===// |
| 9093 | bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, |
| 9094 | SMLoc Loc) { |
| 9095 | if (!V->hasUseList()) |
| 9096 | return false; |
| 9097 | if (V->use_empty()) |
| 9098 | return error(L: Loc, Msg: "value has no uses" ); |
| 9099 | |
| 9100 | unsigned NumUses = 0; |
| 9101 | SmallDenseMap<const Use *, unsigned, 16> Order; |
| 9102 | for (const Use &U : V->uses()) { |
| 9103 | if (++NumUses > Indexes.size()) |
| 9104 | break; |
| 9105 | Order[&U] = Indexes[NumUses - 1]; |
| 9106 | } |
| 9107 | if (NumUses < 2) |
| 9108 | return error(L: Loc, Msg: "value only has one use" ); |
| 9109 | if (Order.size() != Indexes.size() || NumUses > Indexes.size()) |
| 9110 | return error(L: Loc, |
| 9111 | Msg: "wrong number of indexes, expected " + Twine(V->getNumUses())); |
| 9112 | |
| 9113 | V->sortUseList(Cmp: [&](const Use &L, const Use &R) { |
| 9114 | return Order.lookup(Val: &L) < Order.lookup(Val: &R); |
| 9115 | }); |
| 9116 | return false; |
| 9117 | } |
| 9118 | |
| 9119 | /// parseUseListOrderIndexes |
| 9120 | /// ::= '{' uint32 (',' uint32)+ '}' |
| 9121 | bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { |
| 9122 | SMLoc Loc = Lex.getLoc(); |
| 9123 | if (parseToken(T: lltok::lbrace, ErrMsg: "expected '{' here" )) |
| 9124 | return true; |
| 9125 | if (Lex.getKind() == lltok::rbrace) |
| 9126 | return tokError(Msg: "expected non-empty list of uselistorder indexes" ); |
| 9127 | |
| 9128 | // Use Offset, Max, and IsOrdered to check consistency of indexes. The |
| 9129 | // indexes should be distinct numbers in the range [0, size-1], and should |
| 9130 | // not be in order. |
| 9131 | unsigned Offset = 0; |
| 9132 | unsigned Max = 0; |
| 9133 | bool IsOrdered = true; |
| 9134 | assert(Indexes.empty() && "Expected empty order vector" ); |
| 9135 | do { |
| 9136 | unsigned Index; |
| 9137 | if (parseUInt32(Val&: Index)) |
| 9138 | return true; |
| 9139 | |
| 9140 | // Update consistency checks. |
| 9141 | Offset += Index - Indexes.size(); |
| 9142 | Max = std::max(a: Max, b: Index); |
| 9143 | IsOrdered &= Index == Indexes.size(); |
| 9144 | |
| 9145 | Indexes.push_back(Elt: Index); |
| 9146 | } while (EatIfPresent(T: lltok::comma)); |
| 9147 | |
| 9148 | if (parseToken(T: lltok::rbrace, ErrMsg: "expected '}' here" )) |
| 9149 | return true; |
| 9150 | |
| 9151 | if (Indexes.size() < 2) |
| 9152 | return error(L: Loc, Msg: "expected >= 2 uselistorder indexes" ); |
| 9153 | if (Offset != 0 || Max >= Indexes.size()) |
| 9154 | return error(L: Loc, |
| 9155 | Msg: "expected distinct uselistorder indexes in range [0, size)" ); |
| 9156 | if (IsOrdered) |
| 9157 | return error(L: Loc, Msg: "expected uselistorder indexes to change the order" ); |
| 9158 | |
| 9159 | return false; |
| 9160 | } |
| 9161 | |
| 9162 | /// parseUseListOrder |
| 9163 | /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes |
| 9164 | bool LLParser::parseUseListOrder(PerFunctionState *PFS) { |
| 9165 | SMLoc Loc = Lex.getLoc(); |
| 9166 | if (parseToken(T: lltok::kw_uselistorder, ErrMsg: "expected uselistorder directive" )) |
| 9167 | return true; |
| 9168 | |
| 9169 | Value *V; |
| 9170 | SmallVector<unsigned, 16> Indexes; |
| 9171 | if (parseTypeAndValue(V, PFS) || |
| 9172 | parseToken(T: lltok::comma, ErrMsg: "expected comma in uselistorder directive" ) || |
| 9173 | parseUseListOrderIndexes(Indexes)) |
| 9174 | return true; |
| 9175 | |
| 9176 | return sortUseListOrder(V, Indexes, Loc); |
| 9177 | } |
| 9178 | |
| 9179 | /// parseUseListOrderBB |
| 9180 | /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes |
| 9181 | bool LLParser::parseUseListOrderBB() { |
| 9182 | assert(Lex.getKind() == lltok::kw_uselistorder_bb); |
| 9183 | SMLoc Loc = Lex.getLoc(); |
| 9184 | Lex.Lex(); |
| 9185 | |
| 9186 | ValID Fn, Label; |
| 9187 | SmallVector<unsigned, 16> Indexes; |
| 9188 | if (parseValID(ID&: Fn, /*PFS=*/nullptr) || |
| 9189 | parseToken(T: lltok::comma, ErrMsg: "expected comma in uselistorder_bb directive" ) || |
| 9190 | parseValID(ID&: Label, /*PFS=*/nullptr) || |
| 9191 | parseToken(T: lltok::comma, ErrMsg: "expected comma in uselistorder_bb directive" ) || |
| 9192 | parseUseListOrderIndexes(Indexes)) |
| 9193 | return true; |
| 9194 | |
| 9195 | // Check the function. |
| 9196 | GlobalValue *GV; |
| 9197 | if (Fn.Kind == ValID::t_GlobalName) |
| 9198 | GV = M->getNamedValue(Name: Fn.StrVal); |
| 9199 | else if (Fn.Kind == ValID::t_GlobalID) |
| 9200 | GV = NumberedVals.get(ID: Fn.UIntVal); |
| 9201 | else |
| 9202 | return error(L: Fn.Loc, Msg: "expected function name in uselistorder_bb" ); |
| 9203 | if (!GV) |
| 9204 | return error(L: Fn.Loc, |
| 9205 | Msg: "invalid function forward reference in uselistorder_bb" ); |
| 9206 | auto *F = dyn_cast<Function>(Val: GV); |
| 9207 | if (!F) |
| 9208 | return error(L: Fn.Loc, Msg: "expected function name in uselistorder_bb" ); |
| 9209 | if (F->isDeclaration()) |
| 9210 | return error(L: Fn.Loc, Msg: "invalid declaration in uselistorder_bb" ); |
| 9211 | |
| 9212 | // Check the basic block. |
| 9213 | if (Label.Kind == ValID::t_LocalID) |
| 9214 | return error(L: Label.Loc, Msg: "invalid numeric label in uselistorder_bb" ); |
| 9215 | if (Label.Kind != ValID::t_LocalName) |
| 9216 | return error(L: Label.Loc, Msg: "expected basic block name in uselistorder_bb" ); |
| 9217 | Value *V = F->getValueSymbolTable()->lookup(Name: Label.StrVal); |
| 9218 | if (!V) |
| 9219 | return error(L: Label.Loc, Msg: "invalid basic block in uselistorder_bb" ); |
| 9220 | if (!isa<BasicBlock>(Val: V)) |
| 9221 | return error(L: Label.Loc, Msg: "expected basic block in uselistorder_bb" ); |
| 9222 | |
| 9223 | return sortUseListOrder(V, Indexes, Loc); |
| 9224 | } |
| 9225 | |
| 9226 | /// ModuleEntry |
| 9227 | /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' |
| 9228 | /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' |
| 9229 | bool LLParser::parseModuleEntry(unsigned ID) { |
| 9230 | assert(Lex.getKind() == lltok::kw_module); |
| 9231 | Lex.Lex(); |
| 9232 | |
| 9233 | std::string Path; |
| 9234 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9235 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9236 | parseToken(T: lltok::kw_path, ErrMsg: "expected 'path' here" ) || |
| 9237 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9238 | parseStringConstant(Result&: Path) || |
| 9239 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9240 | parseToken(T: lltok::kw_hash, ErrMsg: "expected 'hash' here" ) || |
| 9241 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9242 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9243 | return true; |
| 9244 | |
| 9245 | ModuleHash Hash; |
| 9246 | if (parseUInt32(Val&: Hash[0]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9247 | parseUInt32(Val&: Hash[1]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9248 | parseUInt32(Val&: Hash[2]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9249 | parseUInt32(Val&: Hash[3]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9250 | parseUInt32(Val&: Hash[4])) |
| 9251 | return true; |
| 9252 | |
| 9253 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" ) || |
| 9254 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9255 | return true; |
| 9256 | |
| 9257 | auto ModuleEntry = Index->addModule(ModPath: Path, Hash); |
| 9258 | ModuleIdMap[ID] = ModuleEntry->first(); |
| 9259 | |
| 9260 | return false; |
| 9261 | } |
| 9262 | |
| 9263 | /// TypeIdEntry |
| 9264 | /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' |
| 9265 | bool LLParser::parseTypeIdEntry(unsigned ID) { |
| 9266 | assert(Lex.getKind() == lltok::kw_typeid); |
| 9267 | Lex.Lex(); |
| 9268 | |
| 9269 | std::string Name; |
| 9270 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9271 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9272 | parseToken(T: lltok::kw_name, ErrMsg: "expected 'name' here" ) || |
| 9273 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9274 | parseStringConstant(Result&: Name)) |
| 9275 | return true; |
| 9276 | |
| 9277 | TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(TypeId: Name); |
| 9278 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9279 | parseTypeIdSummary(TIS) || parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9280 | return true; |
| 9281 | |
| 9282 | // Check if this ID was forward referenced, and if so, update the |
| 9283 | // corresponding GUIDs. |
| 9284 | auto FwdRefTIDs = ForwardRefTypeIds.find(x: ID); |
| 9285 | if (FwdRefTIDs != ForwardRefTypeIds.end()) { |
| 9286 | for (auto TIDRef : FwdRefTIDs->second) { |
| 9287 | assert(!*TIDRef.first && |
| 9288 | "Forward referenced type id GUID expected to be 0" ); |
| 9289 | *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: Name); |
| 9290 | } |
| 9291 | ForwardRefTypeIds.erase(position: FwdRefTIDs); |
| 9292 | } |
| 9293 | |
| 9294 | return false; |
| 9295 | } |
| 9296 | |
| 9297 | /// TypeIdSummary |
| 9298 | /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' |
| 9299 | bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { |
| 9300 | if (parseToken(T: lltok::kw_summary, ErrMsg: "expected 'summary' here" ) || |
| 9301 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9302 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9303 | parseTypeTestResolution(TTRes&: TIS.TTRes)) |
| 9304 | return true; |
| 9305 | |
| 9306 | if (EatIfPresent(T: lltok::comma)) { |
| 9307 | // Expect optional wpdResolutions field |
| 9308 | if (parseOptionalWpdResolutions(WPDResMap&: TIS.WPDRes)) |
| 9309 | return true; |
| 9310 | } |
| 9311 | |
| 9312 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9313 | return true; |
| 9314 | |
| 9315 | return false; |
| 9316 | } |
| 9317 | |
| 9318 | static ValueInfo EmptyVI = |
| 9319 | ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); |
| 9320 | |
| 9321 | /// TypeIdCompatibleVtableEntry |
| 9322 | /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' |
| 9323 | /// TypeIdCompatibleVtableInfo |
| 9324 | /// ')' |
| 9325 | bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { |
| 9326 | assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); |
| 9327 | Lex.Lex(); |
| 9328 | |
| 9329 | std::string Name; |
| 9330 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9331 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9332 | parseToken(T: lltok::kw_name, ErrMsg: "expected 'name' here" ) || |
| 9333 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9334 | parseStringConstant(Result&: Name)) |
| 9335 | return true; |
| 9336 | |
| 9337 | TypeIdCompatibleVtableInfo &TI = |
| 9338 | Index->getOrInsertTypeIdCompatibleVtableSummary(TypeId: Name); |
| 9339 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9340 | parseToken(T: lltok::kw_summary, ErrMsg: "expected 'summary' here" ) || |
| 9341 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9342 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9343 | return true; |
| 9344 | |
| 9345 | IdToIndexMapType IdToIndexMap; |
| 9346 | // parse each call edge |
| 9347 | do { |
| 9348 | uint64_t Offset; |
| 9349 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9350 | parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here" ) || |
| 9351 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || parseUInt64(Val&: Offset) || |
| 9352 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" )) |
| 9353 | return true; |
| 9354 | |
| 9355 | LocTy Loc = Lex.getLoc(); |
| 9356 | unsigned GVId; |
| 9357 | ValueInfo VI; |
| 9358 | if (parseGVReference(VI, GVId)) |
| 9359 | return true; |
| 9360 | |
| 9361 | // Keep track of the TypeIdCompatibleVtableInfo array index needing a |
| 9362 | // forward reference. We will save the location of the ValueInfo needing an |
| 9363 | // update, but can only do so once the std::vector is finalized. |
| 9364 | if (VI == EmptyVI) |
| 9365 | IdToIndexMap[GVId].push_back(x: std::make_pair(x: TI.size(), y&: Loc)); |
| 9366 | TI.push_back(x: {Offset, VI}); |
| 9367 | |
| 9368 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in call" )) |
| 9369 | return true; |
| 9370 | } while (EatIfPresent(T: lltok::comma)); |
| 9371 | |
| 9372 | // Now that the TI vector is finalized, it is safe to save the locations |
| 9373 | // of any forward GV references that need updating later. |
| 9374 | for (auto I : IdToIndexMap) { |
| 9375 | auto &Infos = ForwardRefValueInfos[I.first]; |
| 9376 | for (auto P : I.second) { |
| 9377 | assert(TI[P.first].VTableVI == EmptyVI && |
| 9378 | "Forward referenced ValueInfo expected to be empty" ); |
| 9379 | Infos.emplace_back(args: &TI[P.first].VTableVI, args&: P.second); |
| 9380 | } |
| 9381 | } |
| 9382 | |
| 9383 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" ) || |
| 9384 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9385 | return true; |
| 9386 | |
| 9387 | // Check if this ID was forward referenced, and if so, update the |
| 9388 | // corresponding GUIDs. |
| 9389 | auto FwdRefTIDs = ForwardRefTypeIds.find(x: ID); |
| 9390 | if (FwdRefTIDs != ForwardRefTypeIds.end()) { |
| 9391 | for (auto TIDRef : FwdRefTIDs->second) { |
| 9392 | assert(!*TIDRef.first && |
| 9393 | "Forward referenced type id GUID expected to be 0" ); |
| 9394 | *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: Name); |
| 9395 | } |
| 9396 | ForwardRefTypeIds.erase(position: FwdRefTIDs); |
| 9397 | } |
| 9398 | |
| 9399 | return false; |
| 9400 | } |
| 9401 | |
| 9402 | /// TypeTestResolution |
| 9403 | /// ::= 'typeTestRes' ':' '(' 'kind' ':' |
| 9404 | /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' |
| 9405 | /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? |
| 9406 | /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? |
| 9407 | /// [',' 'inlinesBits' ':' UInt64]? ')' |
| 9408 | bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { |
| 9409 | if (parseToken(T: lltok::kw_typeTestRes, ErrMsg: "expected 'typeTestRes' here" ) || |
| 9410 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9411 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9412 | parseToken(T: lltok::kw_kind, ErrMsg: "expected 'kind' here" ) || |
| 9413 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 9414 | return true; |
| 9415 | |
| 9416 | switch (Lex.getKind()) { |
| 9417 | case lltok::kw_unknown: |
| 9418 | TTRes.TheKind = TypeTestResolution::Unknown; |
| 9419 | break; |
| 9420 | case lltok::kw_unsat: |
| 9421 | TTRes.TheKind = TypeTestResolution::Unsat; |
| 9422 | break; |
| 9423 | case lltok::kw_byteArray: |
| 9424 | TTRes.TheKind = TypeTestResolution::ByteArray; |
| 9425 | break; |
| 9426 | case lltok::kw_inline: |
| 9427 | TTRes.TheKind = TypeTestResolution::Inline; |
| 9428 | break; |
| 9429 | case lltok::kw_single: |
| 9430 | TTRes.TheKind = TypeTestResolution::Single; |
| 9431 | break; |
| 9432 | case lltok::kw_allOnes: |
| 9433 | TTRes.TheKind = TypeTestResolution::AllOnes; |
| 9434 | break; |
| 9435 | default: |
| 9436 | return error(L: Lex.getLoc(), Msg: "unexpected TypeTestResolution kind" ); |
| 9437 | } |
| 9438 | Lex.Lex(); |
| 9439 | |
| 9440 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9441 | parseToken(T: lltok::kw_sizeM1BitWidth, ErrMsg: "expected 'sizeM1BitWidth' here" ) || |
| 9442 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9443 | parseUInt32(Val&: TTRes.SizeM1BitWidth)) |
| 9444 | return true; |
| 9445 | |
| 9446 | // parse optional fields |
| 9447 | while (EatIfPresent(T: lltok::comma)) { |
| 9448 | switch (Lex.getKind()) { |
| 9449 | case lltok::kw_alignLog2: |
| 9450 | Lex.Lex(); |
| 9451 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || |
| 9452 | parseUInt64(Val&: TTRes.AlignLog2)) |
| 9453 | return true; |
| 9454 | break; |
| 9455 | case lltok::kw_sizeM1: |
| 9456 | Lex.Lex(); |
| 9457 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseUInt64(Val&: TTRes.SizeM1)) |
| 9458 | return true; |
| 9459 | break; |
| 9460 | case lltok::kw_bitMask: { |
| 9461 | unsigned Val; |
| 9462 | Lex.Lex(); |
| 9463 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseUInt32(Val)) |
| 9464 | return true; |
| 9465 | assert(Val <= 0xff); |
| 9466 | TTRes.BitMask = (uint8_t)Val; |
| 9467 | break; |
| 9468 | } |
| 9469 | case lltok::kw_inlineBits: |
| 9470 | Lex.Lex(); |
| 9471 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || |
| 9472 | parseUInt64(Val&: TTRes.InlineBits)) |
| 9473 | return true; |
| 9474 | break; |
| 9475 | default: |
| 9476 | return error(L: Lex.getLoc(), Msg: "expected optional TypeTestResolution field" ); |
| 9477 | } |
| 9478 | } |
| 9479 | |
| 9480 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9481 | return true; |
| 9482 | |
| 9483 | return false; |
| 9484 | } |
| 9485 | |
| 9486 | /// OptionalWpdResolutions |
| 9487 | /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' |
| 9488 | /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' |
| 9489 | bool LLParser::parseOptionalWpdResolutions( |
| 9490 | std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { |
| 9491 | if (parseToken(T: lltok::kw_wpdResolutions, ErrMsg: "expected 'wpdResolutions' here" ) || |
| 9492 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9493 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9494 | return true; |
| 9495 | |
| 9496 | do { |
| 9497 | uint64_t Offset; |
| 9498 | WholeProgramDevirtResolution WPDRes; |
| 9499 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9500 | parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here" ) || |
| 9501 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || parseUInt64(Val&: Offset) || |
| 9502 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || parseWpdRes(WPDRes) || |
| 9503 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9504 | return true; |
| 9505 | WPDResMap[Offset] = WPDRes; |
| 9506 | } while (EatIfPresent(T: lltok::comma)); |
| 9507 | |
| 9508 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9509 | return true; |
| 9510 | |
| 9511 | return false; |
| 9512 | } |
| 9513 | |
| 9514 | /// WpdRes |
| 9515 | /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' |
| 9516 | /// [',' OptionalResByArg]? ')' |
| 9517 | /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' |
| 9518 | /// ',' 'singleImplName' ':' STRINGCONSTANT ',' |
| 9519 | /// [',' OptionalResByArg]? ')' |
| 9520 | /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' |
| 9521 | /// [',' OptionalResByArg]? ')' |
| 9522 | bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { |
| 9523 | if (parseToken(T: lltok::kw_wpdRes, ErrMsg: "expected 'wpdRes' here" ) || |
| 9524 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9525 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9526 | parseToken(T: lltok::kw_kind, ErrMsg: "expected 'kind' here" ) || |
| 9527 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 9528 | return true; |
| 9529 | |
| 9530 | switch (Lex.getKind()) { |
| 9531 | case lltok::kw_indir: |
| 9532 | WPDRes.TheKind = WholeProgramDevirtResolution::Indir; |
| 9533 | break; |
| 9534 | case lltok::kw_singleImpl: |
| 9535 | WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; |
| 9536 | break; |
| 9537 | case lltok::kw_branchFunnel: |
| 9538 | WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; |
| 9539 | break; |
| 9540 | default: |
| 9541 | return error(L: Lex.getLoc(), Msg: "unexpected WholeProgramDevirtResolution kind" ); |
| 9542 | } |
| 9543 | Lex.Lex(); |
| 9544 | |
| 9545 | // parse optional fields |
| 9546 | while (EatIfPresent(T: lltok::comma)) { |
| 9547 | switch (Lex.getKind()) { |
| 9548 | case lltok::kw_singleImplName: |
| 9549 | Lex.Lex(); |
| 9550 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9551 | parseStringConstant(Result&: WPDRes.SingleImplName)) |
| 9552 | return true; |
| 9553 | break; |
| 9554 | case lltok::kw_resByArg: |
| 9555 | if (parseOptionalResByArg(ResByArg&: WPDRes.ResByArg)) |
| 9556 | return true; |
| 9557 | break; |
| 9558 | default: |
| 9559 | return error(L: Lex.getLoc(), |
| 9560 | Msg: "expected optional WholeProgramDevirtResolution field" ); |
| 9561 | } |
| 9562 | } |
| 9563 | |
| 9564 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9565 | return true; |
| 9566 | |
| 9567 | return false; |
| 9568 | } |
| 9569 | |
| 9570 | /// OptionalResByArg |
| 9571 | /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' |
| 9572 | /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' |
| 9573 | /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | |
| 9574 | /// 'virtualConstProp' ) |
| 9575 | /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? |
| 9576 | /// [',' 'bit' ':' UInt32]? ')' |
| 9577 | bool LLParser::parseOptionalResByArg( |
| 9578 | std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> |
| 9579 | &ResByArg) { |
| 9580 | if (parseToken(T: lltok::kw_resByArg, ErrMsg: "expected 'resByArg' here" ) || |
| 9581 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9582 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9583 | return true; |
| 9584 | |
| 9585 | do { |
| 9586 | std::vector<uint64_t> Args; |
| 9587 | if (parseArgs(Args) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9588 | parseToken(T: lltok::kw_byArg, ErrMsg: "expected 'byArg here" ) || |
| 9589 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9590 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9591 | parseToken(T: lltok::kw_kind, ErrMsg: "expected 'kind' here" ) || |
| 9592 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 9593 | return true; |
| 9594 | |
| 9595 | WholeProgramDevirtResolution::ByArg ByArg; |
| 9596 | switch (Lex.getKind()) { |
| 9597 | case lltok::kw_indir: |
| 9598 | ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; |
| 9599 | break; |
| 9600 | case lltok::kw_uniformRetVal: |
| 9601 | ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; |
| 9602 | break; |
| 9603 | case lltok::kw_uniqueRetVal: |
| 9604 | ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; |
| 9605 | break; |
| 9606 | case lltok::kw_virtualConstProp: |
| 9607 | ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; |
| 9608 | break; |
| 9609 | default: |
| 9610 | return error(L: Lex.getLoc(), |
| 9611 | Msg: "unexpected WholeProgramDevirtResolution::ByArg kind" ); |
| 9612 | } |
| 9613 | Lex.Lex(); |
| 9614 | |
| 9615 | // parse optional fields |
| 9616 | while (EatIfPresent(T: lltok::comma)) { |
| 9617 | switch (Lex.getKind()) { |
| 9618 | case lltok::kw_info: |
| 9619 | Lex.Lex(); |
| 9620 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9621 | parseUInt64(Val&: ByArg.Info)) |
| 9622 | return true; |
| 9623 | break; |
| 9624 | case lltok::kw_byte: |
| 9625 | Lex.Lex(); |
| 9626 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9627 | parseUInt32(Val&: ByArg.Byte)) |
| 9628 | return true; |
| 9629 | break; |
| 9630 | case lltok::kw_bit: |
| 9631 | Lex.Lex(); |
| 9632 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9633 | parseUInt32(Val&: ByArg.Bit)) |
| 9634 | return true; |
| 9635 | break; |
| 9636 | default: |
| 9637 | return error(L: Lex.getLoc(), |
| 9638 | Msg: "expected optional whole program devirt field" ); |
| 9639 | } |
| 9640 | } |
| 9641 | |
| 9642 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9643 | return true; |
| 9644 | |
| 9645 | ResByArg[Args] = ByArg; |
| 9646 | } while (EatIfPresent(T: lltok::comma)); |
| 9647 | |
| 9648 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9649 | return true; |
| 9650 | |
| 9651 | return false; |
| 9652 | } |
| 9653 | |
| 9654 | /// OptionalResByArg |
| 9655 | /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' |
| 9656 | bool LLParser::parseArgs(std::vector<uint64_t> &Args) { |
| 9657 | if (parseToken(T: lltok::kw_args, ErrMsg: "expected 'args' here" ) || |
| 9658 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9659 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9660 | return true; |
| 9661 | |
| 9662 | do { |
| 9663 | uint64_t Val; |
| 9664 | if (parseUInt64(Val)) |
| 9665 | return true; |
| 9666 | Args.push_back(x: Val); |
| 9667 | } while (EatIfPresent(T: lltok::comma)); |
| 9668 | |
| 9669 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9670 | return true; |
| 9671 | |
| 9672 | return false; |
| 9673 | } |
| 9674 | |
| 9675 | static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; |
| 9676 | |
| 9677 | static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { |
| 9678 | bool ReadOnly = Fwd->isReadOnly(); |
| 9679 | bool WriteOnly = Fwd->isWriteOnly(); |
| 9680 | assert(!(ReadOnly && WriteOnly)); |
| 9681 | *Fwd = Resolved; |
| 9682 | if (ReadOnly) |
| 9683 | Fwd->setReadOnly(); |
| 9684 | if (WriteOnly) |
| 9685 | Fwd->setWriteOnly(); |
| 9686 | } |
| 9687 | |
| 9688 | /// Stores the given Name/GUID and associated summary into the Index. |
| 9689 | /// Also updates any forward references to the associated entry ID. |
| 9690 | bool LLParser::addGlobalValueToIndex( |
| 9691 | std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, |
| 9692 | unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) { |
| 9693 | // First create the ValueInfo utilizing the Name or GUID. |
| 9694 | ValueInfo VI; |
| 9695 | if (GUID != 0) { |
| 9696 | assert(Name.empty()); |
| 9697 | VI = Index->getOrInsertValueInfo(GUID); |
| 9698 | } else { |
| 9699 | assert(!Name.empty()); |
| 9700 | if (M) { |
| 9701 | auto *GV = M->getNamedValue(Name); |
| 9702 | if (!GV) |
| 9703 | return error(L: Loc, Msg: "Reference to undefined global \"" + Name + "\"" ); |
| 9704 | |
| 9705 | VI = Index->getOrInsertValueInfo(GV); |
| 9706 | } else { |
| 9707 | assert( |
| 9708 | (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && |
| 9709 | "Need a source_filename to compute GUID for local" ); |
| 9710 | GUID = GlobalValue::getGUIDAssumingExternalLinkage( |
| 9711 | GlobalName: GlobalValue::getGlobalIdentifier(Name, Linkage, FileName: SourceFileName)); |
| 9712 | VI = Index->getOrInsertValueInfo(GUID, Name: Index->saveString(String: Name)); |
| 9713 | } |
| 9714 | } |
| 9715 | |
| 9716 | // Resolve forward references from calls/refs |
| 9717 | auto FwdRefVIs = ForwardRefValueInfos.find(x: ID); |
| 9718 | if (FwdRefVIs != ForwardRefValueInfos.end()) { |
| 9719 | for (auto VIRef : FwdRefVIs->second) { |
| 9720 | assert(VIRef.first->getRef() == FwdVIRef && |
| 9721 | "Forward referenced ValueInfo expected to be empty" ); |
| 9722 | resolveFwdRef(Fwd: VIRef.first, Resolved&: VI); |
| 9723 | } |
| 9724 | ForwardRefValueInfos.erase(position: FwdRefVIs); |
| 9725 | } |
| 9726 | |
| 9727 | // Resolve forward references from aliases |
| 9728 | auto FwdRefAliasees = ForwardRefAliasees.find(x: ID); |
| 9729 | if (FwdRefAliasees != ForwardRefAliasees.end()) { |
| 9730 | for (auto AliaseeRef : FwdRefAliasees->second) { |
| 9731 | assert(!AliaseeRef.first->hasAliasee() && |
| 9732 | "Forward referencing alias already has aliasee" ); |
| 9733 | assert(Summary && "Aliasee must be a definition" ); |
| 9734 | AliaseeRef.first->setAliasee(AliaseeVI&: VI, Aliasee: Summary.get()); |
| 9735 | } |
| 9736 | ForwardRefAliasees.erase(position: FwdRefAliasees); |
| 9737 | } |
| 9738 | |
| 9739 | // Add the summary if one was provided. |
| 9740 | if (Summary) |
| 9741 | Index->addGlobalValueSummary(VI, Summary: std::move(Summary)); |
| 9742 | |
| 9743 | // Save the associated ValueInfo for use in later references by ID. |
| 9744 | if (ID == NumberedValueInfos.size()) |
| 9745 | NumberedValueInfos.push_back(x: VI); |
| 9746 | else { |
| 9747 | // Handle non-continuous numbers (to make test simplification easier). |
| 9748 | if (ID > NumberedValueInfos.size()) |
| 9749 | NumberedValueInfos.resize(new_size: ID + 1); |
| 9750 | NumberedValueInfos[ID] = VI; |
| 9751 | } |
| 9752 | |
| 9753 | return false; |
| 9754 | } |
| 9755 | |
| 9756 | /// parseSummaryIndexFlags |
| 9757 | /// ::= 'flags' ':' UInt64 |
| 9758 | bool LLParser::parseSummaryIndexFlags() { |
| 9759 | assert(Lex.getKind() == lltok::kw_flags); |
| 9760 | Lex.Lex(); |
| 9761 | |
| 9762 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 9763 | return true; |
| 9764 | uint64_t Flags; |
| 9765 | if (parseUInt64(Val&: Flags)) |
| 9766 | return true; |
| 9767 | if (Index) |
| 9768 | Index->setFlags(Flags); |
| 9769 | return false; |
| 9770 | } |
| 9771 | |
| 9772 | /// parseBlockCount |
| 9773 | /// ::= 'blockcount' ':' UInt64 |
| 9774 | bool LLParser::parseBlockCount() { |
| 9775 | assert(Lex.getKind() == lltok::kw_blockcount); |
| 9776 | Lex.Lex(); |
| 9777 | |
| 9778 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 9779 | return true; |
| 9780 | uint64_t BlockCount; |
| 9781 | if (parseUInt64(Val&: BlockCount)) |
| 9782 | return true; |
| 9783 | if (Index) |
| 9784 | Index->setBlockCount(BlockCount); |
| 9785 | return false; |
| 9786 | } |
| 9787 | |
| 9788 | /// parseGVEntry |
| 9789 | /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) |
| 9790 | /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' |
| 9791 | /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' |
| 9792 | bool LLParser::parseGVEntry(unsigned ID) { |
| 9793 | assert(Lex.getKind() == lltok::kw_gv); |
| 9794 | Lex.Lex(); |
| 9795 | |
| 9796 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9797 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9798 | return true; |
| 9799 | |
| 9800 | LocTy Loc = Lex.getLoc(); |
| 9801 | std::string Name; |
| 9802 | GlobalValue::GUID GUID = 0; |
| 9803 | switch (Lex.getKind()) { |
| 9804 | case lltok::kw_name: |
| 9805 | Lex.Lex(); |
| 9806 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9807 | parseStringConstant(Result&: Name)) |
| 9808 | return true; |
| 9809 | // Can't create GUID/ValueInfo until we have the linkage. |
| 9810 | break; |
| 9811 | case lltok::kw_guid: |
| 9812 | Lex.Lex(); |
| 9813 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || parseUInt64(Val&: GUID)) |
| 9814 | return true; |
| 9815 | break; |
| 9816 | default: |
| 9817 | return error(L: Lex.getLoc(), Msg: "expected name or guid tag" ); |
| 9818 | } |
| 9819 | |
| 9820 | if (!EatIfPresent(T: lltok::comma)) { |
| 9821 | // No summaries. Wrap up. |
| 9822 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9823 | return true; |
| 9824 | // This was created for a call to an external or indirect target. |
| 9825 | // A GUID with no summary came from a VALUE_GUID record, dummy GUID |
| 9826 | // created for indirect calls with VP. A Name with no GUID came from |
| 9827 | // an external definition. We pass ExternalLinkage since that is only |
| 9828 | // used when the GUID must be computed from Name, and in that case |
| 9829 | // the symbol must have external linkage. |
| 9830 | return addGlobalValueToIndex(Name, GUID, Linkage: GlobalValue::ExternalLinkage, ID, |
| 9831 | Summary: nullptr, Loc); |
| 9832 | } |
| 9833 | |
| 9834 | // Have a list of summaries |
| 9835 | if (parseToken(T: lltok::kw_summaries, ErrMsg: "expected 'summaries' here" ) || |
| 9836 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9837 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 9838 | return true; |
| 9839 | do { |
| 9840 | switch (Lex.getKind()) { |
| 9841 | case lltok::kw_function: |
| 9842 | if (parseFunctionSummary(Name, GUID, ID)) |
| 9843 | return true; |
| 9844 | break; |
| 9845 | case lltok::kw_variable: |
| 9846 | if (parseVariableSummary(Name, GUID, ID)) |
| 9847 | return true; |
| 9848 | break; |
| 9849 | case lltok::kw_alias: |
| 9850 | if (parseAliasSummary(Name, GUID, ID)) |
| 9851 | return true; |
| 9852 | break; |
| 9853 | default: |
| 9854 | return error(L: Lex.getLoc(), Msg: "expected summary type" ); |
| 9855 | } |
| 9856 | } while (EatIfPresent(T: lltok::comma)); |
| 9857 | |
| 9858 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" ) || |
| 9859 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9860 | return true; |
| 9861 | |
| 9862 | return false; |
| 9863 | } |
| 9864 | |
| 9865 | /// FunctionSummary |
| 9866 | /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags |
| 9867 | /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? |
| 9868 | /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? |
| 9869 | /// [',' OptionalRefs]? ')' |
| 9870 | bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, |
| 9871 | unsigned ID) { |
| 9872 | LocTy Loc = Lex.getLoc(); |
| 9873 | assert(Lex.getKind() == lltok::kw_function); |
| 9874 | Lex.Lex(); |
| 9875 | |
| 9876 | StringRef ModulePath; |
| 9877 | GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( |
| 9878 | GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, |
| 9879 | /*NotEligibleToImport=*/false, |
| 9880 | /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, |
| 9881 | GlobalValueSummary::Definition); |
| 9882 | unsigned InstCount; |
| 9883 | SmallVector<FunctionSummary::EdgeTy, 0> Calls; |
| 9884 | FunctionSummary::TypeIdInfo TypeIdInfo; |
| 9885 | std::vector<FunctionSummary::ParamAccess> ParamAccesses; |
| 9886 | SmallVector<ValueInfo, 0> Refs; |
| 9887 | std::vector<CallsiteInfo> Callsites; |
| 9888 | std::vector<AllocInfo> Allocs; |
| 9889 | // Default is all-zeros (conservative values). |
| 9890 | FunctionSummary::FFlags FFlags = {}; |
| 9891 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9892 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9893 | parseModuleReference(ModulePath) || |
| 9894 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || parseGVFlags(GVFlags) || |
| 9895 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9896 | parseToken(T: lltok::kw_insts, ErrMsg: "expected 'insts' here" ) || |
| 9897 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || parseUInt32(Val&: InstCount)) |
| 9898 | return true; |
| 9899 | |
| 9900 | // parse optional fields |
| 9901 | while (EatIfPresent(T: lltok::comma)) { |
| 9902 | switch (Lex.getKind()) { |
| 9903 | case lltok::kw_funcFlags: |
| 9904 | if (parseOptionalFFlags(FFlags)) |
| 9905 | return true; |
| 9906 | break; |
| 9907 | case lltok::kw_calls: |
| 9908 | if (parseOptionalCalls(Calls)) |
| 9909 | return true; |
| 9910 | break; |
| 9911 | case lltok::kw_typeIdInfo: |
| 9912 | if (parseOptionalTypeIdInfo(TypeIdInfo)) |
| 9913 | return true; |
| 9914 | break; |
| 9915 | case lltok::kw_refs: |
| 9916 | if (parseOptionalRefs(Refs)) |
| 9917 | return true; |
| 9918 | break; |
| 9919 | case lltok::kw_params: |
| 9920 | if (parseOptionalParamAccesses(Params&: ParamAccesses)) |
| 9921 | return true; |
| 9922 | break; |
| 9923 | case lltok::kw_allocs: |
| 9924 | if (parseOptionalAllocs(Allocs)) |
| 9925 | return true; |
| 9926 | break; |
| 9927 | case lltok::kw_callsites: |
| 9928 | if (parseOptionalCallsites(Callsites)) |
| 9929 | return true; |
| 9930 | break; |
| 9931 | default: |
| 9932 | return error(L: Lex.getLoc(), Msg: "expected optional function summary field" ); |
| 9933 | } |
| 9934 | } |
| 9935 | |
| 9936 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 9937 | return true; |
| 9938 | |
| 9939 | auto FS = std::make_unique<FunctionSummary>( |
| 9940 | args&: GVFlags, args&: InstCount, args&: FFlags, args: std::move(Refs), args: std::move(Calls), |
| 9941 | args: std::move(TypeIdInfo.TypeTests), |
| 9942 | args: std::move(TypeIdInfo.TypeTestAssumeVCalls), |
| 9943 | args: std::move(TypeIdInfo.TypeCheckedLoadVCalls), |
| 9944 | args: std::move(TypeIdInfo.TypeTestAssumeConstVCalls), |
| 9945 | args: std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), |
| 9946 | args: std::move(ParamAccesses), args: std::move(Callsites), args: std::move(Allocs)); |
| 9947 | |
| 9948 | FS->setModulePath(ModulePath); |
| 9949 | |
| 9950 | return addGlobalValueToIndex(Name, GUID, |
| 9951 | Linkage: (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, |
| 9952 | Summary: std::move(FS), Loc); |
| 9953 | } |
| 9954 | |
| 9955 | /// VariableSummary |
| 9956 | /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags |
| 9957 | /// [',' OptionalRefs]? ')' |
| 9958 | bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, |
| 9959 | unsigned ID) { |
| 9960 | LocTy Loc = Lex.getLoc(); |
| 9961 | assert(Lex.getKind() == lltok::kw_variable); |
| 9962 | Lex.Lex(); |
| 9963 | |
| 9964 | StringRef ModulePath; |
| 9965 | GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( |
| 9966 | GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, |
| 9967 | /*NotEligibleToImport=*/false, |
| 9968 | /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, |
| 9969 | GlobalValueSummary::Definition); |
| 9970 | GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, |
| 9971 | /* WriteOnly */ false, |
| 9972 | /* Constant */ false, |
| 9973 | GlobalObject::VCallVisibilityPublic); |
| 9974 | SmallVector<ValueInfo, 0> Refs; |
| 9975 | VTableFuncList VTableFuncs; |
| 9976 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 9977 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 9978 | parseModuleReference(ModulePath) || |
| 9979 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || parseGVFlags(GVFlags) || |
| 9980 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 9981 | parseGVarFlags(GVarFlags)) |
| 9982 | return true; |
| 9983 | |
| 9984 | // parse optional fields |
| 9985 | while (EatIfPresent(T: lltok::comma)) { |
| 9986 | switch (Lex.getKind()) { |
| 9987 | case lltok::kw_vTableFuncs: |
| 9988 | if (parseOptionalVTableFuncs(VTableFuncs)) |
| 9989 | return true; |
| 9990 | break; |
| 9991 | case lltok::kw_refs: |
| 9992 | if (parseOptionalRefs(Refs)) |
| 9993 | return true; |
| 9994 | break; |
| 9995 | default: |
| 9996 | return error(L: Lex.getLoc(), Msg: "expected optional variable summary field" ); |
| 9997 | } |
| 9998 | } |
| 9999 | |
| 10000 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10001 | return true; |
| 10002 | |
| 10003 | auto GS = |
| 10004 | std::make_unique<GlobalVarSummary>(args&: GVFlags, args&: GVarFlags, args: std::move(Refs)); |
| 10005 | |
| 10006 | GS->setModulePath(ModulePath); |
| 10007 | GS->setVTableFuncs(std::move(VTableFuncs)); |
| 10008 | |
| 10009 | return addGlobalValueToIndex(Name, GUID, |
| 10010 | Linkage: (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, |
| 10011 | Summary: std::move(GS), Loc); |
| 10012 | } |
| 10013 | |
| 10014 | /// AliasSummary |
| 10015 | /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' |
| 10016 | /// 'aliasee' ':' GVReference ')' |
| 10017 | bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, |
| 10018 | unsigned ID) { |
| 10019 | assert(Lex.getKind() == lltok::kw_alias); |
| 10020 | LocTy Loc = Lex.getLoc(); |
| 10021 | Lex.Lex(); |
| 10022 | |
| 10023 | StringRef ModulePath; |
| 10024 | GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( |
| 10025 | GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, |
| 10026 | /*NotEligibleToImport=*/false, |
| 10027 | /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, |
| 10028 | GlobalValueSummary::Definition); |
| 10029 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10030 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 10031 | parseModuleReference(ModulePath) || |
| 10032 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || parseGVFlags(GVFlags) || |
| 10033 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 10034 | parseToken(T: lltok::kw_aliasee, ErrMsg: "expected 'aliasee' here" ) || |
| 10035 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 10036 | return true; |
| 10037 | |
| 10038 | ValueInfo AliaseeVI; |
| 10039 | unsigned GVId; |
| 10040 | auto AS = std::make_unique<AliasSummary>(args&: GVFlags); |
| 10041 | AS->setModulePath(ModulePath); |
| 10042 | |
| 10043 | if (!EatIfPresent(T: lltok::kw_null)) { |
| 10044 | if (parseGVReference(VI&: AliaseeVI, GVId)) |
| 10045 | return true; |
| 10046 | |
| 10047 | // Record forward reference if the aliasee is not parsed yet. |
| 10048 | if (AliaseeVI.getRef() == FwdVIRef) { |
| 10049 | ForwardRefAliasees[GVId].emplace_back(args: AS.get(), args&: Loc); |
| 10050 | } else { |
| 10051 | auto Summary = Index->findSummaryInModule(VI: AliaseeVI, ModuleId: ModulePath); |
| 10052 | assert(Summary && "Aliasee must be a definition" ); |
| 10053 | AS->setAliasee(AliaseeVI, Aliasee: Summary); |
| 10054 | } |
| 10055 | } |
| 10056 | |
| 10057 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10058 | return true; |
| 10059 | |
| 10060 | return addGlobalValueToIndex(Name, GUID, |
| 10061 | Linkage: (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, |
| 10062 | Summary: std::move(AS), Loc); |
| 10063 | } |
| 10064 | |
| 10065 | /// Flag |
| 10066 | /// ::= [0|1] |
| 10067 | bool LLParser::parseFlag(unsigned &Val) { |
| 10068 | if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) |
| 10069 | return tokError(Msg: "expected integer" ); |
| 10070 | Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); |
| 10071 | Lex.Lex(); |
| 10072 | return false; |
| 10073 | } |
| 10074 | |
| 10075 | /// OptionalFFlags |
| 10076 | /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? |
| 10077 | /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? |
| 10078 | /// [',' 'returnDoesNotAlias' ':' Flag]? ')' |
| 10079 | /// [',' 'noInline' ':' Flag]? ')' |
| 10080 | /// [',' 'alwaysInline' ':' Flag]? ')' |
| 10081 | /// [',' 'noUnwind' ':' Flag]? ')' |
| 10082 | /// [',' 'mayThrow' ':' Flag]? ')' |
| 10083 | /// [',' 'hasUnknownCall' ':' Flag]? ')' |
| 10084 | /// [',' 'mustBeUnreachable' ':' Flag]? ')' |
| 10085 | |
| 10086 | bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { |
| 10087 | assert(Lex.getKind() == lltok::kw_funcFlags); |
| 10088 | Lex.Lex(); |
| 10089 | |
| 10090 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in funcFlags" ) || |
| 10091 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in funcFlags" )) |
| 10092 | return true; |
| 10093 | |
| 10094 | do { |
| 10095 | unsigned Val = 0; |
| 10096 | switch (Lex.getKind()) { |
| 10097 | case lltok::kw_readNone: |
| 10098 | Lex.Lex(); |
| 10099 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10100 | return true; |
| 10101 | FFlags.ReadNone = Val; |
| 10102 | break; |
| 10103 | case lltok::kw_readOnly: |
| 10104 | Lex.Lex(); |
| 10105 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10106 | return true; |
| 10107 | FFlags.ReadOnly = Val; |
| 10108 | break; |
| 10109 | case lltok::kw_noRecurse: |
| 10110 | Lex.Lex(); |
| 10111 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10112 | return true; |
| 10113 | FFlags.NoRecurse = Val; |
| 10114 | break; |
| 10115 | case lltok::kw_returnDoesNotAlias: |
| 10116 | Lex.Lex(); |
| 10117 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10118 | return true; |
| 10119 | FFlags.ReturnDoesNotAlias = Val; |
| 10120 | break; |
| 10121 | case lltok::kw_noInline: |
| 10122 | Lex.Lex(); |
| 10123 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10124 | return true; |
| 10125 | FFlags.NoInline = Val; |
| 10126 | break; |
| 10127 | case lltok::kw_alwaysInline: |
| 10128 | Lex.Lex(); |
| 10129 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10130 | return true; |
| 10131 | FFlags.AlwaysInline = Val; |
| 10132 | break; |
| 10133 | case lltok::kw_noUnwind: |
| 10134 | Lex.Lex(); |
| 10135 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10136 | return true; |
| 10137 | FFlags.NoUnwind = Val; |
| 10138 | break; |
| 10139 | case lltok::kw_mayThrow: |
| 10140 | Lex.Lex(); |
| 10141 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10142 | return true; |
| 10143 | FFlags.MayThrow = Val; |
| 10144 | break; |
| 10145 | case lltok::kw_hasUnknownCall: |
| 10146 | Lex.Lex(); |
| 10147 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10148 | return true; |
| 10149 | FFlags.HasUnknownCall = Val; |
| 10150 | break; |
| 10151 | case lltok::kw_mustBeUnreachable: |
| 10152 | Lex.Lex(); |
| 10153 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val)) |
| 10154 | return true; |
| 10155 | FFlags.MustBeUnreachable = Val; |
| 10156 | break; |
| 10157 | default: |
| 10158 | return error(L: Lex.getLoc(), Msg: "expected function flag type" ); |
| 10159 | } |
| 10160 | } while (EatIfPresent(T: lltok::comma)); |
| 10161 | |
| 10162 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in funcFlags" )) |
| 10163 | return true; |
| 10164 | |
| 10165 | return false; |
| 10166 | } |
| 10167 | |
| 10168 | /// OptionalCalls |
| 10169 | /// := 'calls' ':' '(' Call [',' Call]* ')' |
| 10170 | /// Call ::= '(' 'callee' ':' GVReference |
| 10171 | /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? |
| 10172 | /// [ ',' 'tail' ]? ')' |
| 10173 | bool LLParser::parseOptionalCalls( |
| 10174 | SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) { |
| 10175 | assert(Lex.getKind() == lltok::kw_calls); |
| 10176 | Lex.Lex(); |
| 10177 | |
| 10178 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in calls" ) || |
| 10179 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in calls" )) |
| 10180 | return true; |
| 10181 | |
| 10182 | IdToIndexMapType IdToIndexMap; |
| 10183 | // parse each call edge |
| 10184 | do { |
| 10185 | ValueInfo VI; |
| 10186 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in call" ) || |
| 10187 | parseToken(T: lltok::kw_callee, ErrMsg: "expected 'callee' in call" ) || |
| 10188 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10189 | return true; |
| 10190 | |
| 10191 | LocTy Loc = Lex.getLoc(); |
| 10192 | unsigned GVId; |
| 10193 | if (parseGVReference(VI, GVId)) |
| 10194 | return true; |
| 10195 | |
| 10196 | CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; |
| 10197 | unsigned RelBF = 0; |
| 10198 | unsigned HasTailCall = false; |
| 10199 | |
| 10200 | // parse optional fields |
| 10201 | while (EatIfPresent(T: lltok::comma)) { |
| 10202 | switch (Lex.getKind()) { |
| 10203 | case lltok::kw_hotness: |
| 10204 | Lex.Lex(); |
| 10205 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseHotness(Hotness)) |
| 10206 | return true; |
| 10207 | break; |
| 10208 | // Deprecated, keep in order to support old files. |
| 10209 | case lltok::kw_relbf: |
| 10210 | Lex.Lex(); |
| 10211 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseUInt32(Val&: RelBF)) |
| 10212 | return true; |
| 10213 | break; |
| 10214 | case lltok::kw_tail: |
| 10215 | Lex.Lex(); |
| 10216 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val&: HasTailCall)) |
| 10217 | return true; |
| 10218 | break; |
| 10219 | default: |
| 10220 | return error(L: Lex.getLoc(), Msg: "expected hotness, relbf, or tail" ); |
| 10221 | } |
| 10222 | } |
| 10223 | // Keep track of the Call array index needing a forward reference. |
| 10224 | // We will save the location of the ValueInfo needing an update, but |
| 10225 | // can only do so once the std::vector is finalized. |
| 10226 | if (VI.getRef() == FwdVIRef) |
| 10227 | IdToIndexMap[GVId].push_back(x: std::make_pair(x: Calls.size(), y&: Loc)); |
| 10228 | Calls.push_back( |
| 10229 | Elt: FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)}); |
| 10230 | |
| 10231 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in call" )) |
| 10232 | return true; |
| 10233 | } while (EatIfPresent(T: lltok::comma)); |
| 10234 | |
| 10235 | // Now that the Calls vector is finalized, it is safe to save the locations |
| 10236 | // of any forward GV references that need updating later. |
| 10237 | for (auto I : IdToIndexMap) { |
| 10238 | auto &Infos = ForwardRefValueInfos[I.first]; |
| 10239 | for (auto P : I.second) { |
| 10240 | assert(Calls[P.first].first.getRef() == FwdVIRef && |
| 10241 | "Forward referenced ValueInfo expected to be empty" ); |
| 10242 | Infos.emplace_back(args: &Calls[P.first].first, args&: P.second); |
| 10243 | } |
| 10244 | } |
| 10245 | |
| 10246 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in calls" )) |
| 10247 | return true; |
| 10248 | |
| 10249 | return false; |
| 10250 | } |
| 10251 | |
| 10252 | /// Hotness |
| 10253 | /// := ('unknown'|'cold'|'none'|'hot'|'critical') |
| 10254 | bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { |
| 10255 | switch (Lex.getKind()) { |
| 10256 | case lltok::kw_unknown: |
| 10257 | Hotness = CalleeInfo::HotnessType::Unknown; |
| 10258 | break; |
| 10259 | case lltok::kw_cold: |
| 10260 | Hotness = CalleeInfo::HotnessType::Cold; |
| 10261 | break; |
| 10262 | case lltok::kw_none: |
| 10263 | Hotness = CalleeInfo::HotnessType::None; |
| 10264 | break; |
| 10265 | case lltok::kw_hot: |
| 10266 | Hotness = CalleeInfo::HotnessType::Hot; |
| 10267 | break; |
| 10268 | case lltok::kw_critical: |
| 10269 | Hotness = CalleeInfo::HotnessType::Critical; |
| 10270 | break; |
| 10271 | default: |
| 10272 | return error(L: Lex.getLoc(), Msg: "invalid call edge hotness" ); |
| 10273 | } |
| 10274 | Lex.Lex(); |
| 10275 | return false; |
| 10276 | } |
| 10277 | |
| 10278 | /// OptionalVTableFuncs |
| 10279 | /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' |
| 10280 | /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' |
| 10281 | bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { |
| 10282 | assert(Lex.getKind() == lltok::kw_vTableFuncs); |
| 10283 | Lex.Lex(); |
| 10284 | |
| 10285 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in vTableFuncs" ) || |
| 10286 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in vTableFuncs" )) |
| 10287 | return true; |
| 10288 | |
| 10289 | IdToIndexMapType IdToIndexMap; |
| 10290 | // parse each virtual function pair |
| 10291 | do { |
| 10292 | ValueInfo VI; |
| 10293 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in vTableFunc" ) || |
| 10294 | parseToken(T: lltok::kw_virtFunc, ErrMsg: "expected 'callee' in vTableFunc" ) || |
| 10295 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10296 | return true; |
| 10297 | |
| 10298 | LocTy Loc = Lex.getLoc(); |
| 10299 | unsigned GVId; |
| 10300 | if (parseGVReference(VI, GVId)) |
| 10301 | return true; |
| 10302 | |
| 10303 | uint64_t Offset; |
| 10304 | if (parseToken(T: lltok::comma, ErrMsg: "expected comma" ) || |
| 10305 | parseToken(T: lltok::kw_offset, ErrMsg: "expected offset" ) || |
| 10306 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseUInt64(Val&: Offset)) |
| 10307 | return true; |
| 10308 | |
| 10309 | // Keep track of the VTableFuncs array index needing a forward reference. |
| 10310 | // We will save the location of the ValueInfo needing an update, but |
| 10311 | // can only do so once the std::vector is finalized. |
| 10312 | if (VI == EmptyVI) |
| 10313 | IdToIndexMap[GVId].push_back(x: std::make_pair(x: VTableFuncs.size(), y&: Loc)); |
| 10314 | VTableFuncs.push_back(x: {VI, Offset}); |
| 10315 | |
| 10316 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in vTableFunc" )) |
| 10317 | return true; |
| 10318 | } while (EatIfPresent(T: lltok::comma)); |
| 10319 | |
| 10320 | // Now that the VTableFuncs vector is finalized, it is safe to save the |
| 10321 | // locations of any forward GV references that need updating later. |
| 10322 | for (auto I : IdToIndexMap) { |
| 10323 | auto &Infos = ForwardRefValueInfos[I.first]; |
| 10324 | for (auto P : I.second) { |
| 10325 | assert(VTableFuncs[P.first].FuncVI == EmptyVI && |
| 10326 | "Forward referenced ValueInfo expected to be empty" ); |
| 10327 | Infos.emplace_back(args: &VTableFuncs[P.first].FuncVI, args&: P.second); |
| 10328 | } |
| 10329 | } |
| 10330 | |
| 10331 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in vTableFuncs" )) |
| 10332 | return true; |
| 10333 | |
| 10334 | return false; |
| 10335 | } |
| 10336 | |
| 10337 | /// ParamNo := 'param' ':' UInt64 |
| 10338 | bool LLParser::parseParamNo(uint64_t &ParamNo) { |
| 10339 | if (parseToken(T: lltok::kw_param, ErrMsg: "expected 'param' here" ) || |
| 10340 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || parseUInt64(Val&: ParamNo)) |
| 10341 | return true; |
| 10342 | return false; |
| 10343 | } |
| 10344 | |
| 10345 | /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' |
| 10346 | bool LLParser::parseParamAccessOffset(ConstantRange &Range) { |
| 10347 | APSInt Lower; |
| 10348 | APSInt Upper; |
| 10349 | auto ParseAPSInt = [&](APSInt &Val) { |
| 10350 | if (Lex.getKind() != lltok::APSInt) |
| 10351 | return tokError(Msg: "expected integer" ); |
| 10352 | Val = Lex.getAPSIntVal(); |
| 10353 | Val = Val.extOrTrunc(width: FunctionSummary::ParamAccess::RangeWidth); |
| 10354 | Val.setIsSigned(true); |
| 10355 | Lex.Lex(); |
| 10356 | return false; |
| 10357 | }; |
| 10358 | if (parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here" ) || |
| 10359 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10360 | parseToken(T: lltok::lsquare, ErrMsg: "expected '[' here" ) || ParseAPSInt(Lower) || |
| 10361 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || ParseAPSInt(Upper) || |
| 10362 | parseToken(T: lltok::rsquare, ErrMsg: "expected ']' here" )) |
| 10363 | return true; |
| 10364 | |
| 10365 | ++Upper; |
| 10366 | Range = |
| 10367 | (Lower == Upper && !Lower.isMaxValue()) |
| 10368 | ? ConstantRange::getEmpty(BitWidth: FunctionSummary::ParamAccess::RangeWidth) |
| 10369 | : ConstantRange(Lower, Upper); |
| 10370 | |
| 10371 | return false; |
| 10372 | } |
| 10373 | |
| 10374 | /// ParamAccessCall |
| 10375 | /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' |
| 10376 | bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, |
| 10377 | IdLocListType &IdLocList) { |
| 10378 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 10379 | parseToken(T: lltok::kw_callee, ErrMsg: "expected 'callee' here" ) || |
| 10380 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" )) |
| 10381 | return true; |
| 10382 | |
| 10383 | unsigned GVId; |
| 10384 | ValueInfo VI; |
| 10385 | LocTy Loc = Lex.getLoc(); |
| 10386 | if (parseGVReference(VI, GVId)) |
| 10387 | return true; |
| 10388 | |
| 10389 | Call.Callee = VI; |
| 10390 | IdLocList.emplace_back(args&: GVId, args&: Loc); |
| 10391 | |
| 10392 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 10393 | parseParamNo(ParamNo&: Call.ParamNo) || |
| 10394 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 10395 | parseParamAccessOffset(Range&: Call.Offsets)) |
| 10396 | return true; |
| 10397 | |
| 10398 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10399 | return true; |
| 10400 | |
| 10401 | return false; |
| 10402 | } |
| 10403 | |
| 10404 | /// ParamAccess |
| 10405 | /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' |
| 10406 | /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' |
| 10407 | bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, |
| 10408 | IdLocListType &IdLocList) { |
| 10409 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 10410 | parseParamNo(ParamNo&: Param.ParamNo) || |
| 10411 | parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 10412 | parseParamAccessOffset(Range&: Param.Use)) |
| 10413 | return true; |
| 10414 | |
| 10415 | if (EatIfPresent(T: lltok::comma)) { |
| 10416 | if (parseToken(T: lltok::kw_calls, ErrMsg: "expected 'calls' here" ) || |
| 10417 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10418 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10419 | return true; |
| 10420 | do { |
| 10421 | FunctionSummary::ParamAccess::Call Call; |
| 10422 | if (parseParamAccessCall(Call, IdLocList)) |
| 10423 | return true; |
| 10424 | Param.Calls.push_back(x: Call); |
| 10425 | } while (EatIfPresent(T: lltok::comma)); |
| 10426 | |
| 10427 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10428 | return true; |
| 10429 | } |
| 10430 | |
| 10431 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10432 | return true; |
| 10433 | |
| 10434 | return false; |
| 10435 | } |
| 10436 | |
| 10437 | /// OptionalParamAccesses |
| 10438 | /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' |
| 10439 | bool LLParser::parseOptionalParamAccesses( |
| 10440 | std::vector<FunctionSummary::ParamAccess> &Params) { |
| 10441 | assert(Lex.getKind() == lltok::kw_params); |
| 10442 | Lex.Lex(); |
| 10443 | |
| 10444 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10445 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10446 | return true; |
| 10447 | |
| 10448 | IdLocListType VContexts; |
| 10449 | size_t CallsNum = 0; |
| 10450 | do { |
| 10451 | FunctionSummary::ParamAccess ParamAccess; |
| 10452 | if (parseParamAccess(Param&: ParamAccess, IdLocList&: VContexts)) |
| 10453 | return true; |
| 10454 | CallsNum += ParamAccess.Calls.size(); |
| 10455 | assert(VContexts.size() == CallsNum); |
| 10456 | (void)CallsNum; |
| 10457 | Params.emplace_back(args: std::move(ParamAccess)); |
| 10458 | } while (EatIfPresent(T: lltok::comma)); |
| 10459 | |
| 10460 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10461 | return true; |
| 10462 | |
| 10463 | // Now that the Params is finalized, it is safe to save the locations |
| 10464 | // of any forward GV references that need updating later. |
| 10465 | IdLocListType::const_iterator ItContext = VContexts.begin(); |
| 10466 | for (auto &PA : Params) { |
| 10467 | for (auto &C : PA.Calls) { |
| 10468 | if (C.Callee.getRef() == FwdVIRef) |
| 10469 | ForwardRefValueInfos[ItContext->first].emplace_back(args: &C.Callee, |
| 10470 | args: ItContext->second); |
| 10471 | ++ItContext; |
| 10472 | } |
| 10473 | } |
| 10474 | assert(ItContext == VContexts.end()); |
| 10475 | |
| 10476 | return false; |
| 10477 | } |
| 10478 | |
| 10479 | /// OptionalRefs |
| 10480 | /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' |
| 10481 | bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) { |
| 10482 | assert(Lex.getKind() == lltok::kw_refs); |
| 10483 | Lex.Lex(); |
| 10484 | |
| 10485 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in refs" ) || |
| 10486 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in refs" )) |
| 10487 | return true; |
| 10488 | |
| 10489 | struct ValueContext { |
| 10490 | ValueInfo VI; |
| 10491 | unsigned GVId; |
| 10492 | LocTy Loc; |
| 10493 | }; |
| 10494 | std::vector<ValueContext> VContexts; |
| 10495 | // parse each ref edge |
| 10496 | do { |
| 10497 | ValueContext VC; |
| 10498 | VC.Loc = Lex.getLoc(); |
| 10499 | if (parseGVReference(VI&: VC.VI, GVId&: VC.GVId)) |
| 10500 | return true; |
| 10501 | VContexts.push_back(x: VC); |
| 10502 | } while (EatIfPresent(T: lltok::comma)); |
| 10503 | |
| 10504 | // Sort value contexts so that ones with writeonly |
| 10505 | // and readonly ValueInfo are at the end of VContexts vector. |
| 10506 | // See FunctionSummary::specialRefCounts() |
| 10507 | llvm::sort(C&: VContexts, Comp: [](const ValueContext &VC1, const ValueContext &VC2) { |
| 10508 | return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); |
| 10509 | }); |
| 10510 | |
| 10511 | IdToIndexMapType IdToIndexMap; |
| 10512 | for (auto &VC : VContexts) { |
| 10513 | // Keep track of the Refs array index needing a forward reference. |
| 10514 | // We will save the location of the ValueInfo needing an update, but |
| 10515 | // can only do so once the std::vector is finalized. |
| 10516 | if (VC.VI.getRef() == FwdVIRef) |
| 10517 | IdToIndexMap[VC.GVId].push_back(x: std::make_pair(x: Refs.size(), y&: VC.Loc)); |
| 10518 | Refs.push_back(Elt: VC.VI); |
| 10519 | } |
| 10520 | |
| 10521 | // Now that the Refs vector is finalized, it is safe to save the locations |
| 10522 | // of any forward GV references that need updating later. |
| 10523 | for (auto I : IdToIndexMap) { |
| 10524 | auto &Infos = ForwardRefValueInfos[I.first]; |
| 10525 | for (auto P : I.second) { |
| 10526 | assert(Refs[P.first].getRef() == FwdVIRef && |
| 10527 | "Forward referenced ValueInfo expected to be empty" ); |
| 10528 | Infos.emplace_back(args: &Refs[P.first], args&: P.second); |
| 10529 | } |
| 10530 | } |
| 10531 | |
| 10532 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in refs" )) |
| 10533 | return true; |
| 10534 | |
| 10535 | return false; |
| 10536 | } |
| 10537 | |
| 10538 | /// OptionalTypeIdInfo |
| 10539 | /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? |
| 10540 | /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? |
| 10541 | /// [',' TypeCheckedLoadConstVCalls]? ')' |
| 10542 | bool LLParser::parseOptionalTypeIdInfo( |
| 10543 | FunctionSummary::TypeIdInfo &TypeIdInfo) { |
| 10544 | assert(Lex.getKind() == lltok::kw_typeIdInfo); |
| 10545 | Lex.Lex(); |
| 10546 | |
| 10547 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10548 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in typeIdInfo" )) |
| 10549 | return true; |
| 10550 | |
| 10551 | do { |
| 10552 | switch (Lex.getKind()) { |
| 10553 | case lltok::kw_typeTests: |
| 10554 | if (parseTypeTests(TypeTests&: TypeIdInfo.TypeTests)) |
| 10555 | return true; |
| 10556 | break; |
| 10557 | case lltok::kw_typeTestAssumeVCalls: |
| 10558 | if (parseVFuncIdList(Kind: lltok::kw_typeTestAssumeVCalls, |
| 10559 | VFuncIdList&: TypeIdInfo.TypeTestAssumeVCalls)) |
| 10560 | return true; |
| 10561 | break; |
| 10562 | case lltok::kw_typeCheckedLoadVCalls: |
| 10563 | if (parseVFuncIdList(Kind: lltok::kw_typeCheckedLoadVCalls, |
| 10564 | VFuncIdList&: TypeIdInfo.TypeCheckedLoadVCalls)) |
| 10565 | return true; |
| 10566 | break; |
| 10567 | case lltok::kw_typeTestAssumeConstVCalls: |
| 10568 | if (parseConstVCallList(Kind: lltok::kw_typeTestAssumeConstVCalls, |
| 10569 | ConstVCallList&: TypeIdInfo.TypeTestAssumeConstVCalls)) |
| 10570 | return true; |
| 10571 | break; |
| 10572 | case lltok::kw_typeCheckedLoadConstVCalls: |
| 10573 | if (parseConstVCallList(Kind: lltok::kw_typeCheckedLoadConstVCalls, |
| 10574 | ConstVCallList&: TypeIdInfo.TypeCheckedLoadConstVCalls)) |
| 10575 | return true; |
| 10576 | break; |
| 10577 | default: |
| 10578 | return error(L: Lex.getLoc(), Msg: "invalid typeIdInfo list type" ); |
| 10579 | } |
| 10580 | } while (EatIfPresent(T: lltok::comma)); |
| 10581 | |
| 10582 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in typeIdInfo" )) |
| 10583 | return true; |
| 10584 | |
| 10585 | return false; |
| 10586 | } |
| 10587 | |
| 10588 | /// TypeTests |
| 10589 | /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) |
| 10590 | /// [',' (SummaryID | UInt64)]* ')' |
| 10591 | bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { |
| 10592 | assert(Lex.getKind() == lltok::kw_typeTests); |
| 10593 | Lex.Lex(); |
| 10594 | |
| 10595 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10596 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in typeIdInfo" )) |
| 10597 | return true; |
| 10598 | |
| 10599 | IdToIndexMapType IdToIndexMap; |
| 10600 | do { |
| 10601 | GlobalValue::GUID GUID = 0; |
| 10602 | if (Lex.getKind() == lltok::SummaryID) { |
| 10603 | unsigned ID = Lex.getUIntVal(); |
| 10604 | LocTy Loc = Lex.getLoc(); |
| 10605 | // Keep track of the TypeTests array index needing a forward reference. |
| 10606 | // We will save the location of the GUID needing an update, but |
| 10607 | // can only do so once the std::vector is finalized. |
| 10608 | IdToIndexMap[ID].push_back(x: std::make_pair(x: TypeTests.size(), y&: Loc)); |
| 10609 | Lex.Lex(); |
| 10610 | } else if (parseUInt64(Val&: GUID)) |
| 10611 | return true; |
| 10612 | TypeTests.push_back(x: GUID); |
| 10613 | } while (EatIfPresent(T: lltok::comma)); |
| 10614 | |
| 10615 | // Now that the TypeTests vector is finalized, it is safe to save the |
| 10616 | // locations of any forward GV references that need updating later. |
| 10617 | for (auto I : IdToIndexMap) { |
| 10618 | auto &Ids = ForwardRefTypeIds[I.first]; |
| 10619 | for (auto P : I.second) { |
| 10620 | assert(TypeTests[P.first] == 0 && |
| 10621 | "Forward referenced type id GUID expected to be 0" ); |
| 10622 | Ids.emplace_back(args: &TypeTests[P.first], args&: P.second); |
| 10623 | } |
| 10624 | } |
| 10625 | |
| 10626 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in typeIdInfo" )) |
| 10627 | return true; |
| 10628 | |
| 10629 | return false; |
| 10630 | } |
| 10631 | |
| 10632 | /// VFuncIdList |
| 10633 | /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' |
| 10634 | bool LLParser::parseVFuncIdList( |
| 10635 | lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { |
| 10636 | assert(Lex.getKind() == Kind); |
| 10637 | Lex.Lex(); |
| 10638 | |
| 10639 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10640 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10641 | return true; |
| 10642 | |
| 10643 | IdToIndexMapType IdToIndexMap; |
| 10644 | do { |
| 10645 | FunctionSummary::VFuncId VFuncId; |
| 10646 | if (parseVFuncId(VFuncId, IdToIndexMap, Index: VFuncIdList.size())) |
| 10647 | return true; |
| 10648 | VFuncIdList.push_back(x: VFuncId); |
| 10649 | } while (EatIfPresent(T: lltok::comma)); |
| 10650 | |
| 10651 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10652 | return true; |
| 10653 | |
| 10654 | // Now that the VFuncIdList vector is finalized, it is safe to save the |
| 10655 | // locations of any forward GV references that need updating later. |
| 10656 | for (auto I : IdToIndexMap) { |
| 10657 | auto &Ids = ForwardRefTypeIds[I.first]; |
| 10658 | for (auto P : I.second) { |
| 10659 | assert(VFuncIdList[P.first].GUID == 0 && |
| 10660 | "Forward referenced type id GUID expected to be 0" ); |
| 10661 | Ids.emplace_back(args: &VFuncIdList[P.first].GUID, args&: P.second); |
| 10662 | } |
| 10663 | } |
| 10664 | |
| 10665 | return false; |
| 10666 | } |
| 10667 | |
| 10668 | /// ConstVCallList |
| 10669 | /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' |
| 10670 | bool LLParser::parseConstVCallList( |
| 10671 | lltok::Kind Kind, |
| 10672 | std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { |
| 10673 | assert(Lex.getKind() == Kind); |
| 10674 | Lex.Lex(); |
| 10675 | |
| 10676 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10677 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10678 | return true; |
| 10679 | |
| 10680 | IdToIndexMapType IdToIndexMap; |
| 10681 | do { |
| 10682 | FunctionSummary::ConstVCall ConstVCall; |
| 10683 | if (parseConstVCall(ConstVCall, IdToIndexMap, Index: ConstVCallList.size())) |
| 10684 | return true; |
| 10685 | ConstVCallList.push_back(x: ConstVCall); |
| 10686 | } while (EatIfPresent(T: lltok::comma)); |
| 10687 | |
| 10688 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10689 | return true; |
| 10690 | |
| 10691 | // Now that the ConstVCallList vector is finalized, it is safe to save the |
| 10692 | // locations of any forward GV references that need updating later. |
| 10693 | for (auto I : IdToIndexMap) { |
| 10694 | auto &Ids = ForwardRefTypeIds[I.first]; |
| 10695 | for (auto P : I.second) { |
| 10696 | assert(ConstVCallList[P.first].VFunc.GUID == 0 && |
| 10697 | "Forward referenced type id GUID expected to be 0" ); |
| 10698 | Ids.emplace_back(args: &ConstVCallList[P.first].VFunc.GUID, args&: P.second); |
| 10699 | } |
| 10700 | } |
| 10701 | |
| 10702 | return false; |
| 10703 | } |
| 10704 | |
| 10705 | /// ConstVCall |
| 10706 | /// ::= '(' VFuncId ',' Args ')' |
| 10707 | bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, |
| 10708 | IdToIndexMapType &IdToIndexMap, unsigned Index) { |
| 10709 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" ) || |
| 10710 | parseVFuncId(VFuncId&: ConstVCall.VFunc, IdToIndexMap, Index)) |
| 10711 | return true; |
| 10712 | |
| 10713 | if (EatIfPresent(T: lltok::comma)) |
| 10714 | if (parseArgs(Args&: ConstVCall.Args)) |
| 10715 | return true; |
| 10716 | |
| 10717 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10718 | return true; |
| 10719 | |
| 10720 | return false; |
| 10721 | } |
| 10722 | |
| 10723 | /// VFuncId |
| 10724 | /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' |
| 10725 | /// 'offset' ':' UInt64 ')' |
| 10726 | bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, |
| 10727 | IdToIndexMapType &IdToIndexMap, unsigned Index) { |
| 10728 | assert(Lex.getKind() == lltok::kw_vFuncId); |
| 10729 | Lex.Lex(); |
| 10730 | |
| 10731 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10732 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10733 | return true; |
| 10734 | |
| 10735 | if (Lex.getKind() == lltok::SummaryID) { |
| 10736 | VFuncId.GUID = 0; |
| 10737 | unsigned ID = Lex.getUIntVal(); |
| 10738 | LocTy Loc = Lex.getLoc(); |
| 10739 | // Keep track of the array index needing a forward reference. |
| 10740 | // We will save the location of the GUID needing an update, but |
| 10741 | // can only do so once the caller's std::vector is finalized. |
| 10742 | IdToIndexMap[ID].push_back(x: std::make_pair(x&: Index, y&: Loc)); |
| 10743 | Lex.Lex(); |
| 10744 | } else if (parseToken(T: lltok::kw_guid, ErrMsg: "expected 'guid' here" ) || |
| 10745 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10746 | parseUInt64(Val&: VFuncId.GUID)) |
| 10747 | return true; |
| 10748 | |
| 10749 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here" ) || |
| 10750 | parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here" ) || |
| 10751 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10752 | parseUInt64(Val&: VFuncId.Offset) || |
| 10753 | parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10754 | return true; |
| 10755 | |
| 10756 | return false; |
| 10757 | } |
| 10758 | |
| 10759 | /// GVFlags |
| 10760 | /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' |
| 10761 | /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ',' |
| 10762 | /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ',' |
| 10763 | /// 'canAutoHide' ':' Flag ',' ')' |
| 10764 | bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { |
| 10765 | assert(Lex.getKind() == lltok::kw_flags); |
| 10766 | Lex.Lex(); |
| 10767 | |
| 10768 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10769 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10770 | return true; |
| 10771 | |
| 10772 | do { |
| 10773 | unsigned Flag = 0; |
| 10774 | switch (Lex.getKind()) { |
| 10775 | case lltok::kw_linkage: |
| 10776 | Lex.Lex(); |
| 10777 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10778 | return true; |
| 10779 | bool HasLinkage; |
| 10780 | GVFlags.Linkage = parseOptionalLinkageAux(Kind: Lex.getKind(), HasLinkage); |
| 10781 | assert(HasLinkage && "Linkage not optional in summary entry" ); |
| 10782 | Lex.Lex(); |
| 10783 | break; |
| 10784 | case lltok::kw_visibility: |
| 10785 | Lex.Lex(); |
| 10786 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10787 | return true; |
| 10788 | parseOptionalVisibility(Res&: Flag); |
| 10789 | GVFlags.Visibility = Flag; |
| 10790 | break; |
| 10791 | case lltok::kw_notEligibleToImport: |
| 10792 | Lex.Lex(); |
| 10793 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val&: Flag)) |
| 10794 | return true; |
| 10795 | GVFlags.NotEligibleToImport = Flag; |
| 10796 | break; |
| 10797 | case lltok::kw_live: |
| 10798 | Lex.Lex(); |
| 10799 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val&: Flag)) |
| 10800 | return true; |
| 10801 | GVFlags.Live = Flag; |
| 10802 | break; |
| 10803 | case lltok::kw_dsoLocal: |
| 10804 | Lex.Lex(); |
| 10805 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val&: Flag)) |
| 10806 | return true; |
| 10807 | GVFlags.DSOLocal = Flag; |
| 10808 | break; |
| 10809 | case lltok::kw_canAutoHide: |
| 10810 | Lex.Lex(); |
| 10811 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || parseFlag(Val&: Flag)) |
| 10812 | return true; |
| 10813 | GVFlags.CanAutoHide = Flag; |
| 10814 | break; |
| 10815 | case lltok::kw_importType: |
| 10816 | Lex.Lex(); |
| 10817 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10818 | return true; |
| 10819 | GlobalValueSummary::ImportKind IK; |
| 10820 | if (parseOptionalImportType(Kind: Lex.getKind(), Res&: IK)) |
| 10821 | return true; |
| 10822 | GVFlags.ImportType = static_cast<unsigned>(IK); |
| 10823 | Lex.Lex(); |
| 10824 | break; |
| 10825 | default: |
| 10826 | return error(L: Lex.getLoc(), Msg: "expected gv flag type" ); |
| 10827 | } |
| 10828 | } while (EatIfPresent(T: lltok::comma)); |
| 10829 | |
| 10830 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" )) |
| 10831 | return true; |
| 10832 | |
| 10833 | return false; |
| 10834 | } |
| 10835 | |
| 10836 | /// GVarFlags |
| 10837 | /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag |
| 10838 | /// ',' 'writeonly' ':' Flag |
| 10839 | /// ',' 'constant' ':' Flag ')' |
| 10840 | bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { |
| 10841 | assert(Lex.getKind() == lltok::kw_varFlags); |
| 10842 | Lex.Lex(); |
| 10843 | |
| 10844 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10845 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' here" )) |
| 10846 | return true; |
| 10847 | |
| 10848 | auto ParseRest = [this](unsigned int &Val) { |
| 10849 | Lex.Lex(); |
| 10850 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10851 | return true; |
| 10852 | return parseFlag(Val); |
| 10853 | }; |
| 10854 | |
| 10855 | do { |
| 10856 | unsigned Flag = 0; |
| 10857 | switch (Lex.getKind()) { |
| 10858 | case lltok::kw_readonly: |
| 10859 | if (ParseRest(Flag)) |
| 10860 | return true; |
| 10861 | GVarFlags.MaybeReadOnly = Flag; |
| 10862 | break; |
| 10863 | case lltok::kw_writeonly: |
| 10864 | if (ParseRest(Flag)) |
| 10865 | return true; |
| 10866 | GVarFlags.MaybeWriteOnly = Flag; |
| 10867 | break; |
| 10868 | case lltok::kw_constant: |
| 10869 | if (ParseRest(Flag)) |
| 10870 | return true; |
| 10871 | GVarFlags.Constant = Flag; |
| 10872 | break; |
| 10873 | case lltok::kw_vcall_visibility: |
| 10874 | if (ParseRest(Flag)) |
| 10875 | return true; |
| 10876 | GVarFlags.VCallVisibility = Flag; |
| 10877 | break; |
| 10878 | default: |
| 10879 | return error(L: Lex.getLoc(), Msg: "expected gvar flag type" ); |
| 10880 | } |
| 10881 | } while (EatIfPresent(T: lltok::comma)); |
| 10882 | return parseToken(T: lltok::rparen, ErrMsg: "expected ')' here" ); |
| 10883 | } |
| 10884 | |
| 10885 | /// ModuleReference |
| 10886 | /// ::= 'module' ':' UInt |
| 10887 | bool LLParser::parseModuleReference(StringRef &ModulePath) { |
| 10888 | // parse module id. |
| 10889 | if (parseToken(T: lltok::kw_module, ErrMsg: "expected 'module' here" ) || |
| 10890 | parseToken(T: lltok::colon, ErrMsg: "expected ':' here" ) || |
| 10891 | parseToken(T: lltok::SummaryID, ErrMsg: "expected module ID" )) |
| 10892 | return true; |
| 10893 | |
| 10894 | unsigned ModuleID = Lex.getUIntVal(); |
| 10895 | auto I = ModuleIdMap.find(x: ModuleID); |
| 10896 | // We should have already parsed all module IDs |
| 10897 | assert(I != ModuleIdMap.end()); |
| 10898 | ModulePath = I->second; |
| 10899 | return false; |
| 10900 | } |
| 10901 | |
| 10902 | /// GVReference |
| 10903 | /// ::= SummaryID |
| 10904 | bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { |
| 10905 | bool WriteOnly = false, ReadOnly = EatIfPresent(T: lltok::kw_readonly); |
| 10906 | if (!ReadOnly) |
| 10907 | WriteOnly = EatIfPresent(T: lltok::kw_writeonly); |
| 10908 | if (parseToken(T: lltok::SummaryID, ErrMsg: "expected GV ID" )) |
| 10909 | return true; |
| 10910 | |
| 10911 | GVId = Lex.getUIntVal(); |
| 10912 | // Check if we already have a VI for this GV |
| 10913 | if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) { |
| 10914 | assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); |
| 10915 | VI = NumberedValueInfos[GVId]; |
| 10916 | } else |
| 10917 | // We will create a forward reference to the stored location. |
| 10918 | VI = ValueInfo(false, FwdVIRef); |
| 10919 | |
| 10920 | if (ReadOnly) |
| 10921 | VI.setReadOnly(); |
| 10922 | if (WriteOnly) |
| 10923 | VI.setWriteOnly(); |
| 10924 | return false; |
| 10925 | } |
| 10926 | |
| 10927 | /// OptionalAllocs |
| 10928 | /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')' |
| 10929 | /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')' |
| 10930 | /// ',' MemProfs ')' |
| 10931 | /// Version ::= UInt32 |
| 10932 | bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) { |
| 10933 | assert(Lex.getKind() == lltok::kw_allocs); |
| 10934 | Lex.Lex(); |
| 10935 | |
| 10936 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in allocs" ) || |
| 10937 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in allocs" )) |
| 10938 | return true; |
| 10939 | |
| 10940 | // parse each alloc |
| 10941 | do { |
| 10942 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in alloc" ) || |
| 10943 | parseToken(T: lltok::kw_versions, ErrMsg: "expected 'versions' in alloc" ) || |
| 10944 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || |
| 10945 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in versions" )) |
| 10946 | return true; |
| 10947 | |
| 10948 | SmallVector<uint8_t> Versions; |
| 10949 | do { |
| 10950 | uint8_t V = 0; |
| 10951 | if (parseAllocType(AllocType&: V)) |
| 10952 | return true; |
| 10953 | Versions.push_back(Elt: V); |
| 10954 | } while (EatIfPresent(T: lltok::comma)); |
| 10955 | |
| 10956 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in versions" ) || |
| 10957 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in alloc" )) |
| 10958 | return true; |
| 10959 | |
| 10960 | std::vector<MIBInfo> MIBs; |
| 10961 | if (parseMemProfs(MIBs)) |
| 10962 | return true; |
| 10963 | |
| 10964 | Allocs.push_back(x: {Versions, MIBs}); |
| 10965 | |
| 10966 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in alloc" )) |
| 10967 | return true; |
| 10968 | } while (EatIfPresent(T: lltok::comma)); |
| 10969 | |
| 10970 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in allocs" )) |
| 10971 | return true; |
| 10972 | |
| 10973 | return false; |
| 10974 | } |
| 10975 | |
| 10976 | /// MemProfs |
| 10977 | /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')' |
| 10978 | /// MemProf ::= '(' 'type' ':' AllocType |
| 10979 | /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')' |
| 10980 | /// StackId ::= UInt64 |
| 10981 | bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) { |
| 10982 | assert(Lex.getKind() == lltok::kw_memProf); |
| 10983 | Lex.Lex(); |
| 10984 | |
| 10985 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in memprof" ) || |
| 10986 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in memprof" )) |
| 10987 | return true; |
| 10988 | |
| 10989 | // parse each MIB |
| 10990 | do { |
| 10991 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in memprof" ) || |
| 10992 | parseToken(T: lltok::kw_type, ErrMsg: "expected 'type' in memprof" ) || |
| 10993 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 10994 | return true; |
| 10995 | |
| 10996 | uint8_t AllocType; |
| 10997 | if (parseAllocType(AllocType)) |
| 10998 | return true; |
| 10999 | |
| 11000 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' in memprof" ) || |
| 11001 | parseToken(T: lltok::kw_stackIds, ErrMsg: "expected 'stackIds' in memprof" ) || |
| 11002 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || |
| 11003 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in stackIds" )) |
| 11004 | return true; |
| 11005 | |
| 11006 | SmallVector<unsigned> StackIdIndices; |
| 11007 | // Combined index alloc records may not have a stack id list. |
| 11008 | if (Lex.getKind() != lltok::rparen) { |
| 11009 | do { |
| 11010 | uint64_t StackId = 0; |
| 11011 | if (parseUInt64(Val&: StackId)) |
| 11012 | return true; |
| 11013 | StackIdIndices.push_back(Elt: Index->addOrGetStackIdIndex(StackId)); |
| 11014 | } while (EatIfPresent(T: lltok::comma)); |
| 11015 | } |
| 11016 | |
| 11017 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in stackIds" )) |
| 11018 | return true; |
| 11019 | |
| 11020 | MIBs.push_back(x: {(AllocationType)AllocType, StackIdIndices}); |
| 11021 | |
| 11022 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in memprof" )) |
| 11023 | return true; |
| 11024 | } while (EatIfPresent(T: lltok::comma)); |
| 11025 | |
| 11026 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in memprof" )) |
| 11027 | return true; |
| 11028 | |
| 11029 | return false; |
| 11030 | } |
| 11031 | |
| 11032 | /// AllocType |
| 11033 | /// := ('none'|'notcold'|'cold'|'hot') |
| 11034 | bool LLParser::parseAllocType(uint8_t &AllocType) { |
| 11035 | switch (Lex.getKind()) { |
| 11036 | case lltok::kw_none: |
| 11037 | AllocType = (uint8_t)AllocationType::None; |
| 11038 | break; |
| 11039 | case lltok::kw_notcold: |
| 11040 | AllocType = (uint8_t)AllocationType::NotCold; |
| 11041 | break; |
| 11042 | case lltok::kw_cold: |
| 11043 | AllocType = (uint8_t)AllocationType::Cold; |
| 11044 | break; |
| 11045 | case lltok::kw_hot: |
| 11046 | AllocType = (uint8_t)AllocationType::Hot; |
| 11047 | break; |
| 11048 | default: |
| 11049 | return error(L: Lex.getLoc(), Msg: "invalid alloc type" ); |
| 11050 | } |
| 11051 | Lex.Lex(); |
| 11052 | return false; |
| 11053 | } |
| 11054 | |
| 11055 | /// OptionalCallsites |
| 11056 | /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')' |
| 11057 | /// Callsite ::= '(' 'callee' ':' GVReference |
| 11058 | /// ',' 'clones' ':' '(' Version [',' Version]* ')' |
| 11059 | /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')' |
| 11060 | /// Version ::= UInt32 |
| 11061 | /// StackId ::= UInt64 |
| 11062 | bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) { |
| 11063 | assert(Lex.getKind() == lltok::kw_callsites); |
| 11064 | Lex.Lex(); |
| 11065 | |
| 11066 | if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in callsites" ) || |
| 11067 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in callsites" )) |
| 11068 | return true; |
| 11069 | |
| 11070 | IdToIndexMapType IdToIndexMap; |
| 11071 | // parse each callsite |
| 11072 | do { |
| 11073 | if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in callsite" ) || |
| 11074 | parseToken(T: lltok::kw_callee, ErrMsg: "expected 'callee' in callsite" ) || |
| 11075 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" )) |
| 11076 | return true; |
| 11077 | |
| 11078 | ValueInfo VI; |
| 11079 | unsigned GVId = 0; |
| 11080 | LocTy Loc = Lex.getLoc(); |
| 11081 | if (!EatIfPresent(T: lltok::kw_null)) { |
| 11082 | if (parseGVReference(VI, GVId)) |
| 11083 | return true; |
| 11084 | } |
| 11085 | |
| 11086 | if (parseToken(T: lltok::comma, ErrMsg: "expected ',' in callsite" ) || |
| 11087 | parseToken(T: lltok::kw_clones, ErrMsg: "expected 'clones' in callsite" ) || |
| 11088 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || |
| 11089 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in clones" )) |
| 11090 | return true; |
| 11091 | |
| 11092 | SmallVector<unsigned> Clones; |
| 11093 | do { |
| 11094 | unsigned V = 0; |
| 11095 | if (parseUInt32(Val&: V)) |
| 11096 | return true; |
| 11097 | Clones.push_back(Elt: V); |
| 11098 | } while (EatIfPresent(T: lltok::comma)); |
| 11099 | |
| 11100 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in clones" ) || |
| 11101 | parseToken(T: lltok::comma, ErrMsg: "expected ',' in callsite" ) || |
| 11102 | parseToken(T: lltok::kw_stackIds, ErrMsg: "expected 'stackIds' in callsite" ) || |
| 11103 | parseToken(T: lltok::colon, ErrMsg: "expected ':'" ) || |
| 11104 | parseToken(T: lltok::lparen, ErrMsg: "expected '(' in stackIds" )) |
| 11105 | return true; |
| 11106 | |
| 11107 | SmallVector<unsigned> StackIdIndices; |
| 11108 | // Synthesized callsite records will not have a stack id list. |
| 11109 | if (Lex.getKind() != lltok::rparen) { |
| 11110 | do { |
| 11111 | uint64_t StackId = 0; |
| 11112 | if (parseUInt64(Val&: StackId)) |
| 11113 | return true; |
| 11114 | StackIdIndices.push_back(Elt: Index->addOrGetStackIdIndex(StackId)); |
| 11115 | } while (EatIfPresent(T: lltok::comma)); |
| 11116 | } |
| 11117 | |
| 11118 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in stackIds" )) |
| 11119 | return true; |
| 11120 | |
| 11121 | // Keep track of the Callsites array index needing a forward reference. |
| 11122 | // We will save the location of the ValueInfo needing an update, but |
| 11123 | // can only do so once the SmallVector is finalized. |
| 11124 | if (VI.getRef() == FwdVIRef) |
| 11125 | IdToIndexMap[GVId].push_back(x: std::make_pair(x: Callsites.size(), y&: Loc)); |
| 11126 | Callsites.push_back(x: {VI, Clones, StackIdIndices}); |
| 11127 | |
| 11128 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in callsite" )) |
| 11129 | return true; |
| 11130 | } while (EatIfPresent(T: lltok::comma)); |
| 11131 | |
| 11132 | // Now that the Callsites vector is finalized, it is safe to save the |
| 11133 | // locations of any forward GV references that need updating later. |
| 11134 | for (auto I : IdToIndexMap) { |
| 11135 | auto &Infos = ForwardRefValueInfos[I.first]; |
| 11136 | for (auto P : I.second) { |
| 11137 | assert(Callsites[P.first].Callee.getRef() == FwdVIRef && |
| 11138 | "Forward referenced ValueInfo expected to be empty" ); |
| 11139 | Infos.emplace_back(args: &Callsites[P.first].Callee, args&: P.second); |
| 11140 | } |
| 11141 | } |
| 11142 | |
| 11143 | if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in callsites" )) |
| 11144 | return true; |
| 11145 | |
| 11146 | return false; |
| 11147 | } |
| 11148 | |