Path: blob/main/contrib/llvm-project/llvm/lib/Frontend/HLSL/CBuffer.cpp
213799 views
//===- CBuffer.cpp - HLSL constant buffer handling ------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/Frontend/HLSL/CBuffer.h"9#include "llvm/Frontend/HLSL/HLSLResource.h"10#include "llvm/IR/DerivedTypes.h"11#include "llvm/IR/Metadata.h"12#include "llvm/IR/Module.h"1314using namespace llvm;15using namespace llvm::hlsl;1617static size_t getMemberOffset(GlobalVariable *Handle, size_t Index) {18auto *HandleTy = cast<TargetExtType>(Handle->getValueType());19assert(HandleTy->getName().ends_with(".CBuffer") && "Not a cbuffer type");20assert(HandleTy->getNumTypeParameters() == 1 && "Expected layout type");2122auto *LayoutTy = cast<TargetExtType>(HandleTy->getTypeParameter(0));23assert(LayoutTy->getName().ends_with(".Layout") && "Not a layout type");2425// Skip the "size" parameter.26size_t ParamIndex = Index + 1;27assert(LayoutTy->getNumIntParameters() > ParamIndex &&28"Not enough parameters");2930return LayoutTy->getIntParameter(ParamIndex);31}3233std::optional<CBufferMetadata> CBufferMetadata::get(Module &M) {34NamedMDNode *CBufMD = M.getNamedMetadata("hlsl.cbs");35if (!CBufMD)36return std::nullopt;3738std::optional<CBufferMetadata> Result({CBufMD});3940for (const MDNode *MD : CBufMD->operands()) {41assert(MD->getNumOperands() && "Invalid cbuffer metadata");4243auto *Handle = cast<GlobalVariable>(44cast<ValueAsMetadata>(MD->getOperand(0))->getValue());45CBufferMapping &Mapping = Result->Mappings.emplace_back(Handle);4647for (int I = 1, E = MD->getNumOperands(); I < E; ++I) {48Metadata *OpMD = MD->getOperand(I);49// Some members may be null if they've been optimized out.50if (!OpMD)51continue;52auto *V = cast<GlobalVariable>(cast<ValueAsMetadata>(OpMD)->getValue());53Mapping.Members.emplace_back(V, getMemberOffset(Handle, I - 1));54}55}5657return Result;58}5960void CBufferMetadata::eraseFromModule() {61// Remove the cbs named metadata62MD->eraseFromParent();63}6465APInt hlsl::translateCBufArrayOffset(const DataLayout &DL, APInt Offset,66ArrayType *Ty) {67int64_t TypeSize = DL.getTypeSizeInBits(Ty->getElementType()) / 8;68int64_t RoundUp = alignTo(TypeSize, Align(CBufferRowSizeInBytes));69return Offset.udiv(TypeSize) * RoundUp;70}717273