clang 24.0.0git
LowerToLLVM.cpp
Go to the documentation of this file.
1//====- LowerToLLVM.cpp - Lowering from CIR to LLVMIR ---------------------===//
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 implements lowering of CIR operations to LLVMIR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LowerToLLVM.h"
14#include "LowerToLLVMMetadata.h"
17
18#include <array>
19#include <optional>
20
21#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
22#include "mlir/Conversion/OpenMPToLLVM/ConvertOpenMPToLLVM.h"
23#include "mlir/Dialect/DLTI/DLTI.h"
24#include "mlir/Dialect/Func/IR/FuncOps.h"
25#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
26#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
27#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
28#include "mlir/Dialect/LLVMIR/Transforms/Passes.h"
29#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
30#include "mlir/Dialect/OpenMP/Transforms/Passes.h"
31#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
32#include "mlir/IR/BuiltinAttributes.h"
33#include "mlir/IR/BuiltinDialect.h"
34#include "mlir/IR/BuiltinOps.h"
35#include "mlir/IR/Diagnostics.h"
36#include "mlir/IR/Location.h"
37#include "mlir/IR/Matchers.h"
38#include "mlir/IR/Types.h"
39#include "mlir/Pass/Pass.h"
40#include "mlir/Pass/PassManager.h"
41#include "mlir/Support/LLVM.h"
42#include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h"
43#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
44#include "mlir/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.h"
45#include "mlir/Target/LLVMIR/Export.h"
46#include "mlir/Transforms/DialectConversion.h"
55#include "clang/CIR/Passes.h"
56#include "llvm/ADT/MapVector.h"
57#include "llvm/ADT/StringMap.h"
58#include "llvm/ADT/TypeSwitch.h"
59#include "llvm/IR/Module.h"
60#include "llvm/Support/AMDGPUAddrSpace.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/TimeProfiler.h"
64#include "llvm/Support/VirtualFileSystem.h"
65#include "llvm/Support/raw_ostream.h"
66#include "llvm/TargetParser/AtomicScope.h"
67
68using namespace cir;
69using namespace llvm;
70
71namespace cir {
72namespace direct {
73
74//===----------------------------------------------------------------------===//
75// Helper Methods
76//===----------------------------------------------------------------------===//
77
78namespace {
79/// If the given type is a vector or matrix type, return its element type.
80/// Otherwise return the given type unchanged.
81mlir::Type elementTypeIfVectorOrMatrix(mlir::Type type) {
82 return llvm::TypeSwitch<mlir::Type, mlir::Type>(type)
83 .Case<cir::VectorType, cir::MatrixType, mlir::VectorType>(
84 [](auto p) { return p.getElementType(); })
85 .Default([](mlir::Type p) { return p; });
86}
87} // namespace
88
89static constexpr char kTypeConversionErrorMsg[] =
90 "ClangIR lowering NYI: cannot convert ";
91
92static mlir::InFlightDiagnostic emitTypeConversionError(mlir::Operation *op,
93 mlir::Type type) {
94 return op->emitError() << kTypeConversionErrorMsg << type;
95}
96
97static mlir::InFlightDiagnostic emitTypeConversionError(mlir::Location loc,
98 mlir::Type type) {
99 return mlir::emitError(loc) << kTypeConversionErrorMsg << type;
100}
101
102/// Alignment to use for a memory access whose op carries no explicit alignment.
103/// For _BitInt the storage integer iM's ABI alignment (e.g. i128's 16)
104/// over-aligns the value, so use the _BitInt language alignment (e.g. 8).
105/// An SVE count lowers to target("aarch64.svcount"), which the MLIR data
106/// layout cannot size, so it also uses its language alignment.
107static uint64_t getMemoryFallbackAlignment(mlir::Operation *op,
108 mlir::Type cirType,
109 mlir::Type llvmMemType,
110 const mlir::DataLayout &dataLayout) {
111 if (cir::isBitIntType(cirType) || mlir::isa<cir::SveCountType>(cirType))
112 return cir::CIRDataLayout(op->getParentOfType<mlir::ModuleOp>())
113 .getTypeLanguageAlignment(cirType);
114 return dataLayout.getTypeABIAlignment(llvmMemType);
115}
116
117static mlir::Value createIntCast(mlir::OpBuilder &bld, mlir::Value src,
118 mlir::IntegerType dstTy,
119 bool isSigned = false) {
120 mlir::Type srcTy = src.getType();
121 assert(mlir::isa<mlir::IntegerType>(srcTy));
122
123 unsigned srcWidth = mlir::cast<mlir::IntegerType>(srcTy).getWidth();
124 unsigned dstWidth = mlir::cast<mlir::IntegerType>(dstTy).getWidth();
125 mlir::Location loc = src.getLoc();
126
127 if (dstWidth > srcWidth && isSigned)
128 return mlir::LLVM::SExtOp::create(bld, loc, dstTy, src);
129 if (dstWidth > srcWidth)
130 return mlir::LLVM::ZExtOp::create(bld, loc, dstTy, src);
131 if (dstWidth < srcWidth)
132 return mlir::LLVM::TruncOp::create(bld, loc, dstTy, src);
133 return mlir::LLVM::BitcastOp::create(bld, loc, dstTy, src);
134}
135
136/// Cast a _BitInt(N) value between its literal width iN and its padded
137/// in-memory storage iM (sign/zero-extend to memory per signedness so the
138/// padding bits are well-defined, truncate back on load; matches classic
139/// CodeGen). Callers must first rule out the unsupported byte-array storage
140/// form (isSplitStorageBitInt / a null convertTypeForMemory result).
141static mlir::Value
142castBitIntMemoryStorage(mlir::ConversionPatternRewriter &rewriter,
143 const mlir::DataLayout &dataLayout, cir::IntType intTy,
144 mlir::Value value, bool toMemory) {
145 unsigned storageBits = intTy.getStorageTypeWidth(dataLayout);
146 if (storageBits == intTy.getWidth())
147 return value;
148 unsigned dstBits = toMemory ? storageBits : intTy.getWidth();
149 return createIntCast(rewriter, value, rewriter.getIntegerType(dstBits),
150 /*isSigned=*/toMemory && intTy.isSigned());
151}
152
153static mlir::LLVM::Visibility
154lowerCIRVisibilityToLLVMVisibility(cir::VisibilityKind visibilityKind) {
155 switch (visibilityKind) {
156 case cir::VisibilityKind::Default:
157 return ::mlir::LLVM::Visibility::Default;
158 case cir::VisibilityKind::Hidden:
159 return ::mlir::LLVM::Visibility::Hidden;
160 case cir::VisibilityKind::Protected:
161 return ::mlir::LLVM::Visibility::Protected;
162 }
163 llvm_unreachable("fully covered switch");
164}
165
166static mlir::Value
167emitBoolVecConversion(mlir::ConversionPatternRewriter &rewriter,
168 mlir::Value srcVec, unsigned numElementsDst) {
169 auto srcTy = mlir::cast<mlir::VectorType>(srcVec.getType());
170 unsigned numElementsSrc = srcTy.getNumElements();
171 if (numElementsSrc == numElementsDst)
172 return srcVec;
173
174 SmallVector<int32_t, 8> mask(numElementsDst, -1);
175 for (unsigned i : llvm::seq(std::min(numElementsDst, numElementsSrc)))
176 mask[i] = i;
177
178 mlir::Location loc = srcVec.getLoc();
179 auto poison = mlir::LLVM::PoisonOp::create(rewriter, loc, srcVec.getType());
180 return mlir::LLVM::ShuffleVectorOp::create(rewriter, loc, srcVec, poison,
181 mask);
182}
183
184/// Emits the value from memory as expected by its users. Should be called when
185/// the memory represetnation of a CIR type is not equal to its scalar
186/// representation.
187static mlir::Value emitFromMemory(mlir::ConversionPatternRewriter &rewriter,
188 const mlir::TypeConverter &converter,
189 mlir::DataLayout const &dataLayout,
190 cir::LoadOp op, mlir::Value value) {
191 // TODO(cir): Handle other types similarly to clang's codegen EmitFromMemory
192 if (auto boolTy = mlir::dyn_cast<cir::BoolType>(op.getType())) {
193 // Create a cast value from specified size in datalayout to i1
194 assert(value.getType().isInteger(dataLayout.getTypeSizeInBits(boolTy)));
195 return createIntCast(rewriter, value, rewriter.getI1Type());
196 }
197
198 // Convert the `iN` back to boolean vectors
199 if (auto vecTy = mlir::dyn_cast<cir::VectorType>(op.getType())) {
200 if (mlir::isa<cir::BoolType>(vecTy.getElementType())) {
201 if (vecTy.isScalable())
202 return value;
203 auto rawIntTy = mlir::cast<mlir::IntegerType>(value.getType());
204 auto paddedVecTy = cir::VectorType::getFixed(vecTy.getElementType(),
205 rawIntTy.getWidth());
206 mlir::Type mlirVecTy = converter.convertType(paddedVecTy);
207 // Bitcast iP --> <P x i1>.
208 auto v = mlir::LLVM::BitcastOp::create(rewriter, value.getLoc(),
209 mlirVecTy, value);
210 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
211 return emitBoolVecConversion(rewriter, v, vecTy.getFixedSize());
212 }
213 }
214
215 // Truncate the padded storage integer back to the _BitInt's literal width.
216 if (auto intTy = mlir::dyn_cast<cir::IntType>(op.getType());
217 cir::isBitIntType(intTy))
218 return castBitIntMemoryStorage(rewriter, dataLayout, intTy, value,
219 /*toMemory=*/false);
220
221 return value;
222}
223
224/// Emits a value to memory with the expected scalar type. Should be called when
225/// the memory represetnation of a CIR type is not equal to its scalar
226/// representation.
227static mlir::Value emitToMemory(mlir::ConversionPatternRewriter &rewriter,
228 mlir::DataLayout const &dataLayout,
229 mlir::Type origType, mlir::Value value) {
230
231 // TODO(cir): Handle other types similarly to clang's codegen EmitToMemory
232 if (auto boolTy = mlir::dyn_cast<cir::BoolType>(origType)) {
233 // Create zext of value from i1 to i8
234 mlir::IntegerType memType =
235 rewriter.getIntegerType(dataLayout.getTypeSizeInBits(boolTy));
236 return createIntCast(rewriter, value, memType);
237 }
238
239 // Boolean vectors use:
240 // * `iN` for fixed-width vectors,
241 // * `<vscale x N x i1>` for scalable vectors,
242 // as storage type.
243 if (auto vecTy = mlir::dyn_cast<cir::VectorType>(origType)) {
244 if (mlir::isa<cir::BoolType>(vecTy.getElementType())) {
245 mlir::Type resultTy;
246 if (vecTy.isScalable())
247 resultTy =
248 mlir::VectorType::get(vecTy.getSize().getKnownMinValue(),
249 vecTy.getElementType(), vecTy.isScalable());
250 else {
251 resultTy = mlir::IntegerType::get(origType.getContext(),
252 vecTy.getBoolStorageWidth());
253 value =
254 emitBoolVecConversion(rewriter, value, vecTy.getBoolStorageWidth());
255 }
256 return mlir::LLVM::BitcastOp::create(rewriter, value.getLoc(), resultTy,
257 value);
258 }
259 }
260
261 // Sign/zero-extend the _BitInt value to its padded storage integer.
262 if (auto intTy = mlir::dyn_cast<cir::IntType>(origType);
263 cir::isBitIntType(intTy))
264 return castBitIntMemoryStorage(rewriter, dataLayout, intTy, value,
265 /*toMemory=*/true);
266
267 return value;
268}
269
270mlir::LLVM::Linkage convertLinkage(cir::GlobalLinkageKind linkage) {
271 using CIR = cir::GlobalLinkageKind;
272 using LLVM = mlir::LLVM::Linkage;
273
274 switch (linkage) {
275 case CIR::AppendingLinkage:
276 return LLVM::Appending;
277 case CIR::AvailableExternallyLinkage:
278 return LLVM::AvailableExternally;
279 case CIR::CommonLinkage:
280 return LLVM::Common;
281 case CIR::ExternalLinkage:
282 return LLVM::External;
283 case CIR::ExternalWeakLinkage:
284 return LLVM::ExternWeak;
285 case CIR::InternalLinkage:
286 return LLVM::Internal;
287 case CIR::LinkOnceAnyLinkage:
288 return LLVM::Linkonce;
289 case CIR::LinkOnceODRLinkage:
290 return LLVM::LinkonceODR;
291 case CIR::PrivateLinkage:
292 return LLVM::Private;
293 case CIR::WeakAnyLinkage:
294 return LLVM::Weak;
295 case CIR::WeakODRLinkage:
296 return LLVM::WeakODR;
297 };
298 llvm_unreachable("Unknown CIR linkage type");
299}
300
301static mlir::LLVM::CConv convertCallingConv(cir::CallingConv callingConv) {
302 using CIR = cir::CallingConv;
303 using LLVM = mlir::LLVM::CConv;
304
305 switch (callingConv) {
306 case CIR::C:
307 return LLVM::C;
308 case CIR::SpirKernel:
309 return LLVM::SPIR_KERNEL;
310 case CIR::SpirFunction:
311 return LLVM::SPIR_FUNC;
312 case CIR::PTXKernel:
313 return LLVM::PTX_Kernel;
314 case CIR::AMDGPUKernel:
315 return LLVM::AMDGPU_KERNEL;
316 }
317 llvm_unreachable("Unknown calling convention");
318}
319
320static mlir::LLVM::uwtable::UWTableKind
321convertUWTableKind(cir::UnwindTableKind kind) {
322 using CIR = cir::UnwindTableKind;
323 using LLVM = mlir::LLVM::uwtable::UWTableKind;
324
325 switch (kind) {
326 case CIR::None:
327 return LLVM::None;
328 case CIR::Sync:
329 return LLVM::Sync;
330 case CIR::Async:
331 return LLVM::Async;
332 }
333 llvm_unreachable("Unknown CIR unwind table kind");
334}
335
336static mlir::LLVM::framePointerKind::FramePointerKind
337convertFramePointerKind(cir::FramePointerKind kind) {
338 using CIR = cir::FramePointerKind;
339 using LLVM = mlir::LLVM::framePointerKind::FramePointerKind;
340
341 switch (kind) {
342 case CIR::None:
343 return LLVM::None;
344 case CIR::NonLeaf:
345 return LLVM::NonLeaf;
346 case CIR::All:
347 return LLVM::All;
348 case CIR::Reserved:
349 return LLVM::Reserved;
350 case CIR::NonLeafNoReserve:
351 return LLVM::NonLeafNoReserve;
352 }
353 llvm_unreachable("Unknown CIR frame pointer kind");
354}
355
356/// The "frame-pointer" module flag holds an llvm::FramePointerKind value, as
357/// written by llvm::Module::setFramePointer.
358static llvm::FramePointerKind
359convertFramePointerKindToLLVMIR(cir::FramePointerKind kind) {
360 using CIR = cir::FramePointerKind;
361 using LLVM = llvm::FramePointerKind;
362
363 switch (kind) {
364 case CIR::None:
365 return LLVM::None;
366 case CIR::NonLeaf:
367 return LLVM::NonLeaf;
368 case CIR::All:
369 return LLVM::All;
370 case CIR::Reserved:
371 return LLVM::Reserved;
372 case CIR::NonLeafNoReserve:
373 return LLVM::NonLeafNoReserve;
374 }
375 llvm_unreachable("Unknown CIR frame pointer kind");
376}
377
378mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite(
379 cir::CopyOp op, OpAdaptor adaptor,
380 mlir::ConversionPatternRewriter &rewriter) const {
381 // Opaque pointer conversion does not validate the pointee's memory layout.
382 mlir::Type pointeeType = op.getType().getPointee();
383 if (!convertTypeForMemory(*getTypeConverter(), dataLayout, pointeeType))
384 return emitTypeConversionError(op, pointeeType);
385
386 cir::CIRDataLayout cirDataLayout(op->getParentOfType<mlir::ModuleOp>());
387 const mlir::Value length = mlir::LLVM::ConstantOp::create(
388 rewriter, op.getLoc(), rewriter.getI64Type(),
389 op.getCopySizeInBytes(cirDataLayout.layout));
391
392 uint64_t dstTypeAlign = cirDataLayout.getTypeLanguageAlignment(
393 op.getDst().getType().getPointee());
394 uint64_t srcTypeAlign = cirDataLayout.getTypeLanguageAlignment(
395 op.getSrc().getType().getPointee());
396
397 mlir::NamedAttribute dstAlignAttr = rewriter.getNamedAttr(
398 mlir::LLVM::LLVMDialect::getAlignAttrName(),
399 rewriter.getI64IntegerAttr(op.getDstAlignment().value_or(dstTypeAlign)));
400 mlir::NamedAttribute srcAlignAttr = rewriter.getNamedAttr(
401 mlir::LLVM::LLVMDialect::getAlignAttrName(),
402 rewriter.getI64IntegerAttr(op.getSrcAlignment().value_or(srcTypeAlign)));
403 mlir::ArrayAttr argAttrs = rewriter.getArrayAttr({
404 /*dst_attrs=*/rewriter.getDictionaryAttr({dstAlignAttr}),
405 /*src_attrs=*/rewriter.getDictionaryAttr({srcAlignAttr}),
406 });
407
408 rewriter.replaceOpWithNewOp<mlir::LLVM::MemcpyOp>(
409 op, adaptor.getDst(), adaptor.getSrc(), length, op.getIsVolatile(),
410 /*tbaa_struct=*/nullptr, /*access_groups=*/nullptr,
411 /*alias_scopes=*/nullptr, /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr,
412 /*arg_attrs=*/argAttrs, /*res_attrs=*/nullptr);
413 return mlir::success();
414}
415
416template <typename CIROp, typename LLVMOp>
417static mlir::LogicalResult
418lowerMemTransferOp(CIROp op, typename CIROp::Adaptor adaptor,
419 mlir::ConversionPatternRewriter &rewriter) {
420 mlir::ArrayAttr argAttrs;
421 if (op.getDstAlignment() || op.getSrcAlignment()) {
422 mlir::NamedAttribute dstAlignAttr = rewriter.getNamedAttr(
423 mlir::LLVM::LLVMDialect::getAlignAttrName(),
424 rewriter.getI64IntegerAttr(op.getDstAlignment().value_or(1)));
425 mlir::NamedAttribute srcAlignAttr = rewriter.getNamedAttr(
426 mlir::LLVM::LLVMDialect::getAlignAttrName(),
427 rewriter.getI64IntegerAttr(op.getSrcAlignment().value_or(1)));
428 argAttrs = rewriter.getArrayAttr({
429 /*dst_attrs=*/rewriter.getDictionaryAttr({dstAlignAttr}),
430 /*src_attrs=*/rewriter.getDictionaryAttr({srcAlignAttr}),
431 });
432 }
433 rewriter.replaceOpWithNewOp<LLVMOp>(
434 op, adaptor.getDst(), adaptor.getSrc(), adaptor.getLen(),
435 /*isVolatile=*/false, /*tbaa_struct=*/nullptr,
436 /*access_groups=*/nullptr, /*alias_scopes=*/nullptr,
437 /*noalias_scopes=*/nullptr, /*tbaa=*/nullptr, /*arg_attrs=*/argAttrs,
438 /*res_attrs=*/nullptr);
439 return mlir::success();
440}
441
442mlir::LogicalResult CIRToLLVMMemCpyOpLowering::matchAndRewrite(
443 cir::MemCpyOp op, OpAdaptor adaptor,
444 mlir::ConversionPatternRewriter &rewriter) const {
446 rewriter);
447}
448
449mlir::LogicalResult CIRToLLVMMemMoveOpLowering::matchAndRewrite(
450 cir::MemMoveOp op, OpAdaptor adaptor,
451 mlir::ConversionPatternRewriter &rewriter) const {
453 rewriter);
454}
455
456mlir::LogicalResult CIRToLLVMMemSetOpLowering::matchAndRewrite(
457 cir::MemSetOp op, OpAdaptor adaptor,
458 mlir::ConversionPatternRewriter &rewriter) const {
459
460 // Capture the alignment before the replace erases `op`.
461 mlir::Attribute alignAttr = op.getAlignmentAttr();
462 auto memset = rewriter.replaceOpWithNewOp<mlir::LLVM::MemsetOp>(
463 op, adaptor.getDst(), adaptor.getVal(), adaptor.getLen(),
464 /*isVolatile=*/false);
465
466 if (alignAttr) {
467 // Construct a list full of empty attributes.
468 llvm::SmallVector<mlir::Attribute> attrs{memset.getNumOperands(),
469 rewriter.getDictionaryAttr({})};
470 llvm::SmallVector<mlir::NamedAttribute> destAttrs;
471 destAttrs.push_back(
472 {mlir::LLVM::LLVMDialect::getAlignAttrName(), alignAttr});
473 attrs[memset.odsIndex_dst] = rewriter.getDictionaryAttr(destAttrs);
474
475 auto arrayAttr = rewriter.getArrayAttr(attrs);
476 memset.setArgAttrsAttr(arrayAttr);
477 }
478
479 return mlir::success();
480}
481
482static mlir::Value getLLVMIntCast(mlir::ConversionPatternRewriter &rewriter,
483 mlir::Value llvmSrc, mlir::Type llvmDstIntTy,
484 bool isUnsigned, uint64_t cirSrcWidth,
485 uint64_t cirDstIntWidth) {
486 if (cirSrcWidth == cirDstIntWidth)
487 return llvmSrc;
488
489 auto loc = llvmSrc.getLoc();
490 if (cirSrcWidth < cirDstIntWidth) {
491 if (isUnsigned)
492 return mlir::LLVM::ZExtOp::create(rewriter, loc, llvmDstIntTy, llvmSrc);
493 return mlir::LLVM::SExtOp::create(rewriter, loc, llvmDstIntTy, llvmSrc);
494 }
495
496 // Otherwise truncate
497 return mlir::LLVM::TruncOp::create(rewriter, loc, llvmDstIntTy, llvmSrc);
498}
499
501public:
502 CIRAttrToValue(mlir::Location parentLoc, mlir::ModuleOp parentModule,
503 mlir::ConversionPatternRewriter &rewriter,
504 mlir::SymbolTableCollection &symbolTables,
505 const mlir::TypeConverter *converter,
506 const CIRPreConversionTypeMap &preConversionTypes,
507 LLVMBlockAddressInfo *blockInfoAddr = nullptr)
508 : parentLoc(parentLoc), parentModule(parentModule), rewriter(rewriter),
509 symbolTables(symbolTables), converter(converter),
510 preConversionTypes(preConversionTypes), blockInfoAddr(blockInfoAddr) {}
511
512#define GET_CIR_ATTR_TO_VALUE_VISITOR_DECLS
513#include "clang/CIR/Dialect/IR/CIRLowering.inc"
514#undef GET_CIR_ATTR_TO_VALUE_VISITOR_DECLS
515
516private:
517 struct LoweredGlobalSymbol {
518 mlir::Value addr;
519 mlir::Type sourceType;
520 mlir::Type originalType;
521 unsigned addrSpace;
522 };
523
524 LoweredGlobalSymbol getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol);
525 mlir::Value castGlobalAddrToType(mlir::Value addr, mlir::Type attrType,
526 mlir::Type sourceType, unsigned addrSpace);
527
528 mlir::Location parentLoc;
529 mlir::ModuleOp parentModule;
530 mlir::ConversionPatternRewriter &rewriter;
531 mlir::SymbolTableCollection &symbolTables;
532 const mlir::TypeConverter *converter;
533 const CIRPreConversionTypeMap &preConversionTypes;
534 // Only available when lowering global initializers that may contain block
535 // address attributes. Used to resolve a BlockAddrInfoAttr to its block tag.
536 LLVMBlockAddressInfo *blockInfoAddr;
537};
538
539/// Switches on the type of attribute and calls the appropriate conversion.
540mlir::Value
541lowerCirAttrAsValue(mlir::Location parentLoc, mlir::ModuleOp parentModule,
542 const mlir::Attribute attr,
543 mlir::ConversionPatternRewriter &rewriter,
544 mlir::SymbolTableCollection &symbolTables,
545 const mlir::TypeConverter *converter,
546 const CIRPreConversionTypeMap &preConversionTypes,
547 LLVMBlockAddressInfo *blockInfoAddr) {
548 CIRAttrToValue valueConverter(parentLoc, parentModule, rewriter, symbolTables,
549 converter, preConversionTypes, blockInfoAddr);
550 return valueConverter.visit(attr);
551}
552
553static mlir::LLVM::ModRefInfo convertModRefInfo(cir::ModRefInfo info) {
554 switch (info) {
555 case cir::ModRefInfo::NoModRef:
556 return mlir::LLVM::ModRefInfo::NoModRef;
557 case cir::ModRefInfo::Ref:
558 return mlir::LLVM::ModRefInfo::Ref;
559 case cir::ModRefInfo::Mod:
560 return mlir::LLVM::ModRefInfo::Mod;
561 case cir::ModRefInfo::ModRef:
562 return mlir::LLVM::ModRefInfo::ModRef;
563 }
564 llvm_unreachable("unhandled cir::ModRefInfo");
565}
566
567/// A null input stays null, which is how both dialects spell unknown effects.
568static mlir::LLVM::MemoryEffectsAttr
569convertMemoryEffects(mlir::MLIRContext *ctx, cir::MemoryEffectsAttr effects) {
570 if (!effects)
571 return {};
572
573 return mlir::LLVM::MemoryEffectsAttr::get(
574 ctx, convertModRefInfo(effects.getOther()),
575 convertModRefInfo(effects.getArgMem()),
576 convertModRefInfo(effects.getInaccessibleMem()),
577 convertModRefInfo(effects.getErrnoMem()),
578 convertModRefInfo(effects.getTargetMem0()),
579 convertModRefInfo(effects.getTargetMem1()));
580}
581
582static void convertCallEffects(mlir::Operation *callOp, bool isNothrow,
583 cir::MemoryEffectsAttr effects,
584 mlir::LLVM::MemoryEffectsAttr &memoryEffect,
585 bool &noUnwind, bool &willReturn,
586 bool &noReturn) {
587 memoryEffect = convertMemoryEffects(callOp->getContext(), effects);
588 // CIR spells two separate cannot-unwind facts, nothrow for a callee
589 // declared not to throw and nounwind for one whose effects rule out
590 // unwinding. LLVM has only nounwind, so either one sets it.
591 noUnwind = isNothrow || callOp->hasAttr(CIRDialect::getNoUnwindAttrName());
592 willReturn = callOp->hasAttr(CIRDialect::getWillReturnAttrName());
593 noReturn = callOp->hasAttr(CIRDialect::getNoReturnAttrName());
594}
595
596static mlir::LLVM::CallIntrinsicOp
597createCallLLVMIntrinsicOp(mlir::ConversionPatternRewriter &rewriter,
598 mlir::Location loc, const llvm::Twine &intrinsicName,
599 mlir::Type resultTy, mlir::ValueRange operands,
600 mlir::LLVM::FastmathFlags fastmathFlags = {}) {
601 auto intrinsicNameAttr =
602 mlir::StringAttr::get(rewriter.getContext(), intrinsicName);
603 auto fmfAttr =
604 mlir::LLVM::FastmathFlagsAttr::get(rewriter.getContext(), fastmathFlags);
605 // CallIntrinsicOp has distinct void / result create overloads. The FMF
606 // builders take a TypeRange for results.
607 if (resultTy)
608 return mlir::LLVM::CallIntrinsicOp::create(
609 rewriter, loc, mlir::TypeRange{resultTy}, intrinsicNameAttr, operands,
610 fmfAttr);
611 return mlir::LLVM::CallIntrinsicOp::create(rewriter, loc, intrinsicNameAttr,
612 operands, fmfAttr);
613}
614
615static mlir::LLVM::CallIntrinsicOp replaceOpWithCallLLVMIntrinsicOp(
616 mlir::ConversionPatternRewriter &rewriter, mlir::Operation *op,
617 const llvm::Twine &intrinsicName, mlir::Type resultTy,
618 mlir::ValueRange operands, mlir::LLVM::FastmathFlags fastmathFlags = {}) {
619 mlir::LLVM::CallIntrinsicOp callIntrinOp = createCallLLVMIntrinsicOp(
620 rewriter, op->getLoc(), intrinsicName, resultTy, operands, fastmathFlags);
621 rewriter.replaceOp(op, callIntrinOp.getOperation());
622 return callIntrinOp;
623}
624
625static llvm::StringRef getConstrainedRoundingMetadata(cir::FenvAttr fenv) {
626 std::optional<cir::FPDynamicRoundingMode> rounding =
627 fenv.getDynamicRoundingMode();
628 if (!rounding)
629 return "round.tonearest";
630 switch (*rounding) {
631 case cir::FPDynamicRoundingMode::ToNearest:
632 return "round.tonearest";
633 case cir::FPDynamicRoundingMode::Downward:
634 return "round.downward";
635 case cir::FPDynamicRoundingMode::Upward:
636 return "round.upward";
637 case cir::FPDynamicRoundingMode::UpwardZero:
638 return "round.towardzero";
639 case cir::FPDynamicRoundingMode::ToNearestAway:
640 return "round.tonearestaway";
641 case cir::FPDynamicRoundingMode::Unknown:
642 return "round.dynamic";
643 }
644 llvm_unreachable("unknown FP dynamic rounding mode");
645}
646
647static llvm::StringRef getConstrainedExceptMetadata(cir::FenvAttr fenv) {
648 std::optional<cir::FPExceptionMode> exceptMode = fenv.getExceptMode();
649 if (exceptMode == cir::FPExceptionMode::Masked)
650 return "fpexcept.ignore";
651 mlir::BoolAttr strictExcept = fenv.getStrictExcept();
652 if (!strictExcept)
653 return "fpexcept.ignore";
654 return strictExcept.getValue() ? "fpexcept.strict" : "fpexcept.maytrap";
655}
656
657static mlir::Value
658createFenvMetadataValue(mlir::ConversionPatternRewriter &rewriter,
659 mlir::Location loc, llvm::StringRef str) {
660 auto mdString = mlir::LLVM::MDStringAttr::get(
661 rewriter.getContext(), mlir::StringAttr::get(rewriter.getContext(), str));
662 return mlir::LLVM::MetadataAsValueOp::create(rewriter, loc, mdString);
663}
664
666 mlir::Operation *op, mlir::ValueRange operands, cir::FenvAttr fenv,
667 mlir::Type llvmResTy, mlir::ConversionPatternRewriter &rewriter,
668 llvm::StringRef constrainedMnemonic, bool hasRoundingMode,
669 mlir::LLVM::FastmathFlags fastmathFlags) {
670 mlir::Location loc = op->getLoc();
671 llvm::SmallVector<mlir::Value> callOperands(operands.begin(), operands.end());
672 if (hasRoundingMode)
673 callOperands.push_back(createFenvMetadataValue(
674 rewriter, loc, getConstrainedRoundingMetadata(fenv)));
675 callOperands.push_back(createFenvMetadataValue(
676 rewriter, loc, getConstrainedExceptMetadata(fenv)));
677
679 rewriter, op, "llvm.experimental.constrained." + constrainedMnemonic,
680 llvmResTy, callOperands, fastmathFlags);
681 return mlir::success();
682}
683
684static mlir::LLVM::FastmathFlags
685convertFastMathFlags(cir::FastMathFlags cirFlags);
686
688 mlir::ConversionPatternRewriter &rewriter, mlir::Location loc,
689 mlir::ValueRange operands, mlir::Type llvmResTy, cir::FenvAttr fenv,
690 llvm::StringRef constrainedMnemonic, bool hasRoundingMode,
691 mlir::LLVM::FastmathFlags fastmathFlags = {}) {
692 llvm::SmallVector<mlir::Value> callOperands(operands.begin(), operands.end());
693 if (hasRoundingMode)
694 callOperands.push_back(createFenvMetadataValue(
695 rewriter, loc, getConstrainedRoundingMetadata(fenv)));
696
697 callOperands.push_back(createFenvMetadataValue(
698 rewriter, loc, getConstrainedExceptMetadata(fenv)));
699
700 mlir::LLVM::CallIntrinsicOp intrinsic = createCallLLVMIntrinsicOp(
701 rewriter, loc, "llvm.experimental.constrained." + constrainedMnemonic,
702 llvmResTy, callOperands, fastmathFlags);
703 return intrinsic->getResult(0);
704}
705
706template <typename LLVMOp>
707mlir::LogicalResult lowerFPOp(mlir::Operation *op, mlir::ValueRange operands,
708 cir::FastMathFlagsAttr fastmath,
709 const mlir::TypeConverter &typeConverter,
710 mlir::ConversionPatternRewriter &rewriter) {
711 mlir::Type llvmResTy = typeConverter.convertType(op->getResultTypes()[0]);
712 if (!llvmResTy)
713 return op->emitError("expected LLVM result type for floating-point op");
714
715 auto newOp = rewriter.replaceOpWithNewOp<LLVMOp>(
716 op, mlir::TypeRange{llvmResTy}, operands,
717 cir::getDefaultProperties<LLVMOp>(op->getContext()));
718 if (fastmath)
719 mlir::cast<mlir::LLVM::FastmathFlagsInterface>(newOp.getOperation())
720 .setFastmathAttr(mlir::LLVM::FastmathFlagsAttr::get(
721 rewriter.getContext(), convertFastMathFlags(fastmath.getValue())));
722 return mlir::success();
723}
724
725template <typename LLVMOp>
726mlir::LogicalResult lowerConstrainableFPOp(
727 mlir::Operation *op, mlir::ValueRange operands, cir::FenvAttr fenv,
728 cir::FastMathFlagsAttr fastmath, const mlir::TypeConverter &typeConverter,
729 mlir::ConversionPatternRewriter &rewriter,
730 llvm::StringRef constrainedMnemonic, bool hasRoundingMode) {
731 if (!fenv)
732 return lowerFPOp<LLVMOp>(op, operands, fastmath, typeConverter, rewriter);
733
734 mlir::Type llvmResTy = typeConverter.convertType(op->getResultTypes()[0]);
735 if (!llvmResTy)
736 return op->emitError("expected LLVM result type for floating-point op");
737
738 mlir::LLVM::FastmathFlags fastmathFlags = {};
739 if (fastmath)
740 fastmathFlags = convertFastMathFlags(fastmath.getValue());
741
742 return lowerToConstrainedFPIntrinsic(op, operands, fenv, llvmResTy, rewriter,
743 constrainedMnemonic, hasRoundingMode,
744 fastmathFlags);
745}
746
747mlir::LLVM::FastmathFlagsAttr
748convertToLLVMProperty(mlir::MLIRContext *ctx,
749 std::optional<cir::FastMathFlags> flags) {
750 return mlir::LLVM::FastmathFlagsAttr::get(
751 ctx, flags ? convertFastMathFlags(*flags) : mlir::LLVM::FastmathFlags{});
752}
753
754mlir::IntegerAttr convertToLLVMProperty(mlir::MLIRContext *ctx,
755 cir::FPClassTest flags) {
756 return mlir::IntegerAttr::get(mlir::IntegerType::get(ctx, 32),
757 static_cast<uint32_t>(flags));
758}
759
760mlir::IntegerAttr convertToLLVMProperty(mlir::MLIRContext *ctx, bool flag) {
761 return mlir::IntegerAttr::get(mlir::IntegerType::get(ctx, 1), flag);
762}
763
764static mlir::LLVM::FastmathFlags
765convertFastMathFlags(cir::FastMathFlags cirFlags) {
766 mlir::LLVM::FastmathFlags llvmFlags{};
767 const std::pair<cir::FastMathFlags, mlir::LLVM::FastmathFlags> flags[] = {
768 {cir::FastMathFlags::nnan, mlir::LLVM::FastmathFlags::nnan},
769 {cir::FastMathFlags::ninf, mlir::LLVM::FastmathFlags::ninf},
770 {cir::FastMathFlags::nsz, mlir::LLVM::FastmathFlags::nsz},
771 {cir::FastMathFlags::arcp, mlir::LLVM::FastmathFlags::arcp},
772 {cir::FastMathFlags::contract, mlir::LLVM::FastmathFlags::contract},
773 {cir::FastMathFlags::afn, mlir::LLVM::FastmathFlags::afn},
774 {cir::FastMathFlags::reassoc, mlir::LLVM::FastmathFlags::reassoc},
775 };
776
777 for (auto [cirFlag, llvmFlag] : flags) {
778 if (bitEnumContainsAny(cirFlags, cirFlag))
779 llvmFlags = llvmFlags | llvmFlag;
780 }
781
782 return llvmFlags;
783}
784
785mlir::LogicalResult CIRToLLVMLLVMIntrinsicCallOpLowering::matchAndRewrite(
786 cir::LLVMIntrinsicCallOp op, OpAdaptor adaptor,
787 mlir::ConversionPatternRewriter &rewriter) const {
788 // Result is Optional on the op, so void intrinsics have zero
789 // results; leave llvmResTy null in that case.
790 mlir::Type llvmResTy;
791 if (op->getNumResults() != 0) {
792 llvmResTy = getTypeConverter()->convertType(op->getResultTypes()[0]);
793 if (!llvmResTy)
794 return op.emitError("expected LLVM result type");
795 }
796 StringRef name = op.getIntrinsicName();
797 mlir::LLVM::FastmathFlags fastmathFlags = {};
798 if (std::optional<cir::FastMathFlags> fastmath = op.getFastmathFlags())
799 fastmathFlags = convertFastMathFlags(*fastmath);
800
801 // Some LLVM intrinsics require ElementType attribute to be attached to
802 // the argument of pointer type. That prevents us from generating LLVM IR
803 // because from LLVM dialect, we have LLVM IR like the below which fails
804 // LLVM IR verification.
805 // %3 = call i64 @llvm.aarch64.ldxr.p0(ptr %2)
806 // The expected LLVM IR should be like
807 // %3 = call i64 @llvm.aarch64.ldxr.p0(ptr elementtype(i32) %2)
808 // TODO(cir): MLIR LLVM dialect should handle this part as CIR has no way
809 // to set LLVM IR attribute.
811 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm." + name, llvmResTy,
812 adaptor.getOperands(), fastmathFlags);
813 return mlir::success();
814}
815
816/// BoolAttr visitor.
817mlir::Value CIRAttrToValue::visitCirAttr(cir::BoolAttr boolAttr) {
818 mlir::DataLayout layout(parentModule);
819 mlir::Value boolVal = mlir::LLVM::ConstantOp::create(
820 rewriter, parentLoc, converter->convertType(boolAttr.getType()),
821 boolAttr.getValue());
822 return emitToMemory(rewriter, layout, boolAttr.getType(), boolVal);
823}
824
825/// IntAttr visitor.
826mlir::Value CIRAttrToValue::visitCirAttr(cir::IntAttr intAttr) {
827 mlir::DataLayout layout(parentModule);
828
829 mlir::Type type = intAttr.getType();
830 if (cir::isBitIntType(type)) {
831 mlir::Type biTy = convertTypeForMemory(*converter, layout, type);
832 return mlir::LLVM::ConstantOp::create(
833 rewriter, parentLoc, biTy,
834 getBitIntStorageAttr(rewriter, intAttr, layout));
835 }
836
837 // Materialize the value at its literal width, then widen to the in-memory
838 // storage type (a no-op except for _BitInt) so aggregate members built here
839 // match the iM struct/array fields produced by convertTypeForMemory.
840 mlir::Value val = mlir::LLVM::ConstantOp::create(
841 rewriter, parentLoc, converter->convertType(intAttr.getType()),
842 intAttr.getValue());
843 return emitToMemory(rewriter, layout, intAttr.getType(), val);
844}
845
846/// FPAttr visitor.
847mlir::Value CIRAttrToValue::visitCirAttr(cir::FPAttr fltAttr) {
848 return mlir::LLVM::ConstantOp::create(
849 rewriter, parentLoc, converter->convertType(fltAttr.getType()),
850 fltAttr.getValue());
851}
852
853/// ConstComplexAttr visitor.
854mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstComplexAttr complexAttr) {
855 cir::ComplexType complexType = complexAttr.getType();
856 mlir::Type complexElemTy = complexType.getElementType();
857 mlir::Type complexElemLLVMTy = converter->convertType(complexElemTy);
858
859 mlir::Attribute components[2];
860 if (const auto intType = mlir::dyn_cast<cir::IntType>(complexElemTy)) {
861 components[0] = rewriter.getIntegerAttr(
862 complexElemLLVMTy,
863 mlir::cast<cir::IntAttr>(complexAttr.getReal()).getValue());
864 components[1] = rewriter.getIntegerAttr(
865 complexElemLLVMTy,
866 mlir::cast<cir::IntAttr>(complexAttr.getImag()).getValue());
867 } else {
868 components[0] = rewriter.getFloatAttr(
869 complexElemLLVMTy,
870 mlir::cast<cir::FPAttr>(complexAttr.getReal()).getValue());
871 components[1] = rewriter.getFloatAttr(
872 complexElemLLVMTy,
873 mlir::cast<cir::FPAttr>(complexAttr.getImag()).getValue());
874 }
875
876 return mlir::LLVM::ConstantOp::create(
877 rewriter, parentLoc, converter->convertType(complexAttr.getType()),
878 rewriter.getArrayAttr(components));
879}
880
881/// ConstPtrAttr visitor.
882mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstPtrAttr ptrAttr) {
883 if (ptrAttr.isNullValue()) {
884 return mlir::LLVM::ZeroOp::create(
885 rewriter, parentLoc, converter->convertType(ptrAttr.getType()));
886 }
887 mlir::DataLayout layout(parentModule);
888 mlir::Value ptrVal = mlir::LLVM::ConstantOp::create(
889 rewriter, parentLoc,
890 rewriter.getIntegerType(layout.getTypeSizeInBits(ptrAttr.getType())),
891 ptrAttr.getValue().getInt());
892 return mlir::LLVM::IntToPtrOp::create(
893 rewriter, parentLoc, converter->convertType(ptrAttr.getType()), ptrVal);
894}
895
896/// BlockAddrInfoAttr visitor.
897mlir::Value CIRAttrToValue::visitCirAttr(cir::BlockAddrInfoAttr blockAddrInfo) {
898 assert(blockInfoAddr &&
899 "block address lowering requires LLVMBlockAddressInfo");
900 // A block address is lowered to an llvm.blockaddress op that references a
901 // block tag inside the target function. The matching block tag may not have
902 // been emitted yet, in which case the address is recorded as unresolved and
903 // patched up later in resolveBlockAddressOp.
904 mlir::LLVM::BlockTagOp matchLabel =
905 blockInfoAddr->lookupBlockTag(blockAddrInfo);
906 mlir::LLVM::BlockTagAttr tagAttr =
907 matchLabel ? matchLabel.getTag() : mlir::LLVM::BlockTagAttr{};
908 auto blkAddr = mlir::LLVM::BlockAddressAttr::get(
909 rewriter.getContext(), blockAddrInfo.getFunc(), tagAttr);
910 auto blockAddressOp = mlir::LLVM::BlockAddressOp::create(
911 rewriter, parentLoc,
912 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()), blkAddr);
913 if (!matchLabel)
914 blockInfoAddr->addUnresolvedBlockAddress(blockAddressOp, blockAddrInfo);
915 return blockAddressOp;
916}
917
918/// BlockAddrDiffAttr visitor.
919mlir::Value CIRAttrToValue::visitCirAttr(cir::BlockAddrDiffAttr blockAddrDiff) {
920 assert(blockInfoAddr &&
921 "block address lowering requires LLVMBlockAddressInfo");
922 // A block-address difference initializer is lowered to the difference of the
923 // two block addresses: trunc(ptrtoint(lhs) - ptrtoint(rhs)). Just like a
924 // single block address, each referenced block tag may not have been emitted
925 // yet, in which case it is recorded as unresolved and patched up later in
926 // resolveBlockAddressOp.
927 mlir::DataLayout layout(parentModule);
928 mlir::MLIRContext *ctx = rewriter.getContext();
929 auto ptrTy = mlir::LLVM::LLVMPointerType::get(ctx);
930
931 auto emitBlockAddr = [&](mlir::StringAttr label) -> mlir::Value {
932 auto info = cir::BlockAddrInfoAttr::get(
933 ctx, blockAddrDiff.getFunc().getValue(), label.getValue());
934 mlir::LLVM::BlockTagOp matchLabel = blockInfoAddr->lookupBlockTag(info);
935 mlir::LLVM::BlockTagAttr tagAttr =
936 matchLabel ? matchLabel.getTag() : mlir::LLVM::BlockTagAttr{};
937 auto blkAddr = mlir::LLVM::BlockAddressAttr::get(
938 ctx, blockAddrDiff.getFunc(), tagAttr);
939 auto addrOp =
940 mlir::LLVM::BlockAddressOp::create(rewriter, parentLoc, ptrTy, blkAddr);
941 if (!matchLabel)
942 blockInfoAddr->addUnresolvedBlockAddress(addrOp, info);
943 return addrOp;
944 };
945
946 mlir::Value lhsAddr = emitBlockAddr(blockAddrDiff.getLhsLabel());
947 mlir::Value rhsAddr = emitBlockAddr(blockAddrDiff.getRhsLabel());
948
949 // Compute the difference in a pointer-sized integer, then truncate to the
950 // initializer's type. LLVM is sensitive about the exact format of the
951 // address-of-label difference, so the truncation must happen after the
952 // subtraction.
953 mlir::Type intptrTy =
954 rewriter.getIntegerType(layout.getTypeSizeInBits(ptrTy));
955 mlir::Value lhsInt =
956 mlir::LLVM::PtrToIntOp::create(rewriter, parentLoc, intptrTy, lhsAddr);
957 mlir::Value rhsInt =
958 mlir::LLVM::PtrToIntOp::create(rewriter, parentLoc, intptrTy, rhsAddr);
959 mlir::Value diffVal =
960 mlir::LLVM::SubOp::create(rewriter, parentLoc, lhsInt, rhsInt);
961
962 mlir::Type resultTy = converter->convertType(blockAddrDiff.getType());
963 mlir::Value result = diffVal;
964 if (resultTy != intptrTy)
965 result =
966 mlir::LLVM::TruncOp::create(rewriter, parentLoc, resultTy, diffVal);
967 return result;
968}
969
970// ConstArrayAttr visitor
971mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstArrayAttr attr) {
972 mlir::Type convertedTy = converter->convertType(attr.getType());
973 mlir::DataLayout dataLayout(parentModule);
974 mlir::Type failedType = attr.getType();
975 mlir::Type llvmTy = adjustGlobalTypeForInit(convertedTy, attr, *converter,
976 dataLayout, &failedType);
977 if (!llvmTy) {
978 emitTypeConversionError(parentLoc, failedType);
979 return {};
980 }
981 mlir::Value result;
982
983 // When the array can be represented as a single constant attribute, emit one
984 // llvm.mlir.constant instead of a chain of llvm.insertvalue ops. That works
985 // for any array type, including an array of split rows, but not for a split
986 // array itself: a struct-typed constant needs scalar fields.
987 if (mlir::isa<mlir::LLVM::LLVMArrayType>(llvmTy))
988 if (std::optional<mlir::Attribute> constAttr = lowerConstArrayAttr(
989 attr, symbolTables, converter, preConversionTypes, parentModule))
990 return mlir::LLVM::ConstantOp::create(rewriter, parentLoc, llvmTy,
991 *constAttr);
992
993 if (attr.hasTrailingZeros())
994 result = mlir::LLVM::ZeroOp::create(rewriter, parentLoc, llvmTy);
995 else
996 result = mlir::LLVM::UndefOp::create(rewriter, parentLoc, llvmTy);
997
998 // Iteratively lower each constant element of the array.
999 if (auto arrayAttr = mlir::dyn_cast<mlir::ArrayAttr>(attr.getElts())) {
1000 // Fewer struct members than elements: adjustGlobalTypeForInit grouped the
1001 // elements of an array ending in many zeros into one leading array. That
1002 // array has no trailing zeros, so it keeps its type and still lowers as
1003 // one dense constant.
1004 //
1005 // FIXME: A split array itself is a struct, which llvm.mlir.constant cannot
1006 // hold with aggregate fields, so on this path each split array costs
1007 // insertvalue ops. With many split arrays that cannot be folded into an
1008 // enclosing constant, that may be slower than lowering them unsplit as
1009 // dense arrays; consider a heuristic choosing between the two.
1010 auto structTy = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(llvmTy);
1011 if (structTy && structTy.getBody().size() < arrayAttr.size()) {
1012 auto arrayTy = mlir::cast<cir::ArrayType>(attr.getType());
1013 auto prefix = cir::ConstArrayAttr::get(
1014 cir::ArrayType::get(arrayTy.getElementType(), arrayAttr.size()),
1015 arrayAttr);
1016 mlir::Value init = visit(prefix);
1017 if (!init)
1018 return {};
1019 return mlir::LLVM::InsertValueOp::create(
1020 rewriter, parentLoc, result, init, llvm::ArrayRef<int64_t>{0});
1021 }
1022 for (auto [idx, elt] : llvm::enumerate(arrayAttr)) {
1023 mlir::Value init = visit(elt);
1024 if (!init)
1025 return {};
1026 result = mlir::LLVM::InsertValueOp::create(rewriter, parentLoc, result,
1027 init, idx);
1028 }
1029 } else if (auto strAttr = mlir::dyn_cast<mlir::StringAttr>(attr.getElts())) {
1030 // TODO(cir): this diverges from traditional lowering. Normally the string
1031 // would be a global constant that is memcopied.
1032 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(strAttr.getType());
1033 assert(arrayTy && "String attribute must have an array type");
1034 mlir::Type eltTy = arrayTy.getElementType();
1035 for (auto [idx, elt] : llvm::enumerate(strAttr)) {
1036 auto init = mlir::LLVM::ConstantOp::create(
1037 rewriter, parentLoc, converter->convertType(eltTy), elt);
1038 result = mlir::LLVM::InsertValueOp::create(rewriter, parentLoc, result,
1039 init, idx);
1040 }
1041 } else {
1042 llvm_unreachable("unexpected ConstArrayAttr elements");
1043 }
1044
1045 return result;
1046}
1047
1048/// ConstRecord visitor.
1049mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstRecordAttr constRecord) {
1050 mlir::Type llvmTy = converter->convertType(constRecord.getType());
1051 mlir::DataLayout dataLayout(parentModule);
1052 llvm::SmallVector<unsigned> paddingAddedIndexes;
1053 mlir::Type failedType = constRecord.getType();
1054 llvmTy = adjustGlobalTypeForInit(llvmTy, constRecord, *converter, dataLayout,
1055 paddingAddedIndexes, &failedType);
1056 if (!llvmTy) {
1057 emitTypeConversionError(parentLoc, failedType);
1058 return {};
1059 }
1060 mlir::Value result = mlir::LLVM::UndefOp::create(rewriter, parentLoc, llvmTy);
1061
1062 uint64_t insertIdx = 0;
1063 auto paddingItr = paddingAddedIndexes.begin();
1064
1065 // Iteratively lower each constant element of the record. A record member
1066 // that owns no bytes has no LLVM field and takes no element, so the elements
1067 // run one per field.
1068 for (auto [idx, elt] : llvm::enumerate(constRecord.getMembers())) {
1069 if (paddingItr != paddingAddedIndexes.end() && *paddingItr == idx) {
1070 ++insertIdx;
1071 ++paddingItr;
1072 }
1073
1074 mlir::Value init = visit(elt);
1075 if (!init)
1076 return {};
1077 result = mlir::LLVM::InsertValueOp::create(rewriter, parentLoc, result,
1078 init, insertIdx);
1079 ++insertIdx;
1080 }
1081
1082 return result;
1083}
1084
1085/// ConstVectorAttr visitor.
1086mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstVectorAttr attr) {
1087 const mlir::Type llvmTy = converter->convertType(attr.getType());
1088
1089 SmallVector<mlir::Attribute> mlirValues;
1090 for (const mlir::Attribute elementAttr : attr.getElts()) {
1091 mlir::Attribute mlirAttr;
1092 if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(elementAttr)) {
1093 mlirAttr = rewriter.getIntegerAttr(
1094 converter->convertType(intAttr.getType()), intAttr.getValue());
1095 } else if (auto floatAttr = mlir::dyn_cast<cir::FPAttr>(elementAttr)) {
1096 mlirAttr = rewriter.getFloatAttr(
1097 converter->convertType(floatAttr.getType()), floatAttr.getValue());
1098 } else if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(elementAttr)) {
1099 mlirAttr = rewriter.getBoolAttr(boolAttr.getValue());
1100 } else {
1101 llvm_unreachable("vector constant with an element that is neither an "
1102 "int, a float, or a bool");
1103 }
1104 mlirValues.push_back(mlirAttr);
1105 }
1106
1107 return mlir::LLVM::ConstantOp::create(
1108 rewriter, parentLoc, llvmTy,
1109 mlir::DenseElementsAttr::get(mlir::cast<mlir::ShapedType>(llvmTy),
1110 mlirValues));
1111}
1112
1113// GlobalViewAttr / GlobalOffsetAttr visitors.
1114CIRAttrToValue::LoweredGlobalSymbol
1115CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
1116 cir::CIRDataLayout cirDataLayout(parentModule);
1117 const mlir::DataLayout &dataLayout = cirDataLayout.layout;
1118 mlir::Type sourceType;
1119 mlir::Type originalType;
1120 unsigned addrSpace = 0;
1121 llvm::StringRef symName;
1122 mlir::Operation *sourceSymbol =
1123 symbolTables.lookupSymbolIn(parentModule, symbol);
1124 if (auto llvmSymbol = dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
1125 if (mlir::Type preType =
1126 preConversionTypes.lookup(llvmSymbol.getSymName())) {
1127 originalType = preType;
1128 sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
1129 } else {
1130 sourceType = llvmSymbol.getType();
1131 }
1132 symName = llvmSymbol.getSymName();
1133 addrSpace = llvmSymbol.getAddrSpace();
1134 } else if (auto cirSymbol = dyn_cast<cir::GlobalOp>(sourceSymbol)) {
1135 originalType = cirSymbol.getSymType();
1136 sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
1137 symName = cirSymbol.getSymName();
1138 if (auto targetAS = mlir::dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
1139 cirSymbol.getAddrSpaceAttr()))
1140 addrSpace = targetAS.getValue();
1141 } else if (auto llvmFun = dyn_cast<mlir::LLVM::LLVMFuncOp>(sourceSymbol)) {
1142 if (mlir::Type preType = preConversionTypes.lookup(llvmFun.getSymName())) {
1143 originalType = preType;
1144 sourceType = converter->convertType(originalType);
1145 } else {
1146 sourceType = llvmFun.getFunctionType();
1147 }
1148 symName = llvmFun.getSymName();
1149 addrSpace = cirDataLayout.getProgramAddressSpace();
1150 } else if (auto fun = dyn_cast<cir::FuncOp>(sourceSymbol)) {
1151 originalType = fun.getFunctionType();
1152 sourceType = converter->convertType(originalType);
1153 symName = fun.getSymName();
1154 addrSpace = cirDataLayout.getProgramAddressSpace();
1155 } else if (auto alias = dyn_cast<mlir::LLVM::AliasOp>(sourceSymbol)) {
1156 if (mlir::Type preType = preConversionTypes.lookup(alias.getSymName())) {
1157 originalType = preType;
1158 if (mlir::isa<cir::FuncType>(preType))
1159 sourceType = converter->convertType(originalType);
1160 else
1161 sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
1162 } else {
1163 sourceType = alias.getType();
1164 }
1165 symName = alias.getSymName();
1166 addrSpace = alias.getAddrSpace();
1167 } else {
1168 llvm_unreachable("Unexpected GlobalOp type");
1169 }
1170
1171 mlir::Value addr = mlir::LLVM::AddressOfOp::create(
1172 rewriter, parentLoc,
1173 mlir::LLVM::LLVMPointerType::get(rewriter.getContext(), addrSpace),
1174 symName);
1175 return {addr, sourceType, originalType, addrSpace};
1176}
1177
1178mlir::Value CIRAttrToValue::castGlobalAddrToType(mlir::Value addr,
1179 mlir::Type attrType,
1180 mlir::Type sourceType,
1181 unsigned addrSpace) {
1182
1183 // We can have a global view with an integer type in the case of method
1184 // pointers. With the Itanium ABI, the #cir.method attribute is lowered to a
1185 // #cir.global_view with a pointer-sized integer representing the address of
1186 // the method.
1187 if (mlir::isa<cir::IntType>(attrType)) {
1188 mlir::Type llvmDstTy = converter->convertType(attrType);
1189 return mlir::LLVM::PtrToIntOp::create(rewriter, parentLoc, llvmDstTy, addr);
1190 }
1191
1192 if (auto ptrTy = mlir::dyn_cast<cir::PointerType>(attrType)) {
1193 auto llvmDstTy = converter->convertType<mlir::LLVM::LLVMPointerType>(ptrTy);
1194
1195 if (llvmDstTy.getAddressSpace() != addrSpace)
1196 addr = mlir::LLVM::AddrSpaceCastOp::create(rewriter, parentLoc, llvmDstTy,
1197 addr);
1198
1199 mlir::DataLayout dataLayout(parentModule);
1200 mlir::Type llvmEltTy =
1201 convertTypeForMemory(*converter, dataLayout, ptrTy.getPointee());
1202
1203 // No further cast needed if the pointee type already matches.
1204 if (llvmEltTy == sourceType)
1205 return addr;
1206
1207 // With opaque pointers, the pointer type is already correct (either from
1208 // the original AddressOfOp or after an addrspacecast) — skip the
1209 // redundant bitcast.
1210 if (addr.getType() == llvmDstTy)
1211 return addr;
1212
1213 return mlir::LLVM::BitcastOp::create(rewriter, parentLoc, llvmDstTy, addr);
1214 }
1215
1216 if (mlir::isa<cir::VPtrType>(attrType))
1217 return addr;
1218
1219 llvm_unreachable("Expecting pointer or integer type");
1220}
1221
1222mlir::Value CIRAttrToValue::visitCirAttr(cir::GlobalViewAttr globalAttr) {
1223 LoweredGlobalSymbol lowered = getAddressOfSymbol(globalAttr.getSymbol());
1224 mlir::Value addrOp = lowered.addr;
1225 mlir::Type sourceType = lowered.sourceType;
1226
1227 if (globalAttr.getIndices()) {
1228 if (!sourceType) {
1229 emitTypeConversionError(parentLoc, lowered.originalType)
1230 << " for symbol " << globalAttr.getSymbol();
1231 return {};
1232 }
1233 llvm::SmallVector<mlir::LLVM::GEPArg> indices;
1234
1235 if (mlir::isa<mlir::LLVM::LLVMArrayType, mlir::LLVM::LLVMStructType>(
1236 sourceType))
1237 indices.push_back(0);
1238
1239 for (mlir::Attribute idx : globalAttr.getIndices()) {
1240 auto intAttr = mlir::cast<mlir::IntegerAttr>(idx);
1241 indices.push_back(intAttr.getValue().getSExtValue());
1242 }
1243 mlir::Type resTy = addrOp.getType();
1244 mlir::Type eltTy = converter->convertType(sourceType);
1245 auto gep =
1246 mlir::LLVM::GEPOp::create(rewriter, parentLoc, resTy, eltTy, addrOp,
1247 indices, mlir::LLVM::GEPNoWrapFlags::none);
1248 if (globalAttr.getAddressPoint()) {
1250 if (usesRelativeVTables(parentModule)) {
1251 mlir::emitError(parentLoc)
1252 << "NYI: address point of a relative layout vtable";
1253 return {};
1254 }
1255
1256 // Like classic codegen, a vtable address point is inbounds, and only the
1257 // one vtable of the group it points into can be accessed through it.
1258 auto indices =
1259 globalAttr.getIndices().getAsValueRange<mlir::IntegerAttr>();
1260 assert(llvm::range_size(indices) == 2 &&
1261 "address point takes a vtable index and a slot index");
1262 auto vtableTy = mlir::cast<mlir::LLVM::LLVMArrayType>(
1263 mlir::cast<mlir::LLVM::LLVMStructType>(eltTy)
1264 .getBody()[(*indices.begin()).getZExtValue()]);
1265 mlir::DataLayout layout(parentModule);
1266 int64_t slotSize = layout.getTypeSize(vtableTy.getElementType());
1267 int64_t offset = (*std::next(indices.begin())).getSExtValue() * slotSize;
1268 int64_t size = vtableTy.getNumElements() * slotSize;
1269 unsigned indexBits = *layout.getTypeIndexBitwidth(
1270 mlir::cast<mlir::LLVM::LLVMPointerType>(addrOp.getType()));
1271 gep.setNoWrapFlags(mlir::LLVM::GEPNoWrapFlags::inbounds);
1272
1273 gep.setInrangeAttr(mlir::LLVM::ConstantRangeAttr::get(
1274 rewriter.getContext(),
1275 llvm::APInt(indexBits, -offset, /*isSigned=*/true),
1276 llvm::APInt(indexBits, size - offset, /*isSigned=*/true)));
1277 }
1278 addrOp = gep;
1279 }
1280
1281 return castGlobalAddrToType(addrOp, globalAttr.getType(), sourceType,
1282 lowered.addrSpace);
1283}
1284
1285mlir::Value CIRAttrToValue::visitCirAttr(cir::GlobalOffsetAttr globalAttr) {
1286 LoweredGlobalSymbol lowered = getAddressOfSymbol(globalAttr.getSymbol());
1287 mlir::Value addrOp = lowered.addr;
1288
1289 // A displacement in bytes is a GEP through i8, which is what classic
1290 // codegen emits for the offset of any constant lvalue.
1291 mlir::Value offset = mlir::LLVM::ConstantOp::create(
1292 rewriter, parentLoc, rewriter.getI64Type(),
1293 rewriter.getI64IntegerAttr(globalAttr.getOffset()));
1294 addrOp = mlir::LLVM::GEPOp::create(
1295 rewriter, parentLoc, addrOp.getType(), rewriter.getI8Type(), addrOp,
1296 mlir::ValueRange{offset}, mlir::LLVM::GEPNoWrapFlags::none);
1297
1298 return castGlobalAddrToType(addrOp, globalAttr.getType(), lowered.sourceType,
1299 lowered.addrSpace);
1300}
1301
1302// TypeInfoAttr visitor.
1303mlir::Value CIRAttrToValue::visitCirAttr(cir::TypeInfoAttr typeInfoAttr) {
1304 mlir::Type llvmTy = converter->convertType(typeInfoAttr.getType());
1305 mlir::Value result = mlir::LLVM::UndefOp::create(rewriter, parentLoc, llvmTy);
1306
1307 for (auto [idx, elt] : llvm::enumerate(typeInfoAttr.getData())) {
1308 mlir::Value init = visit(elt);
1309 if (!init)
1310 return {};
1311 result = mlir::LLVM::InsertValueOp::create(rewriter, parentLoc, result,
1312 init, idx);
1313 }
1314
1315 return result;
1316}
1317
1318/// UndefAttr visitor.
1319mlir::Value CIRAttrToValue::visitCirAttr(cir::UndefAttr undefAttr) {
1320 mlir::DataLayout layout(parentModule);
1321 return mlir::LLVM::UndefOp::create(
1322 rewriter, parentLoc,
1323 convertTypeForMemory(*converter, layout, undefAttr.getType()));
1324}
1325
1326/// PoisonAttr visitor.
1327mlir::Value CIRAttrToValue::visitCirAttr(cir::PoisonAttr poisonAttr) {
1328 mlir::DataLayout layout(parentModule);
1329 return mlir::LLVM::PoisonOp::create(
1330 rewriter, parentLoc,
1331 convertTypeForMemory(*converter, layout, poisonAttr.getType()));
1332}
1333
1334// VTableAttr visitor.
1335mlir::Value CIRAttrToValue::visitCirAttr(cir::VTableAttr vtableArr) {
1337 if (usesRelativeVTables(parentModule)) {
1338 mlir::emitError(parentLoc)
1339 << "NYI: initializer of a relative layout vtable";
1340 return {};
1341 }
1342
1343 mlir::Type llvmTy = converter->convertType(vtableArr.getType());
1344 mlir::Value result = mlir::LLVM::UndefOp::create(rewriter, parentLoc, llvmTy);
1345
1346 for (auto [idx, elt] : llvm::enumerate(vtableArr.getData())) {
1347 mlir::Value init = visit(elt);
1348 if (!init)
1349 return {};
1350 result = mlir::LLVM::InsertValueOp::create(rewriter, parentLoc, result,
1351 init, idx);
1352 }
1353
1354 return result;
1355}
1356
1357/// ZeroAttr visitor.
1358mlir::Value CIRAttrToValue::visitCirAttr(cir::ZeroAttr attr) {
1359 mlir::DataLayout layout(parentModule);
1360 return mlir::LLVM::ZeroOp::create(
1361 rewriter, parentLoc,
1362 convertTypeForMemory(*converter, layout, attr.getType()));
1363}
1364
1365// This class handles rewriting initializer attributes for types that do not
1366// require region initialization.
1368public:
1369 GlobalInitAttrRewriter(mlir::Type type, mlir::DataLayout const &dataLayout,
1370 mlir::ConversionPatternRewriter &rewriter)
1371 : llvmType(type), dataLayout(dataLayout), rewriter(rewriter) {}
1372
1373 mlir::Attribute visit(mlir::Attribute attr) {
1374 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
1375 .Case<cir::IntAttr, cir::FPAttr, cir::BoolAttr>(
1376 [&](auto attrT) { return visitCirAttr(attrT); })
1377 .Default([&](auto attrT) { return mlir::Attribute(); });
1378 }
1379
1380 mlir::Attribute visitCirAttr(cir::IntAttr attr) {
1381 // A split-storage _BitInt's memory representation is a byte array (see
1382 // convertTypeForMemory), not a scalar, so its constant must be built as
1383 // raw bytes rather than a single sign/zero-extended IntegerAttr.
1384 if (cir::isBitIntType(attr.getType()))
1385 return getBitIntStorageAttr(rewriter, attr, dataLayout);
1386
1387 return rewriter.getIntegerAttr(llvmType, attr.getValue());
1388 }
1389
1390 mlir::Attribute visitCirAttr(cir::FPAttr attr) {
1391 return rewriter.getFloatAttr(llvmType, attr.getValue());
1392 }
1393
1394 mlir::Attribute visitCirAttr(cir::BoolAttr attr) {
1395 return rewriter.getBoolAttr(attr.getValue());
1396 }
1397
1398private:
1399 mlir::Type llvmType;
1400 const mlir::DataLayout &dataLayout;
1401 mlir::ConversionPatternRewriter &rewriter;
1402};
1403
1404// This pass requires the CIR to be in a "flat" state. All blocks in each
1405// function must belong to the parent region. Once scopes and control flow
1406// are implemented in CIR, a pass will be run before this one to flatten
1407// the CIR and get it into the state that this pass requires.
1409 : public mlir::PassWrapper<ConvertCIRToLLVMPass,
1410 mlir::OperationPass<mlir::ModuleOp>> {
1411 void getDependentDialects(mlir::DialectRegistry &registry) const override {
1412 registry.insert<mlir::BuiltinDialect, mlir::DLTIDialect,
1413 mlir::LLVM::LLVMDialect, mlir::func::FuncDialect>();
1414 }
1415 void runOnOperation() final;
1416
1417 void processCIRAttrs(mlir::ModuleOp module);
1418
1419 void resolveBlockAddressOp(LLVMBlockAddressInfo &blockInfoAddr);
1420
1421 /// Collect (symbol_name, annotations, loc) from cir.func and cir.global ops
1422 /// before the conversion runs (the annotations attribute is dropped during
1423 /// FuncOp/GlobalOp lowering).
1424 void collectGlobalAnnotations(mlir::ModuleOp module);
1425
1426 /// Emit @llvm.global.annotations and supporting string/args constants from
1427 /// the previously-collected annotations. Mirrors what OGCG produces.
1428 void buildGlobalAnnotationsVar(mlir::ModuleOp module,
1429 LLVMAnnotationGlobals &annotationGlobals);
1430
1431 StringRef getDescription() const override {
1432 return "Convert the prepared CIR dialect module to LLVM dialect";
1433 }
1434
1435 StringRef getArgument() const override { return "cir-flat-to-llvm"; }
1436
1437private:
1438 /// One annotation entry collected pre-conversion.
1439 struct CollectedAnnotation {
1440 mlir::StringAttr symName;
1441 cir::AnnotationAttr annotation;
1442 mlir::Location loc;
1443 CollectedAnnotation(mlir::StringAttr symName,
1444 cir::AnnotationAttr annotation, mlir::Location loc)
1445 : symName(symName), annotation(annotation), loc(loc) {}
1446 };
1447 llvm::SmallVector<CollectedAnnotation> collectedAnnotations;
1448};
1449
1450mlir::LogicalResult CIRToLLVMSignBitOpLowering::matchAndRewrite(
1451 cir::SignBitOp op, OpAdaptor adaptor,
1452 mlir::ConversionPatternRewriter &rewriter) const {
1454
1455 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
1456 int width = layout.getTypeSizeInBits(op.getInput().getType());
1457 if (auto longDoubleType =
1458 mlir::dyn_cast<cir::LongDoubleType>(op.getInput().getType())) {
1459 if (mlir::isa<cir::FP80Type>(longDoubleType.getUnderlying())) {
1460 // If the underlying type of LongDouble is FP80Type,
1461 // DataLayout::getTypeSizeInBits returns 128.
1462 // See https://github.com/llvm/clangir/issues/1057.
1463 // Set the width to 80 manually.
1464 width = 80;
1465 }
1466 }
1467 mlir::Type intTy = mlir::IntegerType::get(rewriter.getContext(), width);
1468 auto bitcast = mlir::LLVM::BitcastOp::create(rewriter, op->getLoc(), intTy,
1469 adaptor.getInput());
1470
1471 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op->getLoc(), intTy, 0);
1472 auto cmpResult = mlir::LLVM::ICmpOp::create(rewriter, op.getLoc(),
1473 mlir::LLVM::ICmpPredicate::slt,
1474 bitcast.getResult(), zero);
1475 rewriter.replaceOp(op, cmpResult);
1476 return mlir::success();
1477}
1478
1479mlir::LogicalResult CIRToLLVMAssumeOpLowering::matchAndRewrite(
1480 cir::AssumeOp op, OpAdaptor adaptor,
1481 mlir::ConversionPatternRewriter &rewriter) const {
1482 mlir::Value cond = adaptor.getPredicate();
1483 if (op.getBundleKind() == cir::AssumeBundleKind::None) {
1484 rewriter.replaceOpWithNewOp<mlir::LLVM::AssumeOp>(op, cond);
1485 return mlir::success();
1486 }
1487
1488 llvm::StringRef tag = cir::stringifyAssumeBundleKind(op.getBundleKind());
1489 rewriter.replaceOpWithNewOp<mlir::LLVM::AssumeOp>(op, cond, tag,
1490 adaptor.getBundleArgs());
1491 return mlir::success();
1492}
1493
1494static mlir::LLVM::AtomicOrdering
1495getLLVMMemOrder(std::optional<cir::MemOrder> memorder) {
1496 if (!memorder)
1497 return mlir::LLVM::AtomicOrdering::not_atomic;
1498 switch (*memorder) {
1499 case cir::MemOrder::Relaxed:
1500 return mlir::LLVM::AtomicOrdering::monotonic;
1501 case cir::MemOrder::Consume:
1502 case cir::MemOrder::Acquire:
1503 return mlir::LLVM::AtomicOrdering::acquire;
1504 case cir::MemOrder::Release:
1505 return mlir::LLVM::AtomicOrdering::release;
1506 case cir::MemOrder::AcquireRelease:
1507 return mlir::LLVM::AtomicOrdering::acq_rel;
1508 case cir::MemOrder::SequentiallyConsistent:
1509 return mlir::LLVM::AtomicOrdering::seq_cst;
1510 }
1511 llvm_unreachable("unknown memory order");
1512}
1513
1514static llvm::AtomicScope getAtomicScope(cir::SyncScopeKind syncScope) {
1515 switch (syncScope) {
1516 case cir::SyncScopeKind::SingleThread:
1517 case cir::SyncScopeKind::HIPSingleThread:
1518 return llvm::AtomicScope::Single;
1519 case cir::SyncScopeKind::Wavefront:
1520 case cir::SyncScopeKind::HIPWavefront:
1521 case cir::SyncScopeKind::OpenCLSubGroup:
1522 return llvm::AtomicScope::Wavefront;
1523 case cir::SyncScopeKind::Workgroup:
1524 case cir::SyncScopeKind::HIPWorkgroup:
1525 case cir::SyncScopeKind::OpenCLWorkGroup:
1526 return llvm::AtomicScope::Workgroup;
1527 case cir::SyncScopeKind::Cluster:
1528 case cir::SyncScopeKind::HIPCluster:
1529 return llvm::AtomicScope::Cluster;
1530 case cir::SyncScopeKind::Device:
1531 case cir::SyncScopeKind::HIPAgent:
1532 case cir::SyncScopeKind::OpenCLDevice:
1533 return llvm::AtomicScope::Device;
1534 case cir::SyncScopeKind::System:
1535 case cir::SyncScopeKind::HIPSystem:
1536 case cir::SyncScopeKind::OpenCLAllSVMDevices:
1537 return llvm::AtomicScope::System;
1538 }
1539 llvm_unreachable("unknown sync scope");
1540}
1541
1542static llvm::StringRef getLLVMSyncScope(cir::SyncScopeKind syncScope,
1543 mlir::ModuleOp moduleOp) {
1544 llvm::AtomicScope scope = getAtomicScope(syncScope);
1545 if (auto triple = moduleOp->getAttrOfType<mlir::StringAttr>(
1546 cir::CIRDialect::getTripleAttrName()))
1547 if (std::optional<llvm::StringRef> name = llvm::getAtomicScopeIRString(
1548 llvm::Triple(triple.getValue()), scope))
1549 return *name;
1550 return scope == llvm::AtomicScope::Single ? "singlethread" : "";
1551}
1552
1553static std::optional<llvm::StringRef>
1554getLLVMSyncScope(std::optional<cir::SyncScopeKind> syncScope,
1555 mlir::ModuleOp moduleOp) {
1556 if (syncScope.has_value())
1557 return getLLVMSyncScope(*syncScope, moduleOp);
1558 return std::nullopt;
1559}
1560
1561static void forwardAMDGPUNoPrivateAddrSpace(mlir::Operation *op,
1562 mlir::Operation *llvmOp,
1563 mlir::Value llvmPtr) {
1564 llvm::StringRef name = cir::CIRDialect::getAMDGPUNoPrivateAddrSpaceAttrName();
1565 auto ptrTy = mlir::cast<mlir::LLVM::LLVMPointerType>(llvmPtr.getType());
1566 mlir::Attribute a = op->getAttr(name);
1567 if (a && ptrTy.getAddressSpace() == llvm::AMDGPUAS::FLAT_ADDRESS)
1568 llvmOp->setAttr(name, a);
1569}
1570
1571// CIRGen decides the metadata for a C++/HIP atomic from the atomic options
1572// in effect, so those markers are simply carried across.
1573static void forwardAMDGPUAtomicOptionMarkers(mlir::Operation *op,
1574 mlir::Operation *llvmOp) {
1575 for (llvm::StringRef marker :
1576 {cir::CIRDialect::getAMDGPUNoFineGrainedMemoryAttrName(),
1577 cir::CIRDialect::getAMDGPUNoRemoteMemoryAttrName(),
1578 cir::CIRDialect::getAMDGPUIgnoreDenormalModeAttrName()})
1579 if (mlir::Attribute a = op->getAttr(marker))
1580 llvmOp->setAttr(marker, a);
1581}
1582
1583mlir::LogicalResult CIRToLLVMAtomicCmpXchgOpLowering::matchAndRewrite(
1584 cir::AtomicCmpXchgOp op, OpAdaptor adaptor,
1585 mlir::ConversionPatternRewriter &rewriter) const {
1586 mlir::Value expected = adaptor.getExpected();
1587 mlir::Value desired = adaptor.getDesired();
1588
1589 auto cmpxchg = mlir::LLVM::AtomicCmpXchgOp::create(
1590 rewriter, op.getLoc(), adaptor.getPtr(), expected, desired,
1591 getLLVMMemOrder(adaptor.getSuccOrder()),
1592 getLLVMMemOrder(adaptor.getFailOrder()),
1593 getLLVMSyncScope(op.getSyncScope(),
1594 op->getParentOfType<mlir::ModuleOp>()));
1595
1596 cmpxchg.setAlignment(adaptor.getAlignment());
1597 cmpxchg.setWeak(adaptor.getWeak());
1598 cmpxchg.setVolatile_(adaptor.getIsVolatile());
1599 forwardAMDGPUNoPrivateAddrSpace(op, cmpxchg, adaptor.getPtr());
1600
1601 // Check result and apply stores accordingly.
1602 auto old = mlir::LLVM::ExtractValueOp::create(rewriter, op.getLoc(),
1603 cmpxchg.getResult(), 0);
1604 auto cmp = mlir::LLVM::ExtractValueOp::create(rewriter, op.getLoc(),
1605 cmpxchg.getResult(), 1);
1606
1607 rewriter.replaceOp(op, {old, cmp});
1608 return mlir::success();
1609}
1610
1611mlir::LogicalResult CIRToLLVMAtomicXchgOpLowering::matchAndRewrite(
1612 cir::AtomicXchgOp op, OpAdaptor adaptor,
1613 mlir::ConversionPatternRewriter &rewriter) const {
1615 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(adaptor.getMemOrder());
1616 llvm::StringRef llvmSyncScope = getLLVMSyncScope(
1617 op.getSyncScope(), op->getParentOfType<mlir::ModuleOp>());
1618 // Create the new op first: the forward helpers read `op`, which the
1619 // replace below erases immediately.
1620 auto xchg = mlir::LLVM::AtomicRMWOp::create(
1621 rewriter, op.getLoc(), mlir::LLVM::AtomicBinOp::xchg, adaptor.getPtr(),
1622 adaptor.getVal(), llvmOrder, llvmSyncScope,
1623 adaptor.getAlignment().value_or(0), op.getIsVolatile());
1625 forwardAMDGPUNoPrivateAddrSpace(op, xchg, adaptor.getPtr());
1626 rewriter.replaceOp(op, xchg);
1627 return mlir::success();
1628}
1629
1630mlir::LogicalResult CIRToLLVMAtomicTestAndSetOpLowering::matchAndRewrite(
1631 cir::AtomicTestAndSetOp op, OpAdaptor adaptor,
1632 mlir::ConversionPatternRewriter &rewriter) const {
1634
1635 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
1636
1637 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1638 rewriter.getI8Type(), 1);
1639 auto rmw = mlir::LLVM::AtomicRMWOp::create(
1640 rewriter, op.getLoc(), mlir::LLVM::AtomicBinOp::xchg, adaptor.getPtr(),
1641 one, llvmOrder, /*syncscope=*/llvm::StringRef(),
1642 adaptor.getAlignment().value_or(0), op.getIsVolatile());
1643
1644 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1645 rewriter.getI8Type(), 0);
1646 auto cmp = mlir::LLVM::ICmpOp::create(
1647 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::ne, rmw, zero);
1648
1649 rewriter.replaceOp(op, cmp);
1650 return mlir::success();
1651}
1652
1653mlir::LogicalResult CIRToLLVMAtomicClearOpLowering::matchAndRewrite(
1654 cir::AtomicClearOp op, OpAdaptor adaptor,
1655 mlir::ConversionPatternRewriter &rewriter) const {
1657
1658 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
1659 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1660 rewriter.getI8Type(), 0);
1661 auto store = mlir::LLVM::StoreOp::create(
1662 rewriter, op.getLoc(), zero, adaptor.getPtr(),
1663 adaptor.getAlignment().value_or(0), op.getIsVolatile(),
1664 /*isNonTemporal=*/false, /*isInvariantGroup=*/false, llvmOrder);
1665
1666 rewriter.replaceOp(op, store);
1667 return mlir::success();
1668}
1669
1670mlir::LogicalResult CIRToLLVMAtomicFenceOpLowering::matchAndRewrite(
1671 cir::AtomicFenceOp op, OpAdaptor adaptor,
1672 mlir::ConversionPatternRewriter &rewriter) const {
1673 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(adaptor.getOrdering());
1674
1675 auto fence = mlir::LLVM::FenceOp::create(rewriter, op.getLoc(), llvmOrder);
1676 fence.setSyncscope(getLLVMSyncScope(op.getSyncscope(),
1677 op->getParentOfType<mlir::ModuleOp>()));
1678 if (mlir::Attribute mmra =
1679 op->getAttr(mlir::LLVM::LLVMDialect::getMmraAttrName()))
1680 fence->setAttr(mlir::LLVM::LLVMDialect::getMmraAttrName(), mmra);
1681
1682 rewriter.replaceOp(op, fence);
1683
1684 return mlir::success();
1685}
1686
1687static mlir::LLVM::AtomicBinOp
1688getLLVMAtomicBinOp(cir::AtomicFetchKind k, bool isInt, bool isSignedInt) {
1689 switch (k) {
1690 case cir::AtomicFetchKind::Add:
1691 return isInt ? mlir::LLVM::AtomicBinOp::add : mlir::LLVM::AtomicBinOp::fadd;
1692 case cir::AtomicFetchKind::Sub:
1693 return isInt ? mlir::LLVM::AtomicBinOp::sub : mlir::LLVM::AtomicBinOp::fsub;
1694 case cir::AtomicFetchKind::And:
1695 return mlir::LLVM::AtomicBinOp::_and;
1696 case cir::AtomicFetchKind::Xor:
1697 return mlir::LLVM::AtomicBinOp::_xor;
1698 case cir::AtomicFetchKind::Or:
1699 return mlir::LLVM::AtomicBinOp::_or;
1700 case cir::AtomicFetchKind::Nand:
1701 return mlir::LLVM::AtomicBinOp::nand;
1702 case cir::AtomicFetchKind::Max: {
1703 if (!isInt)
1704 return mlir::LLVM::AtomicBinOp::fmax;
1705 return isSignedInt ? mlir::LLVM::AtomicBinOp::max
1706 : mlir::LLVM::AtomicBinOp::umax;
1707 }
1708 case cir::AtomicFetchKind::Min: {
1709 if (!isInt)
1710 return mlir::LLVM::AtomicBinOp::fmin;
1711 return isSignedInt ? mlir::LLVM::AtomicBinOp::min
1712 : mlir::LLVM::AtomicBinOp::umin;
1713 }
1714 case cir::AtomicFetchKind::UIncWrap:
1715 return mlir::LLVM::AtomicBinOp::uinc_wrap;
1716 case cir::AtomicFetchKind::UDecWrap:
1717 return mlir::LLVM::AtomicBinOp::udec_wrap;
1718 case cir::AtomicFetchKind::Maximum:
1719 return mlir::LLVM::AtomicBinOp::fmaximum;
1720 case cir::AtomicFetchKind::Minimum:
1721 return mlir::LLVM::AtomicBinOp::fminimum;
1722 case cir::AtomicFetchKind::MaximumNum:
1723 return mlir::LLVM::AtomicBinOp::fmaximumnum;
1724 case cir::AtomicFetchKind::MinimumNum:
1725 return mlir::LLVM::AtomicBinOp::fminimumnum;
1726 }
1727 llvm_unreachable("Unknown atomic fetch opcode");
1728}
1729
1730static llvm::StringLiteral getLLVMBinopForPostAtomic(cir::AtomicFetchKind k,
1731 bool isInt) {
1732 switch (k) {
1733 case cir::AtomicFetchKind::Add:
1734 return isInt ? mlir::LLVM::AddOp::getOperationName()
1735 : mlir::LLVM::FAddOp::getOperationName();
1736 case cir::AtomicFetchKind::Sub:
1737 return isInt ? mlir::LLVM::SubOp::getOperationName()
1738 : mlir::LLVM::FSubOp::getOperationName();
1739 case cir::AtomicFetchKind::And:
1740 return mlir::LLVM::AndOp::getOperationName();
1741 case cir::AtomicFetchKind::Xor:
1742 return mlir::LLVM::XOrOp::getOperationName();
1743 case cir::AtomicFetchKind::Or:
1744 return mlir::LLVM::OrOp::getOperationName();
1745 case cir::AtomicFetchKind::Nand:
1746 // There's no nand binop in LLVM, this is later fixed with a not.
1747 return mlir::LLVM::AndOp::getOperationName();
1748 case cir::AtomicFetchKind::Max:
1749 case cir::AtomicFetchKind::Min:
1750 llvm_unreachable("handled in buildMinMaxPostOp");
1751 case cir::AtomicFetchKind::UIncWrap:
1752 case cir::AtomicFetchKind::UDecWrap:
1753 case cir::AtomicFetchKind::Maximum:
1754 case cir::AtomicFetchKind::Minimum:
1755 case cir::AtomicFetchKind::MaximumNum:
1756 case cir::AtomicFetchKind::MinimumNum:
1757 llvm_unreachable("uinc_wrap, udec_wrap, maximum, minimum, maximum_num, and "
1758 "minimum_num are always fetch_first");
1759 }
1760 llvm_unreachable("Unknown atomic fetch opcode");
1761}
1762
1763mlir::Value CIRToLLVMAtomicFetchOpLowering::buildPostOp(
1764 cir::AtomicFetchOp op, OpAdaptor adaptor,
1765 mlir::ConversionPatternRewriter &rewriter, mlir::Value rmwVal,
1766 bool isInt) const {
1767 SmallVector<mlir::Value> atomicOperands = {rmwVal, adaptor.getVal()};
1768 SmallVector<mlir::Type> atomicResTys = {rmwVal.getType()};
1769 return rewriter
1770 .create(op.getLoc(),
1771 rewriter.getStringAttr(
1772 getLLVMBinopForPostAtomic(op.getBinop(), isInt)),
1773 atomicOperands, atomicResTys, {})
1774 ->getResult(0);
1775}
1776
1777mlir::Value CIRToLLVMAtomicFetchOpLowering::buildMinMaxPostOp(
1778 cir::AtomicFetchOp op, OpAdaptor adaptor,
1779 mlir::ConversionPatternRewriter &rewriter, mlir::Value rmwVal, bool isInt,
1780 bool isSigned) const {
1781 mlir::Location loc = op.getLoc();
1782
1783 if (!isInt) {
1784 if (op.getBinop() == cir::AtomicFetchKind::Max)
1785 return mlir::LLVM::MaxNumOp::create(rewriter, loc, rmwVal,
1786 adaptor.getVal());
1787 return mlir::LLVM::MinNumOp::create(rewriter, loc, rmwVal,
1788 adaptor.getVal());
1789 }
1790
1791 mlir::LLVM::ICmpPredicate pred;
1792 if (op.getBinop() == cir::AtomicFetchKind::Max) {
1793 pred = isSigned ? mlir::LLVM::ICmpPredicate::sgt
1794 : mlir::LLVM::ICmpPredicate::ugt;
1795 } else { // Min
1796 pred = isSigned ? mlir::LLVM::ICmpPredicate::slt
1797 : mlir::LLVM::ICmpPredicate::ult;
1798 }
1799 mlir::Value cmp = mlir::LLVM::ICmpOp::create(
1800 rewriter, loc,
1801 mlir::LLVM::ICmpPredicateAttr::get(rewriter.getContext(), pred), rmwVal,
1802 adaptor.getVal());
1803 return mlir::LLVM::SelectOp::create(rewriter, loc, cmp, rmwVal,
1804 adaptor.getVal());
1805}
1806
1807mlir::LogicalResult CIRToLLVMAtomicFetchOpLowering::matchAndRewrite(
1808 cir::AtomicFetchOp op, OpAdaptor adaptor,
1809 mlir::ConversionPatternRewriter &rewriter) const {
1810 bool isInt = false;
1811 bool isSignedInt = false;
1812 if (auto intTy = mlir::dyn_cast<cir::IntType>(op.getVal().getType())) {
1813 isInt = true;
1814 isSignedInt = intTy.isSigned();
1815 } else if (cir::isFPOrVectorOfFPType(op.getVal().getType())) {
1816 isInt = false;
1817 } else {
1818 return op.emitError() << "Unsupported type: " << op.getVal().getType();
1819 }
1820
1821 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
1822 llvm::StringRef llvmSyncScope = getLLVMSyncScope(
1823 op.getSyncScope(), op->getParentOfType<mlir::ModuleOp>());
1824 mlir::LLVM::AtomicBinOp llvmBinOp =
1825 getLLVMAtomicBinOp(op.getBinop(), isInt, isSignedInt);
1826 auto rmwVal = mlir::LLVM::AtomicRMWOp::create(
1827 rewriter, op.getLoc(), llvmBinOp, adaptor.getPtr(), adaptor.getVal(),
1828 llvmOrder, llvmSyncScope, adaptor.getAlignment().value_or(0),
1829 op.getIsVolatile());
1830
1832 forwardAMDGPUNoPrivateAddrSpace(op, rmwVal, adaptor.getPtr());
1833
1834 // The AMDGPU raw hardware atomic builtins need metadata for the backend to
1835 // select the native instruction. LDS atomics are always native, so the
1836 // metadata is only needed for the global and flat address spaces.
1837 if (op->hasAttr(cir::CIRDialect::getAMDGPURawAtomicAttrName())) {
1838 auto ptrTy =
1839 mlir::cast<mlir::LLVM::LLVMPointerType>(adaptor.getPtr().getType());
1840 if (ptrTy.getAddressSpace() != llvm::AMDGPUAS::LOCAL_ADDRESS) {
1841 mlir::UnitAttr unit = rewriter.getUnitAttr();
1842 rmwVal->setAttr(cir::CIRDialect::getAMDGPUNoFineGrainedMemoryAttrName(),
1843 unit);
1844 // Denormal flushing only matters for a float add.
1845 if (llvmBinOp == mlir::LLVM::AtomicBinOp::fadd &&
1846 mlir::isa<cir::SingleType>(op.getVal().getType()))
1847 rmwVal->setAttr(cir::CIRDialect::getAMDGPUIgnoreDenormalModeAttrName(),
1848 unit);
1849 }
1850 }
1851
1852 mlir::Value result = rmwVal.getResult();
1853 if (!op.getFetchFirst()) {
1854 if (op.getBinop() == cir::AtomicFetchKind::Max ||
1855 op.getBinop() == cir::AtomicFetchKind::Min)
1856 result = buildMinMaxPostOp(op, adaptor, rewriter, rmwVal.getRes(), isInt,
1857 isSignedInt);
1858 else
1859 result = buildPostOp(op, adaptor, rewriter, rmwVal.getRes(), isInt);
1860
1861 // Compensate lack of nand binop in LLVM IR.
1862 if (op.getBinop() == cir::AtomicFetchKind::Nand) {
1863 auto negOne = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1864 result.getType(), -1);
1865 result = mlir::LLVM::XOrOp::create(rewriter, op.getLoc(), result, negOne);
1866 }
1867 }
1868
1869 rewriter.replaceOp(op, result);
1870 return mlir::success();
1871}
1872
1873mlir::LogicalResult CIRToLLVMBitClrsbOpLowering::matchAndRewrite(
1874 cir::BitClrsbOp op, OpAdaptor adaptor,
1875 mlir::ConversionPatternRewriter &rewriter) const {
1876 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1877 adaptor.getInput().getType(), 0);
1878 auto isNeg = mlir::LLVM::ICmpOp::create(
1879 rewriter, op.getLoc(),
1880 mlir::LLVM::ICmpPredicateAttr::get(rewriter.getContext(),
1881 mlir::LLVM::ICmpPredicate::slt),
1882 adaptor.getInput(), zero);
1883
1884 auto negOne = mlir::LLVM::ConstantOp::create(
1885 rewriter, op.getLoc(), adaptor.getInput().getType(), -1);
1886 auto flipped = mlir::LLVM::XOrOp::create(rewriter, op.getLoc(),
1887 adaptor.getInput(), negOne);
1888
1889 auto select = mlir::LLVM::SelectOp::create(rewriter, op.getLoc(), isNeg,
1890 flipped, adaptor.getInput());
1891
1892 auto resTy = getTypeConverter()->convertType(op.getType());
1893 auto clz = mlir::LLVM::CountLeadingZerosOp::create(
1894 rewriter, op.getLoc(), resTy, select, /*is_zero_poison=*/false);
1895
1896 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 1);
1897 auto res = mlir::LLVM::SubOp::create(rewriter, op.getLoc(), clz, one,
1898 mlir::LLVM::IntegerOverflowFlags::nuw);
1899 rewriter.replaceOp(op, res);
1900
1901 return mlir::LogicalResult::success();
1902}
1903
1904mlir::LogicalResult CIRToLLVMBitFfsOpLowering::matchAndRewrite(
1905 cir::BitFfsOp op, OpAdaptor adaptor,
1906 mlir::ConversionPatternRewriter &rewriter) const {
1907 auto resTy = getTypeConverter()->convertType(op.getType());
1908 auto ctz = mlir::LLVM::CountTrailingZerosOp::create(rewriter, op.getLoc(),
1909 resTy, adaptor.getInput(),
1910 /*is_zero_poison=*/true);
1911
1912 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 1);
1913 auto ctzAddOne = mlir::LLVM::AddOp::create(rewriter, op.getLoc(), ctz, one);
1914
1915 auto zeroInputTy = mlir::LLVM::ConstantOp::create(
1916 rewriter, op.getLoc(), adaptor.getInput().getType(), 0);
1917 auto isZero = mlir::LLVM::ICmpOp::create(
1918 rewriter, op.getLoc(),
1919 mlir::LLVM::ICmpPredicateAttr::get(rewriter.getContext(),
1920 mlir::LLVM::ICmpPredicate::eq),
1921 adaptor.getInput(), zeroInputTy);
1922
1923 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 0);
1924 auto res = mlir::LLVM::SelectOp::create(rewriter, op.getLoc(), isZero, zero,
1925 ctzAddOne);
1926 rewriter.replaceOp(op, res);
1927
1928 return mlir::LogicalResult::success();
1929}
1930
1931mlir::LogicalResult CIRToLLVMBitParityOpLowering::matchAndRewrite(
1932 cir::BitParityOp op, OpAdaptor adaptor,
1933 mlir::ConversionPatternRewriter &rewriter) const {
1934 auto resTy = getTypeConverter()->convertType(op.getType());
1935 auto popcnt = mlir::LLVM::CtPopOp::create(rewriter, op.getLoc(), resTy,
1936 adaptor.getInput());
1937
1938 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 1);
1939 auto popcntMod2 =
1940 mlir::LLVM::AndOp::create(rewriter, op.getLoc(), popcnt, one);
1941 rewriter.replaceOp(op, popcntMod2);
1942
1943 return mlir::LogicalResult::success();
1944}
1945
1946mlir::LogicalResult CIRToLLVMBrCondOpLowering::matchAndRewrite(
1947 cir::BrCondOp brOp, OpAdaptor adaptor,
1948 mlir::ConversionPatternRewriter &rewriter) const {
1949 // When ZExtOp is implemented, we'll need to check if the condition is a
1950 // ZExtOp and if so, delete it if it has a single use.
1952
1953 mlir::Value i1Condition = adaptor.getCond();
1954
1955 rewriter.replaceOpWithNewOp<mlir::LLVM::CondBrOp>(
1956 brOp, i1Condition, brOp.getDestTrue(), adaptor.getDestOperandsTrue(),
1957 brOp.getDestFalse(), adaptor.getDestOperandsFalse());
1958
1959 return mlir::success();
1960}
1961
1962mlir::Type CIRToLLVMCastOpLowering::convertTy(mlir::Type ty) const {
1963 return getTypeConverter()->convertType(ty);
1964}
1965
1966mlir::LogicalResult CIRToLLVMCastOpLowering::matchAndRewrite(
1967 cir::CastOp castOp, OpAdaptor adaptor,
1968 mlir::ConversionPatternRewriter &rewriter) const {
1969 // For arithmetic conversions, LLVM IR uses the same instruction to convert
1970 // both individual scalars and entire vectors. This lowering pass handles
1971 // both situations.
1972
1973 if (!getTypeConverter()->convertType(castOp.getType()))
1974 return emitTypeConversionError(castOp, castOp.getType());
1975
1976 switch (castOp.getKind()) {
1977 case cir::CastKind::array_to_ptrdecay: {
1978 const auto ptrTy = mlir::cast<cir::PointerType>(castOp.getType());
1979 mlir::Value sourceValue = adaptor.getSrc();
1980 mlir::Type targetType = convertTy(ptrTy);
1981 mlir::Type elementTy = convertTypeForMemory(*getTypeConverter(), dataLayout,
1982 ptrTy.getPointee());
1983 if (!elementTy)
1984 return emitTypeConversionError(castOp, ptrTy.getPointee());
1985 llvm::SmallVector<mlir::LLVM::GEPArg> offset{0};
1986 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
1987 castOp, targetType, elementTy, sourceValue, offset);
1988 break;
1989 }
1990 case cir::CastKind::int_to_bool: {
1991 mlir::Value llvmSrcVal = adaptor.getSrc();
1992 // getZeroAttr yields a splat for vector source types so this also
1993 // handles element-wise int-to-bool conversions (e.g. an ext_vector
1994 // __builtin_convertvector to bool).
1995 mlir::Value zeroInt = mlir::LLVM::ConstantOp::create(
1996 rewriter, castOp.getLoc(), llvmSrcVal.getType(),
1997 rewriter.getZeroAttr(llvmSrcVal.getType()));
1998 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
1999 castOp, mlir::LLVM::ICmpPredicate::ne, llvmSrcVal, zeroInt);
2000 break;
2001 }
2002 case cir::CastKind::integral: {
2003 mlir::Type srcType = castOp.getSrc().getType();
2004 mlir::Type dstType = castOp.getType();
2005 mlir::Value llvmSrcVal = adaptor.getSrc();
2006 mlir::Type llvmDstType = getTypeConverter()->convertType(dstType);
2007 cir::IntType srcIntType =
2008 mlir::cast<cir::IntType>(elementTypeIfVectorOrMatrix(srcType));
2009 cir::IntType dstIntType =
2010 mlir::cast<cir::IntType>(elementTypeIfVectorOrMatrix(dstType));
2011 rewriter.replaceOp(castOp, getLLVMIntCast(rewriter, llvmSrcVal, llvmDstType,
2012 srcIntType.isUnsigned(),
2013 srcIntType.getWidth(),
2014 dstIntType.getWidth()));
2015 break;
2016 }
2017 case cir::CastKind::floating: {
2018 mlir::Value llvmSrcVal = adaptor.getSrc();
2019 mlir::Type llvmDstTy = getTypeConverter()->convertType(castOp.getType());
2020
2021 mlir::Type srcTy = elementTypeIfVectorOrMatrix(castOp.getSrc().getType());
2022 mlir::Type dstTy = elementTypeIfVectorOrMatrix(castOp.getType());
2023
2024 if (!mlir::isa<cir::FPTypeInterface>(dstTy) ||
2025 !mlir::isa<cir::FPTypeInterface>(srcTy))
2026 return castOp.emitError() << "NYI cast from " << srcTy << " to " << dstTy;
2027
2028 auto getFloatWidth = [](mlir::Type ty) -> unsigned {
2029 return mlir::cast<cir::FPTypeInterface>(ty).getWidth();
2030 };
2031
2032 bool isTrunc = getFloatWidth(srcTy) > getFloatWidth(dstTy);
2033 if (cir::FenvAttr fenv = castOp.getFenvAttr()) {
2034 // fptrunc takes rounding mode + exception behavior; fpext takes only
2035 // exception behavior.
2037 castOp, llvmSrcVal, fenv, llvmDstTy, rewriter,
2038 isTrunc ? "fptrunc" : "fpext", /*hasRoundingMode=*/isTrunc);
2039 }
2040 if (isTrunc)
2041 rewriter.replaceOpWithNewOp<mlir::LLVM::FPTruncOp>(castOp, llvmDstTy,
2042 llvmSrcVal);
2043 else
2044 rewriter.replaceOpWithNewOp<mlir::LLVM::FPExtOp>(castOp, llvmDstTy,
2045 llvmSrcVal);
2046 return mlir::success();
2047 }
2048 case cir::CastKind::int_to_ptr: {
2049 auto dstTy = mlir::cast<cir::PointerType>(castOp.getType());
2050 mlir::Value llvmSrcVal = adaptor.getSrc();
2051 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2052 rewriter.replaceOpWithNewOp<mlir::LLVM::IntToPtrOp>(castOp, llvmDstTy,
2053 llvmSrcVal);
2054 return mlir::success();
2055 }
2056 case cir::CastKind::ptr_to_int: {
2057 auto dstTy = mlir::cast<cir::IntType>(castOp.getType());
2058 mlir::Value llvmSrcVal = adaptor.getSrc();
2059 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2060 rewriter.replaceOpWithNewOp<mlir::LLVM::PtrToIntOp>(castOp, llvmDstTy,
2061 llvmSrcVal);
2062 return mlir::success();
2063 }
2064 case cir::CastKind::float_to_bool: {
2065 mlir::Value llvmSrcVal = adaptor.getSrc();
2066 auto kind = mlir::LLVM::FCmpPredicate::une;
2067
2068 // Check if float is not equal to zero. getZeroAttr yields a splat
2069 // for vector source types so this also handles element-wise
2070 // float-to-bool conversions.
2071 auto zeroFloat = mlir::LLVM::ConstantOp::create(
2072 rewriter, castOp.getLoc(), llvmSrcVal.getType(),
2073 rewriter.getZeroAttr(llvmSrcVal.getType()));
2074
2075 // Extend comparison result to either bool (C++) or int (C).
2076 rewriter.replaceOpWithNewOp<mlir::LLVM::FCmpOp>(castOp, kind, llvmSrcVal,
2077 zeroFloat);
2078
2079 return mlir::success();
2080 }
2081 case cir::CastKind::bool_to_int: {
2082 mlir::Type dstTy = castOp.getType();
2083 mlir::Value llvmSrcVal = adaptor.getSrc();
2084 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2085 // Compare element widths so this also handles vector bool -> int casts.
2086 auto srcElemTy = mlir::cast<mlir::IntegerType>(
2087 elementTypeIfVectorOrMatrix(llvmSrcVal.getType()));
2088 auto dstElemTy =
2089 mlir::cast<cir::IntType>(elementTypeIfVectorOrMatrix(dstTy));
2090
2091 if (srcElemTy.getWidth() == dstElemTy.getWidth())
2092 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(castOp, llvmDstTy,
2093 llvmSrcVal);
2094 else
2095 rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(castOp, llvmDstTy,
2096 llvmSrcVal);
2097 return mlir::success();
2098 }
2099 case cir::CastKind::bool_to_float: {
2100 mlir::Type dstTy = castOp.getType();
2101 mlir::Value llvmSrcVal = adaptor.getSrc();
2102 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2103 rewriter.replaceOpWithNewOp<mlir::LLVM::UIToFPOp>(castOp, llvmDstTy,
2104 llvmSrcVal);
2105 return mlir::success();
2106 }
2107 case cir::CastKind::int_to_float: {
2108 mlir::Type dstTy = castOp.getType();
2109 mlir::Value llvmSrcVal = adaptor.getSrc();
2110 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2111 bool isSigned = mlir::cast<cir::IntType>(
2112 elementTypeIfVectorOrMatrix(castOp.getSrc().getType()))
2113 .isSigned();
2114 if (cir::FenvAttr fenv = castOp.getFenvAttr()) {
2116 castOp, llvmSrcVal, fenv, llvmDstTy, rewriter,
2117 isSigned ? "sitofp" : "uitofp", /*hasRoundingMode=*/true);
2118 }
2119 if (isSigned)
2120 rewriter.replaceOpWithNewOp<mlir::LLVM::SIToFPOp>(castOp, llvmDstTy,
2121 llvmSrcVal);
2122 else
2123 rewriter.replaceOpWithNewOp<mlir::LLVM::UIToFPOp>(castOp, llvmDstTy,
2124 llvmSrcVal);
2125 return mlir::success();
2126 }
2127 case cir::CastKind::float_to_int: {
2128 mlir::Type dstTy = castOp.getType();
2129 mlir::Value llvmSrcVal = adaptor.getSrc();
2130 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2131 bool isSigned =
2132 mlir::cast<cir::IntType>(elementTypeIfVectorOrMatrix(castOp.getType()))
2133 .isSigned();
2134 if (cir::FenvAttr fenv = castOp.getFenvAttr()) {
2136 castOp, llvmSrcVal, fenv, llvmDstTy, rewriter,
2137 isSigned ? "fptosi" : "fptoui", /*hasRoundingMode=*/false);
2138 }
2139 if (isSigned)
2140 rewriter.replaceOpWithNewOp<mlir::LLVM::FPToSIOp>(castOp, llvmDstTy,
2141 llvmSrcVal);
2142 else
2143 rewriter.replaceOpWithNewOp<mlir::LLVM::FPToUIOp>(castOp, llvmDstTy,
2144 llvmSrcVal);
2145 return mlir::success();
2146 }
2147 case cir::CastKind::bitcast: {
2148 mlir::Type dstTy = castOp.getType();
2149 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2150
2151 assert(!MissingFeatures::cxxABI());
2153
2154 mlir::Value llvmSrcVal = adaptor.getSrc();
2155 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(castOp, llvmDstTy,
2156 llvmSrcVal);
2157 return mlir::success();
2158 }
2159 case cir::CastKind::ptr_to_bool: {
2160 mlir::Value llvmSrcVal = adaptor.getSrc();
2161 mlir::Value zeroPtr = mlir::LLVM::ZeroOp::create(rewriter, castOp.getLoc(),
2162 llvmSrcVal.getType());
2163 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
2164 castOp, mlir::LLVM::ICmpPredicate::ne, llvmSrcVal, zeroPtr);
2165 break;
2166 }
2167 case cir::CastKind::address_space: {
2168 mlir::Type dstTy = castOp.getType();
2169 mlir::Value llvmSrcVal = adaptor.getSrc();
2170 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
2171 rewriter.replaceOpWithNewOp<mlir::LLVM::AddrSpaceCastOp>(castOp, llvmDstTy,
2172 llvmSrcVal);
2173 break;
2174 }
2175 case cir::CastKind::member_ptr_to_bool:
2176 assert(!MissingFeatures::cxxABI());
2177 assert(!MissingFeatures::methodType());
2178 break;
2179 default: {
2180 return castOp.emitError("Unhandled cast kind: ")
2181 << castOp.getKindAttrName();
2182 }
2183 }
2184
2185 return mlir::success();
2186}
2187
2188mlir::LogicalResult CIRToLLVMBuiltinIntCastOpLowering::matchAndRewrite(
2189 cir::BuiltinIntCastOp op, OpAdaptor adaptor,
2190 mlir::ConversionPatternRewriter &rewriter) const {
2191 // Both the CIR integer and the builtin integer/index lower to LLVM integer
2192 // types, so this cast becomes an integer resize. Signedness is taken from
2193 // the CIR integer side (the builtin/index side is treated as signless).
2194 bool isUnsigned = true;
2195 if (auto cirSrc = mlir::dyn_cast<cir::IntType>(op.getSrc().getType()))
2196 isUnsigned = cirSrc.isUnsigned();
2197 else if (auto cirDst = mlir::dyn_cast<cir::IntType>(op.getType()))
2198 isUnsigned = cirDst.isUnsigned();
2199
2200 mlir::Value llvmSrc = adaptor.getSrc();
2201 mlir::Type llvmDstTy = getTypeConverter()->convertType(op.getType());
2202 auto srcIntTy = mlir::cast<mlir::IntegerType>(llvmSrc.getType());
2203 auto dstIntTy = mlir::cast<mlir::IntegerType>(llvmDstTy);
2204 unsigned srcWidth = srcIntTy.getWidth();
2205 unsigned dstWidth = dstIntTy.getWidth();
2206
2207 // Fixed-width builtin integers must match the CIR integer width.
2208 // If the converted LLVM widths differ, the non-CIR side must have been
2209 // 'index' type (target dependent width).
2210 assert((srcWidth == dstWidth ||
2211 mlir::isa<mlir::IndexType>(op.getSrc().getType()) ||
2212 mlir::isa<mlir::IndexType>(op.getType())) &&
2213 "only index casts may change width during lowering");
2214
2215 // For equal widths getLLVMIntCast returns the source unchanged, so casts
2216 // between CIR integers and fixed-width builtin integers lower to a no-op.
2217 rewriter.replaceOp(op, getLLVMIntCast(rewriter, llvmSrc, dstIntTy, isUnsigned,
2218 srcWidth, dstWidth));
2219 return mlir::success();
2220}
2221
2222static mlir::Value convertToIndexTy(mlir::ConversionPatternRewriter &rewriter,
2223 mlir::ModuleOp mod, mlir::Value index,
2224 mlir::Type baseTy, cir::IntType strideTy) {
2225 mlir::Operation *indexOp = index.getDefiningOp();
2226 if (!indexOp)
2227 return index;
2228
2229 auto indexType = mlir::cast<mlir::IntegerType>(index.getType());
2230 mlir::DataLayout llvmLayout(mod);
2231 std::optional<uint64_t> layoutWidth = llvmLayout.getTypeIndexBitwidth(baseTy);
2232
2233 // If there is no change in width, don't do anything.
2234 if (!layoutWidth || *layoutWidth == indexType.getWidth())
2235 return index;
2236
2237 // If the index comes from a subtraction, make sure the extension happens
2238 // before it. To achieve that, look at unary minus, which already got
2239 // lowered to "sub 0, x".
2240 auto sub = dyn_cast<mlir::LLVM::SubOp>(indexOp);
2241 bool rewriteSub = false;
2242 if (sub) {
2243 if (auto lhsConst = dyn_cast_if_present<mlir::LLVM::ConstantOp>(
2244 sub.getLhs().getDefiningOp())) {
2245 auto lhsConstInt = mlir::dyn_cast<mlir::IntegerAttr>(lhsConst.getValue());
2246 if (lhsConstInt && lhsConstInt.getValue() == 0) {
2247 index = sub.getRhs();
2248 rewriteSub = true;
2249 }
2250 }
2251 }
2252
2253 auto llvmDstType = rewriter.getIntegerType(*layoutWidth);
2254 bool isUnsigned = strideTy && strideTy.isUnsigned();
2255 index = getLLVMIntCast(rewriter, index, llvmDstType, isUnsigned,
2256 indexType.getWidth(), *layoutWidth);
2257
2258 if (rewriteSub) {
2259 index = mlir::LLVM::SubOp::create(
2260 rewriter, index.getLoc(),
2261 mlir::LLVM::ConstantOp::create(rewriter, index.getLoc(),
2262 index.getType(), 0),
2263 index);
2264 }
2265
2266 return index;
2267}
2268
2269mlir::LogicalResult CIRToLLVMPtrStrideOpLowering::matchAndRewrite(
2270 cir::PtrStrideOp ptrStrideOp, OpAdaptor adaptor,
2271 mlir::ConversionPatternRewriter &rewriter) const {
2272
2273 const mlir::TypeConverter *tc = getTypeConverter();
2274 const mlir::Type resultTy = tc->convertType(ptrStrideOp.getType());
2275
2276 mlir::Type elementTy =
2277 convertTypeForMemory(*tc, dataLayout, ptrStrideOp.getElementType());
2278 if (!elementTy)
2279 return emitTypeConversionError(ptrStrideOp, ptrStrideOp.getElementType());
2280
2281 // void and function types doesn't really have a layout to use in GEPs,
2282 // make it i8 instead.
2283 if (mlir::isa<mlir::LLVM::LLVMVoidType>(elementTy) ||
2284 mlir::isa<mlir::LLVM::LLVMFunctionType>(elementTy))
2285 elementTy = mlir::IntegerType::get(elementTy.getContext(), 8,
2286 mlir::IntegerType::Signless);
2287 // Zero-extend, sign-extend or trunc the pointer value.
2288 mlir::Value index = adaptor.getStride();
2289 index = convertToIndexTy(
2290 rewriter, ptrStrideOp->getParentOfType<mlir::ModuleOp>(), index,
2291 adaptor.getBase().getType(),
2292 dyn_cast<cir::IntType>(ptrStrideOp.getOperand(1).getType()));
2293
2294 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
2295 ptrStrideOp, resultTy, elementTy, adaptor.getBase(), index);
2296 return mlir::success();
2297}
2298
2299mlir::LogicalResult CIRToLLVMGetElementOpLowering::matchAndRewrite(
2300 cir::GetElementOp op, OpAdaptor adaptor,
2301 mlir::ConversionPatternRewriter &rewriter) const {
2302 if (auto arrayTy =
2303 mlir::dyn_cast<cir::ArrayType>(op.getBaseType().getPointee())) {
2304 const mlir::TypeConverter *converter = getTypeConverter();
2305 const mlir::Type llArrayTy = converter->convertType(arrayTy);
2306 if (!llArrayTy)
2307 return emitTypeConversionError(op, arrayTy);
2308 const mlir::Type llResultTy = converter->convertType(op.getType());
2309 mlir::Type elementTy =
2310 convertTypeForMemory(*converter, dataLayout, op.getElementType());
2311
2312 // void and function types don't really have a layout to use in GEPs,
2313 // make it i8 instead.
2314 if (mlir::isa<mlir::LLVM::LLVMVoidType>(elementTy) ||
2315 mlir::isa<mlir::LLVM::LLVMFunctionType>(elementTy))
2316 elementTy = rewriter.getIntegerType(8);
2317
2318 mlir::Value index = adaptor.getIndex();
2319 index =
2320 convertToIndexTy(rewriter, op->getParentOfType<mlir::ModuleOp>(), index,
2321 adaptor.getBase().getType(),
2322 dyn_cast<cir::IntType>(op.getOperand(1).getType()));
2323
2324 // Since the base address is a pointer to an array, the first index is
2325 // always zero, and the second one selects the element. The zero takes the
2326 // element index's type, because a raw constant GEP index is always
2327 // translated as i32.
2328 mlir::Value zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
2329 index.getType(), 0);
2330 std::array<mlir::LLVM::GEPArg, 2> offset = {zero, index};
2331 mlir::LLVM::GEPNoWrapFlags flags = mlir::LLVM::GEPNoWrapFlags::none;
2332 if (op.getInBounds())
2333 flags |= mlir::LLVM::GEPNoWrapFlags::inbounds;
2334 if (op.getNoUnsignedWrap())
2335 flags |= mlir::LLVM::GEPNoWrapFlags::nuw;
2336 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
2337 op, llResultTy, llArrayTy, adaptor.getBase(), offset, flags);
2338 return mlir::success();
2339 }
2340
2341 op.emitError() << "NYI: GetElementOp lowering to LLVM for non-array";
2342 return mlir::failure();
2343}
2344
2345mlir::LogicalResult CIRToLLVMBaseClassAddrOpLowering::matchAndRewrite(
2346 cir::BaseClassAddrOp baseClassOp, OpAdaptor adaptor,
2347 mlir::ConversionPatternRewriter &rewriter) const {
2348 const mlir::Type resultType =
2349 getTypeConverter()->convertType(baseClassOp.getType());
2350 if (!resultType)
2351 return emitTypeConversionError(baseClassOp, baseClassOp.getType());
2352 mlir::Value derivedAddr = adaptor.getSrcAddr();
2353 llvm::SmallVector<mlir::LLVM::GEPArg, 1> offset = {
2354 static_cast<int32_t>(adaptor.getOffset().getZExtValue())};
2355 mlir::Type byteType = mlir::IntegerType::get(resultType.getContext(), 8,
2356 mlir::IntegerType::Signless);
2357 if (adaptor.getOffset().getZExtValue() == 0) {
2358 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(baseClassOp, resultType,
2359 adaptor.getSrcAddr());
2360 return mlir::success();
2361 }
2362
2363 if (baseClassOp.getAssumeNotNull()) {
2364 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
2365 baseClassOp, resultType, byteType, derivedAddr, offset);
2366 } else {
2367 auto loc = baseClassOp.getLoc();
2368 mlir::Value isNull = mlir::LLVM::ICmpOp::create(
2369 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, derivedAddr,
2370 mlir::LLVM::ZeroOp::create(rewriter, loc, derivedAddr.getType()));
2371 mlir::Value adjusted = mlir::LLVM::GEPOp::create(
2372 rewriter, loc, resultType, byteType, derivedAddr, offset);
2373 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(baseClassOp, isNull,
2374 derivedAddr, adjusted);
2375 }
2376 return mlir::success();
2377}
2378
2379mlir::LogicalResult CIRToLLVMDerivedClassAddrOpLowering::matchAndRewrite(
2380 cir::DerivedClassAddrOp derivedClassOp, OpAdaptor adaptor,
2381 mlir::ConversionPatternRewriter &rewriter) const {
2382 const mlir::Type resultType =
2383 getTypeConverter()->convertType(derivedClassOp.getType());
2384 if (!resultType)
2385 return emitTypeConversionError(derivedClassOp, derivedClassOp.getType());
2386 mlir::Value baseAddr = adaptor.getSrcAddr();
2387 // The offset is set in the operation as an unsigned value, but it must be
2388 // applied as a negative offset.
2389 int64_t offsetVal = -(adaptor.getOffset().getZExtValue());
2390 if (offsetVal == 0) {
2391 // If the offset is zero, we can just return the source address.
2392 rewriter.replaceOp(derivedClassOp, baseAddr);
2393 return mlir::success();
2394 }
2395 llvm::SmallVector<mlir::LLVM::GEPArg, 1> offset = {
2396 static_cast<int32_t>(offsetVal)};
2397 mlir::Type byteType = mlir::IntegerType::get(resultType.getContext(), 8,
2398 mlir::IntegerType::Signless);
2399 if (derivedClassOp.getAssumeNotNull()) {
2400 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
2401 derivedClassOp, resultType, byteType, baseAddr, offset,
2402 mlir::LLVM::GEPNoWrapFlags::inbounds);
2403 } else {
2404 mlir::Location loc = derivedClassOp.getLoc();
2405 mlir::Value isNull = mlir::LLVM::ICmpOp::create(
2406 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, baseAddr,
2407 mlir::LLVM::ZeroOp::create(rewriter, loc, baseAddr.getType()));
2408 mlir::Value adjusted =
2409 mlir::LLVM::GEPOp::create(rewriter, loc, resultType, byteType, baseAddr,
2410 offset, mlir::LLVM::GEPNoWrapFlags::inbounds);
2411 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(derivedClassOp, isNull,
2412 baseAddr, adjusted);
2413 }
2414 return mlir::success();
2415}
2416
2417mlir::LogicalResult CIRToLLVMFMaxNumOpLowering::matchAndRewrite(
2418 cir::FMaxNumOp op, OpAdaptor adaptor,
2419 mlir::ConversionPatternRewriter &rewriter) const {
2420 mlir::Type resTy = typeConverter->convertType(op.getType());
2421 if (cir::FenvAttr fenv = op.getFenvAttr())
2423 op, adaptor.getOperands(), fenv, resTy, rewriter, "maxnum",
2424 /*hasRoundingMode=*/false, mlir::LLVM::FastmathFlags::nsz);
2425 rewriter.replaceOpWithNewOp<mlir::LLVM::MaxNumOp>(
2426 op, resTy, adaptor.getLhs(), adaptor.getRhs(),
2427 mlir::LLVM::FastmathFlags::nsz);
2428 return mlir::success();
2429}
2430
2431mlir::LogicalResult CIRToLLVMFMinNumOpLowering::matchAndRewrite(
2432 cir::FMinNumOp op, OpAdaptor adaptor,
2433 mlir::ConversionPatternRewriter &rewriter) const {
2434 mlir::Type resTy = typeConverter->convertType(op.getType());
2435 if (cir::FenvAttr fenv = op.getFenvAttr())
2437 op, adaptor.getOperands(), fenv, resTy, rewriter, "minnum",
2438 /*hasRoundingMode=*/false, mlir::LLVM::FastmathFlags::nsz);
2439 rewriter.replaceOpWithNewOp<mlir::LLVM::MinNumOp>(
2440 op, resTy, adaptor.getLhs(), adaptor.getRhs(),
2441 mlir::LLVM::FastmathFlags::nsz);
2442 return mlir::success();
2443}
2444
2445mlir::LogicalResult CIRToLLVMAllocaOpLowering::matchAndRewrite(
2446 cir::AllocaOp op, OpAdaptor adaptor,
2447 mlir::ConversionPatternRewriter &rewriter) const {
2448 mlir::ModuleOp module = op->getParentOfType<mlir::ModuleOp>();
2449 mlir::Attribute langOpts =
2450 module->getAttr(cir::CIRDialect::getLoweringOptionsAttrName());
2451 auto loweringLangOps =
2452 dyn_cast_if_present<cir::LoweringOptionsAttr>(langOpts);
2453
2454 bool isForHLSL = loweringLangOps ? loweringLangOps.getHlsl() : false;
2455 if (isForHLSL && mlir::isa<cir::MatrixType>(op.getAllocaType()) &&
2456 mlir::isa<cir::BoolType>(
2457 cast<cir::MatrixType>(op.getAllocaType()).getElementType())) {
2458 return op.emitError()
2459 << "NYI: Builtin matrix type with bool element type for HLSL";
2460 }
2461
2462 mlir::Value size =
2463 op.isDynamic()
2464 ? adaptor.getDynAllocSize()
2465 : mlir::LLVM::ConstantOp::create(
2466 rewriter, op.getLoc(),
2467 typeConverter->convertType(rewriter.getI32Type()), 1);
2468 mlir::Type elementTy = convertTypeForMemory(*getTypeConverter(), dataLayout,
2469 op.getAllocaType(), isForHLSL);
2470 if (!elementTy)
2471 return op.emitError()
2472 << "NYI: lowering alloca of a type with no memory representation";
2473 mlir::Type resultTy = convertTypeForMemory(*getTypeConverter(), dataLayout,
2474 op.getType(), isForHLSL);
2475 if (!resultTy)
2476 return emitTypeConversionError(op, op.getType());
2477
2479
2480 rewriter.replaceOpWithNewOp<mlir::LLVM::AllocaOp>(op, resultTy, elementTy,
2481 size, op.getAlignment());
2482
2483 return mlir::success();
2484}
2485
2486mlir::LogicalResult CIRToLLVMRotateOpLowering::matchAndRewrite(
2487 cir::RotateOp op, OpAdaptor adaptor,
2488 mlir::ConversionPatternRewriter &rewriter) const {
2489 // Note that LLVM intrinsic calls to @llvm.fsh{r,l}.i* have the same type as
2490 // the operand.
2491 mlir::Value input = adaptor.getInput();
2492 if (op.isRotateLeft())
2493 rewriter.replaceOpWithNewOp<mlir::LLVM::FshlOp>(op, input, input,
2494 adaptor.getAmount());
2495 else
2496 rewriter.replaceOpWithNewOp<mlir::LLVM::FshrOp>(op, input, input,
2497 adaptor.getAmount());
2498 return mlir::LogicalResult::success();
2499}
2500
2501/// The `llvm.byval`, `llvm.sret`, and `llvm.byref` argument attributes carry
2502/// the pointee type as a TypeAttr. After the CallConvLowering pass that type
2503/// is still a CIR type; remap it to the lowered LLVM type so translation to
2504/// LLVM IR does not encounter a CIR type in an attribute. The pointee must
2505/// name the in-memory storage type, not the value type, since it sizes the
2506/// byval copy and the sret slot: a _BitInt narrower than its padded storage
2507/// integer would otherwise understate both. Returns std::nullopt when a
2508/// pointee has no memory representation, leaving the caller to emit the NYI
2509/// error, and the input unchanged when there is nothing to convert.
2510static std::optional<mlir::ArrayAttr> convertTypedArgAttrs(
2511 mlir::ArrayAttr argAttrs, const mlir::TypeConverter &converter,
2512 const mlir::DataLayout &dataLayout, mlir::MLIRContext *ctx) {
2513 if (!argAttrs)
2514 return argAttrs;
2515 bool changed = false;
2516 SmallVector<mlir::Attribute> loweredArgAttrs;
2517 loweredArgAttrs.reserve(argAttrs.size());
2518 for (mlir::Attribute a : argAttrs) {
2519 auto dict = cast<mlir::DictionaryAttr>(a);
2520 SmallVector<mlir::NamedAttribute> entries(dict.begin(), dict.end());
2521 for (mlir::NamedAttribute &entry : entries) {
2522 StringRef name = entry.getName().strref();
2523 if (name != mlir::LLVM::LLVMDialect::getByValAttrName() &&
2524 name != mlir::LLVM::LLVMDialect::getStructRetAttrName() &&
2525 name != mlir::LLVM::LLVMDialect::getByRefAttrName())
2526 continue;
2527 auto typeAttr = dyn_cast<mlir::TypeAttr>(entry.getValue());
2528 if (!typeAttr)
2529 continue;
2530 mlir::Type lowered =
2531 convertTypeForMemory(converter, dataLayout, typeAttr.getValue());
2532 if (!lowered)
2533 return std::nullopt;
2534 if (lowered != typeAttr.getValue()) {
2535 entry.setValue(mlir::TypeAttr::get(lowered));
2536 changed = true;
2537 }
2538 }
2539 loweredArgAttrs.push_back(mlir::DictionaryAttr::get(ctx, entries));
2540 }
2541 return changed ? mlir::ArrayAttr::get(ctx, loweredArgAttrs) : argAttrs;
2542}
2543
2549
2550static mlir::LogicalResult lowerCallAttributes(
2551 cir::CIRCallOpInterface op, const mlir::TypeConverter &converter,
2552 const mlir::DataLayout &dataLayout, LoweredCallAttributes &result) {
2553 if (auto argAttrs = mlir::dyn_cast_if_present<mlir::ArrayAttr>(
2554 op->getInherentAttr(CIRDialect::getArgAttrsAttrName())
2555 .value_or(mlir::Attribute{}))) {
2556 std::optional<mlir::ArrayAttr> lowered =
2557 convertTypedArgAttrs(argAttrs, converter, dataLayout, op->getContext());
2558 if (!lowered)
2559 return op->emitError() << "NYI: lowering a byval/sret/byref call "
2560 "argument whose pointee type has no "
2561 "memory representation";
2562 result.argAttrs = *lowered;
2563 }
2564 result.resAttrs = mlir::dyn_cast_if_present<mlir::ArrayAttr>(
2565 op->getInherentAttr(CIRDialect::getResAttrsAttrName())
2566 .value_or(mlir::Attribute{}));
2567
2568 for (mlir::NamedAttribute attr : op->getDiscardableAttrs()) {
2569 if (attr.getName() == CIRDialect::getNoUnwindAttrName() ||
2570 attr.getName() == CIRDialect::getNoReturnAttrName())
2571 continue;
2573 result.discardableAttrs.push_back(attr);
2574 }
2575 return mlir::success();
2576}
2577
2578template <typename CallLikeOp>
2579static void setLoweredCallAttributes(CallLikeOp op,
2580 const LoweredCallAttributes &attributes) {
2581 if (attributes.argAttrs)
2582 op.setArgAttrsAttr(attributes.argAttrs);
2583 if (attributes.resAttrs)
2584 op.setResAttrsAttr(attributes.resAttrs);
2585 for (mlir::NamedAttribute attr : attributes.discardableAttrs) {
2586 if (op->getInherentAttr(attr.getName()).has_value())
2587 op->setInherentAttr(attr.getName(), attr.getValue());
2588 else
2589 op->setDiscardableAttr(attr.getName(), attr.getValue());
2590 }
2591}
2592
2593static mlir::LogicalResult rewriteCallOrInvoke(
2594 mlir::Operation *op, mlir::ValueRange callOperands,
2595 mlir::ConversionPatternRewriter &rewriter,
2596 const mlir::TypeConverter *converter, const mlir::DataLayout &dataLayout,
2597 mlir::SymbolTableCollection &symbolTables,
2598 mlir::FlatSymbolRefAttr calleeAttr, mlir::Block *continueBlock = nullptr,
2599 mlir::Block *landingPadBlock = nullptr) {
2601 mlir::ValueTypeRange<mlir::ResultRange> cirResults = op->getResultTypes();
2602 auto call = cast<cir::CIRCallOpInterface>(op);
2603
2604 if (converter->convertTypes(cirResults, llvmResults).failed())
2605 return mlir::failure();
2606
2607 mlir::LLVM::MemoryEffectsAttr memoryEffects;
2608 bool noUnwind = false;
2609 bool willReturn = false;
2610 bool noReturn = false;
2611 convertCallEffects(op, call.getNothrow(), call.getMemoryEffectsAttr(),
2612 memoryEffects, noUnwind, willReturn, noReturn);
2613
2614 LoweredCallAttributes attributes;
2615 if (mlir::failed(
2616 lowerCallAttributes(call, *converter, dataLayout, attributes)))
2617 return mlir::failure();
2618
2619 mlir::LLVM::LLVMFunctionType llvmFnTy;
2620
2621 // Temporary to handle the case where we need to prepend an operand if the
2622 // callee is an alias.
2623 SmallVector<mlir::Value> adjustedCallOperands;
2624
2625 if (calleeAttr) { // direct call
2626 mlir::Operation *callee =
2627 symbolTables.lookupNearestSymbolFrom(op, calleeAttr);
2628 if (auto fn = mlir::dyn_cast<mlir::FunctionOpInterface>(callee)) {
2629 llvmFnTy = converter->convertType<mlir::LLVM::LLVMFunctionType>(
2630 fn.getFunctionType());
2631 assert(llvmFnTy && "Failed to convert function type");
2632 } else if (auto alias = mlir::cast<mlir::LLVM::AliasOp>(callee)) {
2633 // If the callee was an alias. In that case,
2634 // we need to prepend the address of the alias to the operands. The
2635 // way aliases work in the LLVM dialect is a little counter-intuitive.
2636 // The AliasOp itself is a pseudo-function that returns the address of
2637 // the global value being aliased, but when we generate the call we
2638 // need to insert an operation that gets the address of the AliasOp.
2639 // This all gets sorted out when the LLVM dialect is lowered to LLVM IR.
2640 auto symAttr = mlir::cast<mlir::FlatSymbolRefAttr>(calleeAttr);
2641 auto addrOfAlias =
2642 mlir::LLVM::AddressOfOp::create(
2643 rewriter, op->getLoc(),
2644 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()), symAttr)
2645 .getResult();
2646 adjustedCallOperands.push_back(addrOfAlias);
2647
2648 // Now add the regular operands and assign this to the range value.
2649 llvm::append_range(adjustedCallOperands, callOperands);
2650 callOperands = adjustedCallOperands;
2651
2652 // Clear the callee attribute because we're calling an alias.
2653 calleeAttr = {};
2654 llvmFnTy = mlir::cast<mlir::LLVM::LLVMFunctionType>(alias.getType());
2655 } else {
2656 // Was this an ifunc?
2657 return op->emitError("Unexpected callee type!");
2658 }
2659 } else { // indirect call
2660 assert(!op->getOperands().empty() &&
2661 "operands list must no be empty for the indirect call");
2662 auto calleeTy = op->getOperands().front().getType();
2663 auto calleePtrTy = cast<cir::PointerType>(calleeTy);
2664 auto calleeFuncTy = cast<cir::FuncType>(calleePtrTy.getPointee());
2665 llvm::append_range(adjustedCallOperands, callOperands);
2666 llvmFnTy = cast<mlir::LLVM::LLVMFunctionType>(
2667 converter->convertType(calleeFuncTy));
2668 }
2669
2670 mlir::LLVM::CConv cconv = convertCallingConv(call.getCallingConv());
2671
2672 // The replace below erases the root op, so read what the CallOp branch
2673 // needs first.
2674 const bool mustTail = op->hasAttr(CIRDialect::getMustTailAttrName());
2675 const std::optional<cir::InlineKind> inlineKind = call.getInlineKind();
2676 if (landingPadBlock) {
2678 auto newOp = rewriter.replaceOpWithNewOp<mlir::LLVM::InvokeOp>(
2679 op, llvmFnTy, calleeAttr, callOperands, continueBlock,
2680 mlir::ValueRange{}, landingPadBlock, mlir::ValueRange{});
2681 newOp.setCConv(cconv);
2682 setLoweredCallAttributes(newOp, attributes);
2683 } else {
2684 auto newOp = rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
2685 op, llvmFnTy, calleeAttr, callOperands);
2686 newOp.setCConv(cconv);
2687 setLoweredCallAttributes(newOp, attributes);
2688 if (memoryEffects)
2689 newOp.setMemoryEffectsAttr(memoryEffects);
2690 newOp.setNoUnwind(noUnwind);
2691 newOp.setWillReturn(willReturn);
2692 newOp.setNoreturn(noReturn);
2693 if (mustTail)
2694 newOp.setTailCallKind(mlir::LLVM::TailCallKind::MustTail);
2695
2696 if (inlineKind) {
2697 newOp.setNoInline(*inlineKind == cir::InlineKind::NoInline);
2698 newOp.setInlineHint(*inlineKind == cir::InlineKind::InlineHint);
2699 newOp.setAlwaysInline(*inlineKind == cir::InlineKind::AlwaysInline);
2700 }
2701 }
2702
2703 return mlir::success();
2704}
2705
2706mlir::LogicalResult CIRToLLVMCallOpLowering::matchAndRewrite(
2707 cir::CallOp op, OpAdaptor adaptor,
2708 mlir::ConversionPatternRewriter &rewriter) const {
2709 return rewriteCallOrInvoke(op.getOperation(), adaptor.getOperands(), rewriter,
2710 getTypeConverter(), dataLayout, symbolTables,
2711 op.getCalleeAttr());
2712}
2713
2714mlir::LogicalResult CIRToLLVMTryCallOpLowering::matchAndRewrite(
2715 cir::TryCallOp op, OpAdaptor adaptor,
2716 mlir::ConversionPatternRewriter &rewriter) const {
2717 return rewriteCallOrInvoke(op.getOperation(), adaptor.getOperands(), rewriter,
2718 getTypeConverter(), dataLayout, symbolTables,
2719 op.getCalleeAttr(), op.getNormalDest(),
2720 op.getUnwindDest());
2721}
2722
2723mlir::LogicalResult CIRToLLVMReturnAddrOpLowering::matchAndRewrite(
2724 cir::ReturnAddrOp op, OpAdaptor adaptor,
2725 mlir::ConversionPatternRewriter &rewriter) const {
2726 const mlir::Type llvmPtrTy = getTypeConverter()->convertType(op.getType());
2727 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.returnaddress",
2728 llvmPtrTy, adaptor.getOperands());
2729 return mlir::success();
2730}
2731
2732mlir::LogicalResult CIRToLLVMFrameAddrOpLowering::matchAndRewrite(
2733 cir::FrameAddrOp op, OpAdaptor adaptor,
2734 mlir::ConversionPatternRewriter &rewriter) const {
2735 const mlir::Type llvmPtrTy = getTypeConverter()->convertType(op.getType());
2736 if (!llvmPtrTy)
2737 return emitTypeConversionError(op, op.getType());
2738 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.frameaddress", llvmPtrTy,
2739 adaptor.getOperands());
2740 return mlir::success();
2741}
2742
2743mlir::LogicalResult CIRToLLVMClearCacheOpLowering::matchAndRewrite(
2744 cir::ClearCacheOp op, OpAdaptor adaptor,
2745 mlir::ConversionPatternRewriter &rewriter) const {
2746 mlir::Value begin = adaptor.getBegin();
2747 mlir::Value end = adaptor.getEnd();
2748 auto intrinNameAttr =
2749 mlir::StringAttr::get(op.getContext(), "llvm.clear_cache");
2750 rewriter.replaceOpWithNewOp<mlir::LLVM::CallIntrinsicOp>(
2751 op, mlir::Type{}, intrinNameAttr, mlir::ValueRange{begin, end});
2752
2753 return mlir::success();
2754}
2755
2756mlir::LogicalResult CIRToLLVMAddrOfReturnAddrOpLowering::matchAndRewrite(
2757 cir::AddrOfReturnAddrOp op, OpAdaptor adaptor,
2758 mlir::ConversionPatternRewriter &rewriter) const {
2759 const mlir::Type llvmPtrTy = getTypeConverter()->convertType(op.getType());
2760 if (!llvmPtrTy)
2761 return emitTypeConversionError(op, op.getType());
2762 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.addressofreturnaddress",
2763 llvmPtrTy, adaptor.getOperands());
2764 return mlir::success();
2765}
2766
2767mlir::LogicalResult CIRToLLVMAMDGPUFeaturePredicateOpLowering::matchAndRewrite(
2768 cir::AMDGPUFeaturePredicateOp op, OpAdaptor adaptor,
2769 mlir::ConversionPatternRewriter &rewriter) const {
2770 mlir::Location loc = op.getLoc();
2771 mlir::MLIRContext *ctx = rewriter.getContext();
2772 mlir::Value specId =
2773 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), -1);
2774 mlir::Value defaultValue =
2775 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI1Type(), 0);
2776 auto predicate = mlir::LLVM::MDNodeAttr::get(
2777 ctx, mlir::LLVM::MDStringAttr::get(ctx, op.getPredicateAttr()));
2778 mlir::Value md =
2779 mlir::LLVM::MetadataAsValueOp::create(rewriter, loc, predicate);
2781 rewriter, op, "llvm.spv.named.boolean.spec.constant",
2782 getTypeConverter()->convertType(op.getType()),
2783 mlir::ValueRange{specId, defaultValue, md});
2784 return mlir::success();
2785}
2786
2787mlir::LogicalResult CIRToLLVMLoadOpLowering::matchAndRewrite(
2788 cir::LoadOp op, OpAdaptor adaptor,
2789 mlir::ConversionPatternRewriter &rewriter) const {
2790 const mlir::Type llvmTy =
2791 convertTypeForLoadStore(*getTypeConverter(), dataLayout, op.getType());
2792 if (!llvmTy)
2793 return emitTypeConversionError(op, op.getType());
2794 mlir::LLVM::AtomicOrdering ordering = getLLVMMemOrder(op.getMemOrder());
2795 std::optional<size_t> opAlign = op.getAlignment();
2796 unsigned alignment = (unsigned)opAlign.value_or(
2797 getMemoryFallbackAlignment(op, op.getType(), llvmTy, dataLayout));
2798
2800
2801 std::optional<llvm::StringRef> llvmSyncScope = getLLVMSyncScope(
2802 op.getSyncScope(), op->getParentOfType<mlir::ModuleOp>());
2803
2804 mlir::LLVM::LoadOp newLoad = mlir::LLVM::LoadOp::create(
2805 rewriter, op->getLoc(), llvmTy, adaptor.getAddr(), alignment,
2806 op.getIsVolatile(), /*isNonTemporal=*/op.getIsNontemporal(),
2807 /*isInvariant=*/op.getInvariant(), /*isInvariantGroup=*/false,
2808 /*isNoundef=*/false, ordering, llvmSyncScope.value_or(std::string()));
2809 if (mlir::Attribute domain = op->getAttr("cir.riscv_nontemporal_domain"))
2810 newLoad->setAttr("cir.riscv_nontemporal_domain", domain);
2811
2812 // Convert adapted result to its original type if needed.
2813 mlir::Value result = emitFromMemory(rewriter, *getTypeConverter(), dataLayout,
2814 op, newLoad.getResult());
2815 rewriter.replaceOp(op, result);
2817 return mlir::LogicalResult::success();
2818}
2819
2820mlir::LogicalResult
2821cir::direct::CIRToLLVMVecMaskedLoadOpLowering::matchAndRewrite(
2822 cir::VecMaskedLoadOp op, OpAdaptor adaptor,
2823 mlir::ConversionPatternRewriter &rewriter) const {
2824 const mlir::Type llvmResTy =
2825 convertTypeForLoadStore(*getTypeConverter(), dataLayout, op.getType());
2826 if (!llvmResTy)
2827 return op.emitError()
2828 << "NYI: lowering masked load of a type with no memory "
2829 "representation";
2830
2831 std::optional<size_t> opAlign = op.getAlignment();
2832 unsigned alignment =
2833 (unsigned)opAlign.value_or(dataLayout.getTypeABIAlignment(llvmResTy));
2834
2835 auto newLoad = mlir::LLVM::MaskedLoadOp::create(
2836 rewriter, op.getLoc(), llvmResTy, adaptor.getAddr(), adaptor.getMask(),
2837 adaptor.getPassThru(), alignment);
2838
2839 rewriter.replaceOp(op, newLoad.getResult());
2840 return mlir::success();
2841}
2842
2843mlir::LogicalResult CIRToLLVMStoreOpLowering::matchAndRewrite(
2844 cir::StoreOp op, OpAdaptor adaptor,
2845 mlir::ConversionPatternRewriter &rewriter) const {
2846 mlir::LLVM::AtomicOrdering memorder = getLLVMMemOrder(op.getMemOrder());
2847 mlir::Type valueType = op.getValue().getType();
2848 const mlir::Type llvmTy =
2849 convertTypeForLoadStore(*getTypeConverter(), dataLayout, valueType);
2850 if (!llvmTy)
2851 return op.emitError()
2852 << "NYI: lowering store of a type with no memory representation";
2853 std::optional<size_t> opAlign = op.getAlignment();
2854 unsigned alignment = (unsigned)opAlign.value_or(
2855 getMemoryFallbackAlignment(op, valueType, llvmTy, dataLayout));
2856
2858
2859 // Convert adapted value to its memory type if needed.
2860 mlir::Value value = emitToMemory(rewriter, dataLayout,
2861 op.getValue().getType(), adaptor.getValue());
2863
2864 std::optional<llvm::StringRef> llvmSyncScope = getLLVMSyncScope(
2865 op.getSyncScope(), op->getParentOfType<mlir::ModuleOp>());
2866
2867 mlir::LLVM::StoreOp storeOp = mlir::LLVM::StoreOp::create(
2868 rewriter, op->getLoc(), value, adaptor.getAddr(), alignment,
2869 op.getIsVolatile(),
2870 /*isNonTemporal=*/op.getIsNontemporal(), /*isInvariantGroup=*/false,
2871 memorder, llvmSyncScope.value_or(std::string()));
2872 if (mlir::Attribute domain = op->getAttr("cir.riscv_nontemporal_domain"))
2873 storeOp->setAttr("cir.riscv_nontemporal_domain", domain);
2874 rewriter.replaceOp(op, storeOp);
2876 return mlir::LogicalResult::success();
2877}
2878
2879static mlir::Type getConstArrayBaseElementType(mlir::Type ty) {
2880 while (auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty))
2881 ty = arrTy.getElementType();
2882 return ty;
2883}
2884
2885static bool isBulkLowerableConstArrayBaseElement(mlir::Type baseElemTy) {
2886 return mlir::isa<cir::PointerType, cir::IntType, cir::BoolType,
2887 cir::FPTypeInterface, cir::RecordType>(baseElemTy);
2888}
2889
2890mlir::LogicalResult CIRToLLVMConstantOpLowering::matchAndRewrite(
2891 cir::ConstantOp op, OpAdaptor adaptor,
2892 mlir::ConversionPatternRewriter &rewriter) const {
2893 mlir::Attribute attr = op.getValue();
2894 if (!getTypeConverter()->convertType(op.getType()))
2895 return emitTypeConversionError(op, op.getType());
2896 mlir::ModuleOp moduleOp = op->getParentOfType<mlir::ModuleOp>();
2897
2898 if (mlir::isa<cir::PoisonAttr>(attr)) {
2899 rewriter.replaceOpWithNewOp<mlir::LLVM::PoisonOp>(
2900 op, getTypeConverter()->convertType(op.getType()));
2901 return mlir::success();
2902 }
2903
2904 if (mlir::isa<cir::UndefAttr>(attr)) {
2905 rewriter.replaceOpWithNewOp<mlir::LLVM::UndefOp>(
2906 op, getTypeConverter()->convertType(op.getType()));
2907 return mlir::success();
2908 }
2909
2910 if (mlir::isa<mlir::IntegerType>(op.getType())) {
2911 // Verified cir.const operations cannot actually be of these types, but the
2912 // lowering pass may generate temporary cir.const operations with these
2913 // types. This is OK since MLIR allows unverified operations to be alive
2914 // during a pass as long as they don't live past the end of the pass.
2915 attr = op.getValue();
2916 } else if (mlir::isa<cir::BoolType>(op.getType())) {
2917 int value = mlir::cast<cir::BoolAttr>(op.getValue()).getValue();
2918 attr = rewriter.getIntegerAttr(typeConverter->convertType(op.getType()),
2919 value);
2920 } else if (mlir::isa<cir::IntType>(op.getType())) {
2921 // Lower GlobalViewAttr to llvm.mlir.addressof + llvm.mlir.ptrtoint and
2922 // BlockAddrDiffAttr to the difference of two llvm.blockaddress.
2923 if (mlir::isa<cir::GlobalViewAttr, cir::BlockAddrDiffAttr>(op.getValue())) {
2924 auto newOp = lowerCirAttrAsValue(
2925 op->getLoc(), moduleOp, op.getValue(), rewriter, symbolTables,
2926 getTypeConverter(), preConversionTypes, &blockInfoAddr);
2927 rewriter.replaceOp(op, newOp);
2928 return mlir::success();
2929 }
2930
2931 attr = rewriter.getIntegerAttr(
2932 typeConverter->convertType(op.getType()),
2933 mlir::cast<cir::IntAttr>(op.getValue()).getValue());
2934 } else if (mlir::isa<cir::FPTypeInterface>(op.getType())) {
2935 attr = rewriter.getFloatAttr(
2936 typeConverter->convertType(op.getType()),
2937 mlir::cast<cir::FPAttr>(op.getValue()).getValue());
2938 } else if (cir::isAnyOpaqueFloatingPointType(op.getType())) {
2939 rewriter.replaceOpWithNewOp<mlir::LLVM::ZeroOp>(
2940 op, typeConverter->convertType(op.getType()));
2941 return mlir::success();
2942 } else if (mlir::isa<cir::PointerType>(op.getType())) {
2943 // Optimize with dedicated LLVM op for null pointers.
2944 if (mlir::isa<cir::ConstPtrAttr>(op.getValue())) {
2945 if (mlir::cast<cir::ConstPtrAttr>(op.getValue()).isNullValue()) {
2946 rewriter.replaceOpWithNewOp<mlir::LLVM::ZeroOp>(
2947 op, typeConverter->convertType(op.getType()));
2948 return mlir::success();
2949 }
2950 }
2951 // Lower GlobalViewAttr and GlobalOffsetAttr to llvm.mlir.addressof,
2952 // non-null ConstPtrAttr to llvm.inttoptr and BlockAddrInfoAttr to
2953 // llvm.blockaddress.
2954 if (mlir::isa<cir::GlobalViewAttr, cir::GlobalOffsetAttr, cir::ConstPtrAttr,
2955 cir::BlockAddrInfoAttr>(op.getValue())) {
2956 auto newOp = lowerCirAttrAsValue(
2957 op->getLoc(), moduleOp, op.getValue(), rewriter, symbolTables,
2958 getTypeConverter(), preConversionTypes, &blockInfoAddr);
2959 if (!newOp)
2960 return mlir::failure();
2961 rewriter.replaceOp(op, newOp);
2962 return mlir::success();
2963 }
2964 attr = op.getValue();
2965 } else if (const auto arrTy = mlir::dyn_cast<cir::ArrayType>(op.getType())) {
2966 // Unlike a global initializer, the constant must keep its type.
2967 mlir::Attribute value = spellOutSplitTrailingZeros(op.getValue());
2968 const auto constArr = mlir::dyn_cast<cir::ConstArrayAttr>(value);
2969 if (!constArr && !isa<cir::ZeroAttr, cir::UndefAttr>(value))
2970 return op.emitError() << "array does not have a constant initializer";
2971
2972 std::optional<mlir::Attribute> denseAttr;
2973 if (constArr &&
2974 (denseAttr = lowerConstArrayAttr(constArr, symbolTables, typeConverter,
2975 preConversionTypes, moduleOp))) {
2976 attr = denseAttr.value();
2977 } else {
2978 const mlir::Value initVal =
2979 lowerCirAttrAsValue(op->getLoc(), moduleOp, value, rewriter,
2980 symbolTables, typeConverter, preConversionTypes);
2981 if (!initVal)
2982 return mlir::failure();
2983 rewriter.replaceOp(op, initVal);
2984 return mlir::success();
2985 }
2986 } else if (const auto recordAttr =
2987 mlir::dyn_cast<cir::ConstRecordAttr>(op.getValue())) {
2988 auto initVal = lowerCirAttrAsValue(
2989 op->getLoc(), moduleOp, spellOutSplitTrailingZeros(recordAttr),
2990 rewriter, symbolTables, typeConverter, preConversionTypes);
2991 if (!initVal)
2992 return mlir::failure();
2993 rewriter.replaceOp(op, initVal);
2994 return mlir::success();
2995 } else if (const auto vecTy = mlir::dyn_cast<cir::VectorType>(op.getType())) {
2996 mlir::Value initVal = lowerCirAttrAsValue(
2997 op->getLoc(), moduleOp, op.getValue(), rewriter, symbolTables,
2998 getTypeConverter(), preConversionTypes);
2999 if (!initVal)
3000 return mlir::failure();
3001 rewriter.replaceOp(op, initVal);
3002 return mlir::success();
3003 } else if (mlir::isa<cir::RecordType>(op.getType())) {
3004 if (mlir::isa<cir::ZeroAttr, cir::UndefAttr>(attr)) {
3005 mlir::Value initVal =
3006 lowerCirAttrAsValue(op->getLoc(), moduleOp, attr, rewriter,
3007 symbolTables, typeConverter, preConversionTypes);
3008 if (!initVal)
3009 return mlir::failure();
3010 rewriter.replaceOp(op, initVal);
3011 return mlir::success();
3012 }
3013 return op.emitError() << "unsupported lowering for record constant type "
3014 << op.getType();
3015 } else if (auto complexTy = mlir::dyn_cast<cir::ComplexType>(op.getType())) {
3016 mlir::Type complexElemTy = complexTy.getElementType();
3017 mlir::Type complexElemLLVMTy = typeConverter->convertType(complexElemTy);
3018
3019 if (auto zeroInitAttr = mlir::dyn_cast<cir::ZeroAttr>(op.getValue())) {
3020 mlir::TypedAttr zeroAttr = rewriter.getZeroAttr(complexElemLLVMTy);
3021 mlir::ArrayAttr array = rewriter.getArrayAttr({zeroAttr, zeroAttr});
3022 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
3023 op, getTypeConverter()->convertType(op.getType()), array);
3024 return mlir::success();
3025 }
3026
3027 if (mlir::isa<cir::UndefAttr>(op.getValue())) {
3028 rewriter.replaceOpWithNewOp<mlir::LLVM::UndefOp>(
3029 op, getTypeConverter()->convertType(op.getType()));
3030 return mlir::success();
3031 }
3032
3033 auto complexAttr = mlir::cast<cir::ConstComplexAttr>(op.getValue());
3034
3035 mlir::Attribute components[2];
3036 if (mlir::isa<cir::IntType>(complexElemTy)) {
3037 components[0] = rewriter.getIntegerAttr(
3038 complexElemLLVMTy,
3039 mlir::cast<cir::IntAttr>(complexAttr.getReal()).getValue());
3040 components[1] = rewriter.getIntegerAttr(
3041 complexElemLLVMTy,
3042 mlir::cast<cir::IntAttr>(complexAttr.getImag()).getValue());
3043 } else {
3044 components[0] = rewriter.getFloatAttr(
3045 complexElemLLVMTy,
3046 mlir::cast<cir::FPAttr>(complexAttr.getReal()).getValue());
3047 components[1] = rewriter.getFloatAttr(
3048 complexElemLLVMTy,
3049 mlir::cast<cir::FPAttr>(complexAttr.getImag()).getValue());
3050 }
3051
3052 attr = rewriter.getArrayAttr(components);
3053 } else {
3054 return op.emitError() << "unsupported constant type " << op.getType();
3055 }
3056
3057 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
3058 op, getTypeConverter()->convertType(op.getType()), attr);
3059
3060 return mlir::success();
3061}
3062
3063static uint64_t getTypeAllocSize(mlir::Type type, mlir::Operation &op) {
3064 mlir::DataLayout layout(op.getParentOfType<mlir::ModuleOp>());
3065 // For LLVM purposes we treat void as u8.
3066 if (isa<cir::VoidType>(type))
3067 type = cir::IntType::get(type.getContext(), 8, /*isSigned=*/false);
3068 return layout.getTypeAllocSize(type);
3069}
3070
3071mlir::LogicalResult CIRToLLVMPrefetchOpLowering::matchAndRewrite(
3072 cir::PrefetchOp op, OpAdaptor adaptor,
3073 mlir::ConversionPatternRewriter &rewriter) const {
3074 rewriter.replaceOpWithNewOp<mlir::LLVM::Prefetch>(
3075 op, adaptor.getAddr(), adaptor.getIsWrite(), adaptor.getLocality(),
3076 /*DataCache=*/1);
3077 return mlir::success();
3078}
3079
3080mlir::LogicalResult CIRToLLVMPtrDiffOpLowering::matchAndRewrite(
3081 cir::PtrDiffOp op, OpAdaptor adaptor,
3082 mlir::ConversionPatternRewriter &rewriter) const {
3083 mlir::Type pointeeType = op.getLhs().getType().getPointee();
3084 if (!convertTypeForMemory(*getTypeConverter(), dataLayout, pointeeType))
3085 return emitTypeConversionError(op, pointeeType);
3086
3087 auto dstTy = mlir::cast<cir::IntType>(op.getType());
3088 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
3089
3090 auto lhs = mlir::LLVM::PtrToIntOp::create(rewriter, op.getLoc(), llvmDstTy,
3091 adaptor.getLhs());
3092 auto rhs = mlir::LLVM::PtrToIntOp::create(rewriter, op.getLoc(), llvmDstTy,
3093 adaptor.getRhs());
3094
3095 auto diff =
3096 mlir::LLVM::SubOp::create(rewriter, op.getLoc(), llvmDstTy, lhs, rhs);
3097
3099 uint64_t typeSize = getTypeAllocSize(pointeeType, *op);
3100
3101 // Avoid silly division by 1.
3102 mlir::Value resultVal = diff.getResult();
3103 if (typeSize != 1) {
3104 auto typeSizeVal = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
3105 llvmDstTy, typeSize);
3106
3107 if (dstTy.isUnsigned()) {
3108 auto uDiv =
3109 mlir::LLVM::UDivOp::create(rewriter, op.getLoc(), diff, typeSizeVal);
3110 uDiv.setIsExact(true);
3111 resultVal = uDiv.getResult();
3112 } else {
3113 auto sDiv =
3114 mlir::LLVM::SDivOp::create(rewriter, op.getLoc(), diff, typeSizeVal);
3115 sDiv.setIsExact(true);
3116 resultVal = sDiv.getResult();
3117 }
3118 }
3119 rewriter.replaceOp(op, resultVal);
3120 return mlir::success();
3121}
3122
3123mlir::LogicalResult CIRToLLVMExpectOpLowering::matchAndRewrite(
3124 cir::ExpectOp op, OpAdaptor adaptor,
3125 mlir::ConversionPatternRewriter &rewriter) const {
3126 // TODO(cir): do not generate LLVM intrinsics under -O0
3128
3129 std::optional<llvm::APFloat> prob = op.getProb();
3130 if (prob)
3131 rewriter.replaceOpWithNewOp<mlir::LLVM::ExpectWithProbabilityOp>(
3132 op, adaptor.getVal(), adaptor.getExpected(), prob.value());
3133 else
3134 rewriter.replaceOpWithNewOp<mlir::LLVM::ExpectOp>(op, adaptor.getVal(),
3135 adaptor.getExpected());
3136 return mlir::success();
3137}
3138
3139/// Return true for discardable CIR markers handled explicitly below.
3140static bool isHandledDiscardableFuncAttr(mlir::NamedAttribute attr) {
3141 return attr.getName() == CIRDialect::getNoReturnAttrName() ||
3142 attr.getName() == CIRDialect::getNoUnwindAttrName() ||
3143 attr.getName() == CIRDialect::getWillReturnAttrName() ||
3144 attr.getName() == CIRDialect::getStrictFPAttrName() ||
3145 attr.getName() == CIRDialect::getNoRecurseAttrName() ||
3146 attr.getName() == CIRDialect::getMustProgressAttrName() ||
3147 attr.getName() == CIRDialect::getNoBuiltinAttrName() ||
3148 attr.getName() == CIRDialect::getOptNoneAttrName() ||
3149 attr.getName() == CIRDialect::getNakedAttrName() ||
3150 attr.getName() == CIRDialect::getSYCLModuleIdAttrName() ||
3151 attr.getName() == CIRDialect::getDontCallErrorAttrName() ||
3152 attr.getName() == CIRDialect::getDontCallWarnAttrName() ||
3153 attr.getName() == CIRDialect::getRuntimeFuncAttrName();
3154}
3155
3156/// Lower `cir.func` attributes for an `LLVMFuncOp` or `LLVM::AliasOp`.
3157/// Drop attributes populated by the destination op builder. If
3158/// `includeFunctionOnlyAttrs` is false, also omit attributes that are only
3159/// valid on functions. Fails when an argument attribute's pointee type has
3160/// no memory representation.
3161mlir::LogicalResult CIRToLLVMFuncOpLowering::lowerFuncAttributes(
3162 cir::FuncOp func, bool includeFunctionOnlyAttrs,
3164 FunctionMetadataLowering metadataLowering(func.getContext());
3165 for (mlir::NamedAttribute attr : func->getDiscardableAttrs()) {
3167 continue;
3168 if (metadataLowering.lower(attr, includeFunctionOnlyAttrs))
3169 continue;
3171 result.push_back(attr);
3172 }
3173
3174 if (mlir::StringAttr visibility = func.getSymVisibilityAttr())
3175 result.emplace_back(func.getSymVisibilityAttrName(), visibility);
3176
3177 if (includeFunctionOnlyAttrs) {
3178 if (mlir::ArrayAttr argAttrs = func.getArgAttrsAttr()) {
3179 std::optional<mlir::ArrayAttr> lowered = convertTypedArgAttrs(
3180 argAttrs, *getTypeConverter(), dataLayout, getContext());
3181 if (!lowered)
3182 return func.emitError() << "NYI: lowering a byval/sret/byref "
3183 "argument whose pointee type has no "
3184 "memory representation";
3185 result.emplace_back(func.getArgAttrsAttrName(), *lowered);
3186 }
3187 if (mlir::ArrayAttr resAttrs = func.getResAttrsAttr())
3188 result.emplace_back(func.getResAttrsAttrName(), resAttrs);
3189 }
3190
3191 if (includeFunctionOnlyAttrs)
3192 metadataLowering.appendAttrs(result);
3193
3194 return mlir::success();
3195}
3196
3197mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
3198 cir::FuncOp op, llvm::StringRef aliasee, mlir::Type ty, OpAdaptor adaptor,
3199 mlir::ConversionPatternRewriter &rewriter) const {
3200 SmallVector<mlir::NamedAttribute, 4> attributes;
3201 if (mlir::failed(lowerFuncAttributes(op, /*includeFunctionOnlyAttrs=*/false,
3202 attributes)))
3203 return mlir::failure();
3204
3205 mlir::Location loc = op.getLoc();
3206 // Create the alias before replacing: without pattern rollback the
3207 // replace erases the root op immediately. The driver does not
3208 // invalidate the cached symbol table either, so build it before the
3209 // replacement exists and maintain it explicitly below.
3210 mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
3211 symbolTables.getSymbolTable(modOp);
3212 auto aliasOp = mlir::LLVM::AliasOp::create(
3213 rewriter, loc, ty, convertLinkage(op.getLinkage()), op.getName(),
3214 op.getDsoLocal(), mlir::LLVM::ThreadLocalMode::NotThreadLocal,
3215 attributes);
3216 aliasOp.setVisibility_(
3217 lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
3218 if (op.getUnnamedAddr())
3219 aliasOp.setUnnamedAddr(mlir::LLVM::UnnamedAddr::Global);
3220 {
3221 mlir::OpBuilder::InsertionGuard guard(rewriter);
3222 rewriter.createBlock(&aliasOp.getInitializerRegion());
3223 cir::CIRDataLayout cirDataLayout(
3224 aliasOp->getParentOfType<mlir::ModuleOp>());
3225 mlir::Type ptrTy = mlir::LLVM::LLVMPointerType::get(
3226 ty.getContext(), cirDataLayout.getProgramAddressSpace());
3227 auto addrOp =
3228 mlir::LLVM::AddressOfOp::create(rewriter, loc, ptrTy, aliasee);
3229 mlir::LLVM::ReturnOp::create(rewriter, loc, addrOp);
3230 }
3231 symbolTables.getSymbolTable(modOp).remove(op);
3232 rewriter.replaceOp(op, aliasOp);
3233 symbolTables.getSymbolTable(modOp).insert(aliasOp);
3234
3235 return mlir::success();
3236}
3237
3238mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewrite(
3239 cir::FuncOp op, OpAdaptor adaptor,
3240 mlir::ConversionPatternRewriter &rewriter) const {
3241
3242 cir::FuncType fnType = op.getFunctionType();
3243 bool isDsoLocal = op.getDsoLocal();
3244 mlir::TypeConverter::SignatureConversion signatureConversion(
3245 fnType.getNumInputs());
3246
3247 for (const auto &argType : llvm::enumerate(fnType.getInputs())) {
3248 mlir::Type convertedType = typeConverter->convertType(argType.value());
3249 if (!convertedType)
3250 return emitTypeConversionError(op, argType.value());
3251 signatureConversion.addInputs(argType.index(), convertedType);
3252 }
3253
3254 mlir::Type resultType =
3255 getTypeConverter()->convertType(fnType.getReturnType());
3256 if (!resultType)
3257 return emitTypeConversionError(op, fnType.getReturnType());
3258
3259 // Create the LLVM function operation.
3260 mlir::Type llvmFnTy = mlir::LLVM::LLVMFunctionType::get(
3261 resultType, signatureConversion.getConvertedTypes(),
3262 /*isVarArg=*/fnType.isVarArg());
3263
3264 // If this is an alias, it needs to be lowered to llvm::AliasOp.
3265 if (std::optional<llvm::StringRef> aliasee = op.getAliasee())
3266 return matchAndRewriteAlias(op, *aliasee, llvmFnTy, adaptor, rewriter);
3267
3268 // LLVMFuncOp expects a single FileLine Location instead of a fused
3269 // location.
3270 mlir::Location loc = op.getLoc();
3271 if (mlir::FusedLoc fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(loc))
3272 loc = fusedLoc.getLocations()[0];
3273 assert((mlir::isa<mlir::FileLineColLoc>(loc) ||
3274 mlir::isa<mlir::UnknownLoc>(loc)) &&
3275 "expected single location or unknown location here");
3276
3277 mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
3278 mlir::LLVM::CConv cconv = convertCallingConv(op.getCallingConv());
3279 SmallVector<mlir::NamedAttribute, 4> attributes;
3280 if (mlir::failed(lowerFuncAttributes(op, /*includeFunctionOnlyAttrs=*/true,
3281 attributes)))
3282 return mlir::failure();
3283
3284 // Convert the body types here: this mutates the op, so it runs after the
3285 // last fallible read above and before any op creation below. A failure
3286 // leaves the body unmoved for the driver to report.
3287 if (failed(rewriter.convertRegionTypes(&op.getBody(), *typeConverter,
3288 &signatureConversion)))
3289 return mlir::failure();
3290
3291 mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
3292
3293 // The driver does not invalidate the cached symbol table, so build it
3294 // before the replacement exists and maintain it explicitly below.
3295 mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
3296 symbolTables.getSymbolTable(modOp);
3297 mlir::LLVM::LLVMFuncOp fn = mlir::LLVM::LLVMFuncOp::create(
3298 rewriter, loc, op.getName(), llvmFnTy, linkage, isDsoLocal, cconv,
3299 comdatAttr, attributes);
3300
3302
3303 if (op.getUnnamedAddr())
3304 fn.setUnnamedAddr(mlir::LLVM::UnnamedAddr::Global);
3305
3306 if (cir::MemoryEffectsAttr effects = op.getMemoryEffectsAttr())
3307 fn.setMemoryEffectsAttr(convertMemoryEffects(fn.getContext(), effects));
3308
3309 // As for calls, either cannot-unwind fact maps to LLVM's nounwind.
3310 if (op->hasAttr(CIRDialect::getNoUnwindAttrName()) ||
3311 op->hasAttr(CIRDialect::getNoThrowAttrName()))
3312 fn.setNoUnwind(true);
3313 if (op->hasAttr(CIRDialect::getWillReturnAttrName()))
3314 fn.setWillReturn(true);
3315
3316 if (op->hasAttr(CIRDialect::getNoReturnAttrName()))
3317 fn.setNoreturn(true);
3318
3319 if (op->hasAttr(CIRDialect::getOptNoneAttrName()))
3320 fn.setOptimizeNone(true);
3321
3322 if (std::optional<cir::UnwindTableKind> uwtableKind = op.getUwtable())
3323 fn.setUwtableKindAttr(mlir::LLVM::UWTableKindAttr::get(
3324 fn.getContext(), convertUWTableKind(*uwtableKind)));
3325
3326 if (std::optional<cir::FramePointerKind> framePointerKind =
3327 op.getFramePointer())
3328 fn.setFramePointerAttr(mlir::LLVM::FramePointerKindAttr::get(
3329 fn.getContext(), convertFramePointerKind(*framePointerKind)));
3330
3331 // Function attributes with no dedicated field on the LLVM dialect's
3332 // LLVMFuncOp are routed through the `passthrough` array. The MLIR LLVM IR
3333 // translator forwards `passthrough` entries to LLVM IR as function
3334 // attributes.
3335 SmallVector<mlir::Attribute> passthrough;
3336 for (llvm::StringRef flagAttr :
3337 {CIRDialect::getStrictFPAttrName(), CIRDialect::getNoRecurseAttrName(),
3338 CIRDialect::getMustProgressAttrName(),
3339 CIRDialect::getNoBuiltinAttrName(), CIRDialect::getNakedAttrName()})
3340 if (op->hasAttr(flagAttr))
3341 passthrough.push_back(rewriter.getStringAttr(flagAttr));
3342
3343 if (auto moduleId = op->getAttrOfType<mlir::StringAttr>(
3344 CIRDialect::getSYCLModuleIdAttrName()))
3345 passthrough.push_back(rewriter.getArrayAttr(
3346 {rewriter.getStringAttr(CIRDialect::getSYCLModuleIdAttrName()),
3347 moduleId}));
3348
3349 for (llvm::StringRef dontCallAttr : {CIRDialect::getDontCallErrorAttrName(),
3350 CIRDialect::getDontCallWarnAttrName()})
3351 if (auto diagnostic = op->getAttrOfType<mlir::StringAttr>(dontCallAttr))
3352 passthrough.push_back(rewriter.getArrayAttr(
3353 {rewriter.getStringAttr(dontCallAttr), diagnostic}));
3354
3355 // Every function but a runtime function gets the TU-wide default function
3356 // attributes.
3357 if (!op->hasAttr(CIRDialect::getRuntimeFuncAttrName())) {
3358 if (auto langOpts = op->getParentOfType<mlir::ModuleOp>()
3359 ->getAttrOfType<cir::LoweringOptionsAttr>(
3360 CIRDialect::getLoweringOptionsAttrName())) {
3361 // A strictfp function may use a pragma to observe FP exceptions locally,
3362 // so the TU-wide default does not apply to it.
3363 if (langOpts.getNoTrappingMath() &&
3364 !op->hasAttr(CIRDialect::getStrictFPAttrName()))
3365 passthrough.push_back(
3366 rewriter.getStrArrayAttr({"no-trapping-math", "true"}));
3367 passthrough.push_back(rewriter.getStrArrayAttr(
3368 {"stack-protector-buffer-size",
3369 llvm::utostr(langOpts.getSspBufferSize())}));
3370 }
3371 }
3372
3373 if (op.getCoroutineKind())
3374 passthrough.push_back(rewriter.getStringAttr("presplitcoroutine"));
3375 if (!passthrough.empty())
3376 fn.setPassthroughAttr(rewriter.getArrayAttr(passthrough));
3377
3378 if (std::optional<cir::InlineKind> inlineKind = op.getInlineKind()) {
3379 fn.setNoInline(*inlineKind == cir::InlineKind::NoInline);
3380 fn.setInlineHint(*inlineKind == cir::InlineKind::InlineHint);
3381 fn.setAlwaysInline(*inlineKind == cir::InlineKind::AlwaysInline);
3382 }
3383
3384 if (std::optional<llvm::StringRef> personality = op.getPersonality())
3385 fn.setPersonality(*personality);
3386
3387 fn.setVisibility_(
3388 lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
3389
3390 fn.setAlignment(op.getAlignment());
3392
3393 symbolTables.getSymbolTable(modOp).remove(op);
3394 rewriter.inlineRegionBefore(op.getBody(), fn.getBody(), fn.end());
3395
3396 rewriter.eraseOp(op);
3397 symbolTables.getSymbolTable(modOp).insert(fn);
3398
3399 return mlir::LogicalResult::success();
3400}
3401
3402mlir::LogicalResult CIRToLLVMGetGlobalOpLowering::matchAndRewrite(
3403 cir::GetGlobalOp op, OpAdaptor adaptor,
3404 mlir::ConversionPatternRewriter &rewriter) const {
3405 // FIXME(cir): Premature DCE to avoid lowering stuff we're not using.
3406 // CIRGen should mitigate this and not emit the get_global.
3407 if (op->getUses().empty()) {
3408 rewriter.eraseOp(op);
3409 return mlir::success();
3410 }
3411
3412 mlir::Type type = getTypeConverter()->convertType(op.getType());
3413 if (!type)
3414 return emitTypeConversionError(op, op.getType());
3415 mlir::Operation *newop = mlir::LLVM::AddressOfOp::create(
3416 rewriter, op.getLoc(), type, op.getName());
3417
3418 if (op.getTls()) {
3419 // Handle access to TLS via intrinsic.
3420 newop = mlir::LLVM::ThreadlocalAddressOp::create(rewriter, op.getLoc(),
3421 type, newop->getResult(0));
3422 }
3423
3424 rewriter.replaceOp(op, newop);
3425 return mlir::success();
3426}
3427
3428llvm::SmallVector<mlir::NamedAttribute>
3429CIRToLLVMGlobalOpLowering::lowerGlobalAttributes(
3430 cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const {
3431 SmallVector<mlir::NamedAttribute> attributes;
3432
3433 if (mlir::StringAttr sectionAttr = op.getSectionAttr())
3434 attributes.push_back(rewriter.getNamedAttr("section", sectionAttr));
3435
3436 mlir::LLVM::VisibilityAttr visibility = mlir::LLVM::VisibilityAttr::get(
3437 getContext(),
3438 lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
3439 attributes.push_back(rewriter.getNamedAttr("visibility_", visibility));
3440
3441 if (op.getUnnamedAddr())
3442 attributes.push_back(rewriter.getNamedAttr(
3443 "unnamed_addr", mlir::LLVM::UnnamedAddrAttr::get(
3444 getContext(), mlir::LLVM::UnnamedAddr::Global)));
3445
3446 if (op->getAttr(CUDAExternallyInitializedAttr::getMnemonic()))
3447 attributes.push_back(rewriter.getNamedAttr("externally_initialized",
3448 rewriter.getUnitAttr()));
3449
3450 return attributes;
3451}
3452
3453static mlir::LLVM::ThreadLocalMode
3454convertTlsModelAttrToLLVM(TLSModelAttr attr) {
3455 // assert that we can just static-cast these.
3456#define CHECK_ENUM(CIR, LLVM_VAL) \
3457 static_assert(static_cast<unsigned>(TLSModel::CIR) == \
3458 static_cast<unsigned>(mlir::LLVM::ThreadLocalMode::LLVM_VAL))
3459 CHECK_ENUM(GeneralDynamic, GeneralDynamic);
3460 CHECK_ENUM(LocalDynamic, LocalDynamic);
3461 CHECK_ENUM(InitialExec, InitialExec);
3462 CHECK_ENUM(LocalExec, LocalExec);
3463#undef CHECK_ENUM
3464
3465 if (!attr)
3466 return mlir::LLVM::ThreadLocalMode::NotThreadLocal;
3467
3468 return static_cast<mlir::LLVM::ThreadLocalMode>(attr.getValue());
3469}
3470
3471/// Create the region-initialized LLVM global beside the CIR op and update
3472/// insertion point to the end of the initializer block. Returns the new op,
3473/// or null on failure. The caller owns the replacement: it runs the
3474/// initializer visit with the old op still in the table, then swaps the
3475/// table and erases the old op on success.
3476mlir::LLVM::GlobalOp
3477CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
3478 cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const {
3479 mlir::Type llvmType =
3480 convertTypeForMemory(*getTypeConverter(), dataLayout, op.getSymType());
3481
3482 // Keep the global's type in sync with the value built by CIRAttrToValue: a
3483 // flexible array member initializer requires an oversized anonymous struct.
3484 mlir::Type failedType = op.getSymType();
3485 if (std::optional<mlir::Attribute> init = op.getInitialValue())
3486 llvmType = adjustGlobalTypeForInit(llvmType, *init, *getTypeConverter(),
3487 dataLayout, &failedType);
3488 if (!llvmType) {
3489 emitTypeConversionError(op, failedType);
3490 return {};
3491 }
3492
3493 // FIXME: These default values are placeholders until the the equivalent
3494 // attributes are available on cir.global ops. This duplicates code
3495 // in CIRToLLVMGlobalOpLowering::matchAndRewrite() but that will go
3496 // away when the placeholders are no longer needed.
3497 const bool isConst = op.getConstant();
3498 unsigned addrSpace = 0;
3499 if (auto targetAS = mlir::dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
3500 op.getAddrSpaceAttr()))
3501 addrSpace = targetAS.getValue();
3502 const bool isDsoLocal = op.getDsoLocal();
3503 mlir::LLVM::ThreadLocalMode threadLocalMode =
3504 convertTlsModelAttrToLLVM(op.getTlsModelAttr());
3505 const uint64_t alignment = op.getAlignment().value_or(0);
3506 const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
3507 const StringRef symbol = op.getSymName();
3508
3509 SmallVector<mlir::NamedAttribute> attributes =
3510 lowerGlobalAttributes(op, rewriter);
3511
3512 mlir::LLVM::GlobalOp newGlobalOp = mlir::LLVM::GlobalOp::create(
3513 rewriter, op.getLoc(), llvmType, isConst, linkage, symbol, nullptr,
3514 alignment, addrSpace, isDsoLocal, threadLocalMode, mlir::SymbolRefAttr{},
3515 attributes);
3516 rewriter.createBlock(&newGlobalOp.getRegion());
3517 rewriter.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
3518 return newGlobalOp;
3519}
3520
3521mlir::LogicalResult
3522CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
3523 cir::GlobalOp op, mlir::Attribute init,
3524 mlir::ConversionPatternRewriter &rewriter) const {
3525 // TODO: Generalize this handling when more types are needed here.
3526 assert((isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
3527 cir::ConstArrayAttr, cir::ConstRecordAttr, cir::ConstVectorAttr,
3528 cir::ConstPtrAttr, cir::ConstComplexAttr, cir::GlobalOffsetAttr,
3529 cir::GlobalViewAttr, cir::TypeInfoAttr, cir::UndefAttr,
3530 cir::PoisonAttr, cir::VTableAttr, cir::ZeroAttr>(init)));
3531
3532 // TODO(cir): once LLVM's dialect has proper equivalent attributes this
3533 // should be updated. For now, we use a custom op to initialize globals
3534 // to the appropriate value.
3535 const mlir::Location loc = op.getLoc();
3536 mlir::ModuleOp moduleOp = op->getParentOfType<mlir::ModuleOp>();
3537 // Build the cached table before the replacement exists, so the swap below
3538 // drops a real entry instead of depending on duplicate tolerance.
3539 auto &symbolTable = symbolTables.getSymbolTable(moduleOp);
3540 // Create the replacement beside the root op, not via replaceOp: the table
3541 // swap below and the visit both need the old op alive.
3542 rewriter.setInsertionPoint(op);
3543 mlir::LLVM::GlobalOp newGlobalOp =
3544 setupRegionInitializedLLVMGlobalOp(op, rewriter);
3545 if (!newGlobalOp)
3546 return mlir::failure();
3547 // Keep the old op in the table during the visit so self-references
3548 // resolve to the CIR type, not the possibly adjusted LLVM type.
3549 // Pass blockInfoAddr so that block address initializers (either as the whole
3550 // initializer or nested inside an aggregate) can be resolved by the
3551 // BlockAddrInfoAttr visitor.
3552 CIRAttrToValue valueConverter(loc, moduleOp, rewriter, symbolTables,
3553 typeConverter, preConversionTypes,
3554 &blockInfoAddr);
3555 mlir::Value value = valueConverter.visit(init);
3556 if (!value) {
3557 // Drop the speculative replacement; the table still holds the live
3558 // root op for the driver to report on. Everything created so far
3559 // lives inside the new global's region, so erasing it restores the
3560 // module exactly: module-level ops must wait for a successful visit
3561 // (see the comdat below).
3562 rewriter.eraseOp(newGlobalOp);
3563 return mlir::failure();
3564 }
3565 mlir::LLVM::ReturnOp::create(rewriter, loc, value);
3566 // Attach comdat only after the visit succeeds, so the failure path
3567 // above only has the new global itself to drop.
3568 if (mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter))
3569 newGlobalOp.setComdatAttr(comdatAttr);
3570 symbolTable.remove(op);
3571 symbolTable.insert(newGlobalOp);
3572 rewriter.eraseOp(op);
3573 return mlir::success();
3574}
3575
3576// Replace a CIR global with an LLVM global, maintaining the cached symbol
3577// table. The table entry is dropped before creation so the replacement
3578// reuses the name.
3579static mlir::LLVM::GlobalOp
3580replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op,
3581 mlir::Type llvmType, bool isConst, mlir::LLVM::Linkage linkage,
3582 llvm::StringRef symbol, mlir::Attribute init,
3583 uint64_t alignment, unsigned addrSpace, bool isDsoLocal,
3584 mlir::LLVM::ThreadLocalMode threadLocalMode,
3585 mlir::SymbolRefAttr comdatAttr,
3587 mlir::ConversionPatternRewriter &rewriter) {
3588 mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
3589 symbolTables.getSymbolTable(modOp).remove(op);
3590 auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
3591 op, llvmType, isConst, linkage, symbol, init, alignment, addrSpace,
3592 isDsoLocal, threadLocalMode, comdatAttr, attributes);
3593 symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
3594 return newGlobalOp;
3595}
3596
3597mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
3598 cir::GlobalOp op, OpAdaptor adaptor,
3599 mlir::ConversionPatternRewriter &rewriter) const {
3600 if (mlir::isa_and_present<cir::LangAddressSpaceAttr>(op.getAddrSpaceAttr()))
3601 return op.emitError()
3602 << "cannot lower a global with a language address space";
3603
3604 // If this global requires non-trivial initialization or destruction,
3605 // that needs to be moved to runtime handlers during LoweringPrepare.
3606 if (!op.getCtorRegion().empty() || !op.getDtorRegion().empty())
3607 return op.emitError() << "GlobalOp ctor and dtor regions should be removed "
3608 "in LoweringPrepare";
3609
3610 std::optional<mlir::Attribute> init = op.getInitialValue();
3611
3612 // Fetch required values to create LLVM op.
3613 const mlir::Type cirSymType = op.getSymType();
3614
3615 // This is the LLVM dialect type.
3616 mlir::Type llvmType =
3617 convertTypeForMemory(*getTypeConverter(), dataLayout, cirSymType);
3618 if (!llvmType)
3619 return op.emitError()
3620 << "NYI: lowering global of a type with no memory representation";
3621
3622 // A flexible array member initializer makes the constant larger than the
3623 // record's declared type, so the global must use an oversized anonymous
3624 // struct instead.
3625 mlir::Type failedType = cirSymType;
3626 if (init.has_value())
3627 llvmType = adjustGlobalTypeForInit(llvmType, *init, *getTypeConverter(),
3628 dataLayout, &failedType);
3629 if (!llvmType)
3630 return emitTypeConversionError(op, failedType);
3631
3632 // FIXME: These default values are placeholders until the the equivalent
3633 // attributes are available on cir.global ops.
3634 const bool isConst = op.getConstant();
3635 unsigned addrSpace = 0;
3636 if (auto targetAS = mlir::dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
3637 op.getAddrSpaceAttr()))
3638 addrSpace = targetAS.getValue();
3639 const bool isDsoLocal = op.getDsoLocal();
3640 mlir::LLVM::ThreadLocalMode threadLocalMode =
3641 convertTlsModelAttrToLLVM(op.getTlsModelAttr());
3642 const uint64_t alignment = op.getAlignment().value_or(0);
3643 const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
3644 const StringRef symbol = op.getSymName();
3646 lowerGlobalAttributes(op, rewriter);
3647
3648 // If this is a variable alias, lower it to llvm.mlir.alias.
3649 if (std::optional<llvm::StringRef> aliasee = op.getAliasee()) {
3650 mlir::Location loc = op.getLoc();
3651 // Create the alias before replacing: without pattern rollback the
3652 // replace erases the root op immediately. The driver does not
3653 // invalidate the cached symbol table either, so build it before the
3654 // replacement exists and maintain it explicitly below.
3655 mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
3656 symbolTables.getSymbolTable(modOp);
3657 auto aliasOp =
3658 mlir::LLVM::AliasOp::create(rewriter, loc, llvmType, linkage, symbol,
3659 isDsoLocal, threadLocalMode, attributes);
3660 {
3661 mlir::OpBuilder::InsertionGuard guard(rewriter);
3662 rewriter.createBlock(&aliasOp.getInitializerRegion());
3663 mlir::Type ptrTy =
3664 mlir::LLVM::LLVMPointerType::get(getContext(), addrSpace);
3665 auto addrOp =
3666 mlir::LLVM::AddressOfOp::create(rewriter, loc, ptrTy, *aliasee);
3667 mlir::LLVM::ReturnOp::create(rewriter, loc, addrOp);
3668 }
3669 symbolTables.getSymbolTable(modOp).remove(op);
3670 rewriter.replaceOp(op, aliasOp);
3671 symbolTables.getSymbolTable(modOp).insert(aliasOp);
3672 return mlir::success();
3673 }
3674
3675 if (init.has_value()) {
3676 if (mlir::isa<cir::FPAttr, cir::IntAttr, cir::BoolAttr>(init.value())) {
3677 GlobalInitAttrRewriter initRewriter(llvmType, dataLayout, rewriter);
3678 init = initRewriter.visit(init.value());
3679 // If initRewriter returned a null attribute, init will have a value but
3680 // the value will be null. If that happens, initRewriter didn't handle the
3681 // attribute type. It probably needs to be added to
3682 // GlobalInitAttrRewriter.
3683 if (!init.value()) {
3684 op.emitError() << "unsupported initializer '" << init.value() << "'";
3685 return mlir::failure();
3686 }
3687 } else if (auto constArr =
3688 mlir::dyn_cast<cir::ConstArrayAttr>(init.value())) {
3689 // Bulk-emit llvm.mlir.global when lowerConstArrayAttr can build the
3690 // whole initializer as one aggregate attribute (no insertvalue
3691 // region). Leaf type must match what lowerConstArrayAttr handles
3692 // (pointers, integers, bools, floats, and string literals with
3693 // trailing_zeros).
3695 getConstArrayBaseElementType(constArr.getType()))) {
3696 mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
3697 if (std::optional<mlir::Attribute> bulkInit =
3698 lowerConstArrayAttr(constArr, symbolTables, typeConverter,
3699 preConversionTypes, modOp)) {
3700 mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
3701 replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
3702 bulkInit.value(), alignment, addrSpace, isDsoLocal,
3703 threadLocalMode, comdatAttr, attributes, rewriter);
3704 return mlir::success();
3705 }
3706 }
3707 return matchAndRewriteRegionInitializedGlobal(op, init.value(), rewriter);
3708 } else if (auto constRecord =
3709 mlir::dyn_cast<cir::ConstRecordAttr>(init.value())) {
3710 // Bulk-emit llvm.mlir.global when every member of the record can be
3711 // lowered to a constant attribute. The LLVM dialect global translation
3712 // turns an ArrayAttr (one element per struct field) into an
3713 // llvm::ConstantStruct, so the whole initializer becomes a single
3714 // attribute on the global instead of an insertvalue region.
3715 mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
3716 if (std::optional<mlir::Attribute> bulkInit =
3717 lowerConstRecordAttr(constRecord, symbolTables, typeConverter,
3718 preConversionTypes, modOp)) {
3719 mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
3720 replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
3721 bulkInit.value(), alignment, addrSpace, isDsoLocal,
3722 threadLocalMode, comdatAttr, attributes, rewriter);
3723 return mlir::success();
3724 }
3725 return matchAndRewriteRegionInitializedGlobal(op, init.value(), rewriter);
3726 } else if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
3727 cir::ConstVectorAttr, cir::ConstRecordAttr,
3728 cir::ConstPtrAttr, cir::ConstComplexAttr,
3729 cir::GlobalOffsetAttr, cir::GlobalViewAttr,
3730 cir::TypeInfoAttr, cir::UndefAttr, cir::PoisonAttr,
3731 cir::VTableAttr, cir::ZeroAttr>(init.value())) {
3732 // TODO(cir): once LLVM's dialect has proper equivalent attributes this
3733 // should be updated. For now, we use a custom op to initialize globals
3734 // to the appropriate value.
3735 return matchAndRewriteRegionInitializedGlobal(op, init.value(), rewriter);
3736 } else {
3737 // We will only get here if new initializer types are added and this
3738 // code is not updated to handle them.
3739 op.emitError() << "unsupported initializer '" << init.value() << "'";
3740 return mlir::failure();
3741 }
3742 }
3743
3744 mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
3745 replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
3746 init.value_or(mlir::Attribute()), alignment, addrSpace,
3747 isDsoLocal, threadLocalMode, comdatAttr, attributes,
3748 rewriter);
3749
3750 return mlir::success();
3751}
3752
3753static mlir::SymbolRefAttr
3754getComdatAttrHelper(mlir::ModuleOp modOp, mlir::OpBuilder &builder,
3755 StringRef symName, mlir::LLVM::ComdatOp &comdatOp,
3756 mlir::SymbolTableCollection &symbolTables) {
3757 mlir::OpBuilder::InsertionGuard guard(builder);
3758 StringRef comdatName = "__llvm_comdat";
3759 if (!comdatOp) {
3760 // The GlobalOp and FuncOp lowering patterns each cache their own
3761 // 'comdatOp', but both now share a single module-level comdat region, so
3762 // whichever pattern gets here second has to find the existing one rather
3763 // than create a duplicate symbol.
3764 comdatOp = modOp.lookupSymbol<mlir::LLVM::ComdatOp>(comdatName);
3765 }
3766
3767 if (!comdatOp) {
3768 builder.setInsertionPointToStart(modOp.getBody());
3769 comdatOp =
3770 mlir::LLVM::ComdatOp::create(builder, modOp.getLoc(), comdatName);
3771 }
3772
3773 // Cached, and shared by both patterns: a linear scan of the comdat region
3774 // per symbol is quadratic in the number of comdats.
3775 mlir::SymbolTable &selectors = symbolTables.getSymbolTable(comdatOp);
3776 if (auto comdatSelector =
3777 selectors.lookup<mlir::LLVM::ComdatSelectorOp>(symName)) {
3778 return mlir::SymbolRefAttr::get(
3779 builder.getContext(), comdatName,
3780 mlir::FlatSymbolRefAttr::get(comdatSelector.getSymNameAttr()));
3781 }
3782
3783 builder.setInsertionPointToStart(&comdatOp.getBody().back());
3784 auto selectorOp = mlir::LLVM::ComdatSelectorOp::create(
3785 builder, comdatOp.getLoc(), symName, mlir::LLVM::comdat::Comdat::Any,
3786 /*sym_visibility=*/nullptr);
3787 selectors.insert(selectorOp);
3788 return mlir::SymbolRefAttr::get(
3789 builder.getContext(), comdatName,
3790 mlir::FlatSymbolRefAttr::get(selectorOp.getSymNameAttr()));
3791}
3792
3793mlir::SymbolRefAttr
3794CIRToLLVMGlobalOpLowering::getComdatAttr(cir::GlobalOp &op,
3795 mlir::OpBuilder &builder) const {
3796 std::optional<llvm::StringRef> comdat = op.getComdat();
3797 if (!comdat)
3798 return mlir::SymbolRefAttr{};
3799 llvm::StringRef comdatKey = comdat->empty() ? op.getSymName() : *comdat;
3800 return getComdatAttrHelper(op->getParentOfType<mlir::ModuleOp>(), builder,
3801 comdatKey, comdatOp, symbolTables);
3802}
3803
3804mlir::SymbolRefAttr
3805CIRToLLVMFuncOpLowering::getComdatAttr(cir::FuncOp &op,
3806 mlir::OpBuilder &builder) const {
3807 std::optional<llvm::StringRef> comdat = op.getComdat();
3808 if (!comdat)
3809 return mlir::SymbolRefAttr{};
3810 llvm::StringRef comdatKey = comdat->empty() ? op.getSymName() : *comdat;
3811 return getComdatAttrHelper(op->getParentOfType<mlir::ModuleOp>(), builder,
3812 comdatKey, comdatOp, symbolTables);
3813}
3814
3815mlir::LogicalResult CIRToLLVMSwitchFlatOpLowering::matchAndRewrite(
3816 cir::SwitchFlatOp op, OpAdaptor adaptor,
3817 mlir::ConversionPatternRewriter &rewriter) const {
3818
3819 llvm::SmallVector<mlir::APInt, 8> caseValues;
3820 for (mlir::Attribute val : op.getCaseValues()) {
3821 auto intAttr = cast<cir::IntAttr>(val);
3822 caseValues.push_back(intAttr.getValue());
3823 }
3824
3825 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
3826
3827 for (mlir::Block *x : op.getCaseDestinations())
3828 caseDestinations.push_back(x);
3829
3830 // Use the converted operands so they match the type-converted successor
3831 // block arguments.
3832 llvm::SmallVector<mlir::ValueRange> caseOperands = adaptor.getCaseOperands();
3833
3834 // Set switch op to branch to the newly created blocks.
3835 rewriter.setInsertionPoint(op);
3836 rewriter.replaceOpWithNewOp<mlir::LLVM::SwitchOp>(
3837 op, adaptor.getCondition(), op.getDefaultDestination(),
3838 adaptor.getDefaultOperands(), caseValues, caseDestinations, caseOperands);
3839 return mlir::success();
3840}
3841
3842static mlir::LLVM::IntegerOverflowFlags nswFlag(bool nsw) {
3843 return nsw ? mlir::LLVM::IntegerOverflowFlags::nsw
3844 : mlir::LLVM::IntegerOverflowFlags::none;
3845}
3846
3847template <typename CIROp, typename LLVMIntOp>
3848static mlir::LogicalResult
3849lowerIncDecOp(CIROp op, typename CIROp::Adaptor adaptor,
3850 mlir::ConversionPatternRewriter &rewriter) {
3851 mlir::Type llvmType = adaptor.getInput().getType();
3852 mlir::Location loc = op.getLoc();
3853
3854 auto maybeNSW = nswFlag(op.getNoSignedWrap());
3855 mlir::LLVM::ConstantOp one;
3856 if (mlir::isa<cir::VectorType>(op.getType())) {
3857 mlir::ShapedType shapedTy = mlir::cast<mlir::ShapedType>(llvmType);
3858 mlir::APInt oneAP(shapedTy.getElementTypeBitWidth(), 1);
3859 auto oneVec = mlir::DenseElementsAttr::get(shapedTy, {oneAP});
3860 one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, oneVec);
3861 } else {
3862 one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 1);
3863 }
3864 rewriter.replaceOpWithNewOp<LLVMIntOp>(op, adaptor.getInput(), one, maybeNSW);
3865 return mlir::success();
3866}
3867
3868mlir::LogicalResult CIRToLLVMIncOpLowering::matchAndRewrite(
3869 cir::IncOp op, OpAdaptor adaptor,
3870 mlir::ConversionPatternRewriter &rewriter) const {
3871 return lowerIncDecOp<cir::IncOp, mlir::LLVM::AddOp>(op, adaptor, rewriter);
3872}
3873
3874mlir::LogicalResult CIRToLLVMDecOpLowering::matchAndRewrite(
3875 cir::DecOp op, OpAdaptor adaptor,
3876 mlir::ConversionPatternRewriter &rewriter) const {
3877 return lowerIncDecOp<cir::DecOp, mlir::LLVM::SubOp>(op, adaptor, rewriter);
3878}
3879
3880mlir::LogicalResult CIRToLLVMMinusOpLowering::matchAndRewrite(
3881 cir::MinusOp op, OpAdaptor adaptor,
3882 mlir::ConversionPatternRewriter &rewriter) const {
3883 bool isVector = mlir::isa<cir::VectorType>(op.getType());
3884 mlir::Type llvmType = adaptor.getInput().getType();
3885 mlir::Location loc = op.getLoc();
3886
3887 auto maybeNSW = nswFlag(op.getNoSignedWrap());
3888 mlir::Value zero;
3889 if (isVector)
3890 zero = mlir::LLVM::ZeroOp::create(rewriter, loc, llvmType);
3891 else
3892 zero = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 0);
3893 rewriter.replaceOpWithNewOp<mlir::LLVM::SubOp>(op, zero, adaptor.getInput(),
3894 maybeNSW);
3895 return mlir::success();
3896}
3897
3898mlir::LogicalResult CIRToLLVMNotOpLowering::matchAndRewrite(
3899 cir::NotOp op, OpAdaptor adaptor,
3900 mlir::ConversionPatternRewriter &rewriter) const {
3901 mlir::Type elementType = elementTypeIfVectorOrMatrix(op.getType());
3902 bool isVector = mlir::isa<cir::VectorType>(op.getType());
3903 mlir::Type llvmType = adaptor.getInput().getType();
3904 mlir::Location loc = op.getLoc();
3905
3906 if (mlir::isa<cir::IntType>(elementType)) {
3907 mlir::Value minusOne;
3908 if (isVector) {
3909 const unsigned eltWidth =
3910 mlir::cast<cir::IntType>(elementType).getWidth();
3911 mlir::DenseElementsAttr denseVec =
3912 mlir::DenseElementsAttr::get(mlir::cast<mlir::ShapedType>(llvmType),
3913 {APInt::getAllOnes(eltWidth)});
3914 minusOne =
3915 mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, denseVec);
3916 } else {
3917 minusOne = mlir::LLVM::ConstantOp::create(
3918 rewriter, loc, llvmType,
3919 APInt::getAllOnes(cast<mlir::IntegerType>(llvmType).getWidth()));
3920 }
3921 rewriter.replaceOpWithNewOp<mlir::LLVM::XOrOp>(op, adaptor.getInput(),
3922 minusOne);
3923 return mlir::success();
3924 }
3925
3926 if (mlir::isa<cir::BoolType>(elementType)) {
3927 mlir::Value one;
3928 if (isVector) {
3929 mlir::DenseElementsAttr denseVec = mlir::DenseElementsAttr::get(
3930 mlir::cast<mlir::ShapedType>(llvmType), {APInt(1, 1)});
3931 one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, denseVec);
3932 } else {
3933 one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 1);
3934 }
3935 rewriter.replaceOpWithNewOp<mlir::LLVM::XOrOp>(op, adaptor.getInput(), one);
3936 return mlir::success();
3937 }
3938
3939 return op.emitError() << "Unsupported type for bitwise NOT";
3940}
3941
3942static bool isIntTypeUnsigned(mlir::Type type) {
3943 // TODO: Ideally, we should only need to check cir::IntType here.
3944 return mlir::isa<cir::IntType>(type)
3945 ? mlir::cast<cir::IntType>(type).isUnsigned()
3946 : mlir::cast<mlir::IntegerType>(type).isUnsigned();
3947}
3948
3949//===----------------------------------------------------------------------===//
3950// Binary Op Lowering
3951//===----------------------------------------------------------------------===//
3952
3953mlir::LLVM::IntegerOverflowFlags
3954convertToLLVMProperty(mlir::MLIRContext *, cir::OverflowFlags flags) {
3955 mlir::LLVM::IntegerOverflowFlags result =
3956 mlir::LLVM::IntegerOverflowFlags::none;
3957 if (bitEnumContainsAny(flags, cir::OverflowFlags::NoSignedWrap))
3958 result = result | mlir::LLVM::IntegerOverflowFlags::nsw;
3959 if (bitEnumContainsAny(flags, cir::OverflowFlags::NoUnsignedWrap))
3960 result = result | mlir::LLVM::IntegerOverflowFlags::nuw;
3961 return result;
3962}
3963
3964/// Lower an integer op to its signed or unsigned LLVM counterpart.
3965template <typename UIntOp, typename SIntOp, typename CIROp>
3966static mlir::LogicalResult
3967lowerIntBinaryOp(CIROp op, mlir::Value lhs, mlir::Value rhs,
3968 mlir::ConversionPatternRewriter &rewriter) {
3969 const mlir::Type eltType = elementTypeIfVectorOrMatrix(op.getRhs().getType());
3970 assert(cir::isIntOrBoolType(eltType) &&
3971 "integer binary op expects integer operand types");
3972 if (isIntTypeUnsigned(eltType))
3973 rewriter.replaceOpWithNewOp<UIntOp>(op, lhs, rhs);
3974 else
3975 rewriter.replaceOpWithNewOp<SIntOp>(op, lhs, rhs);
3976 return mlir::success();
3977}
3978
3979mlir::LogicalResult CIRToLLVMAddSatOpLowering::matchAndRewrite(
3980 cir::AddSatOp op, OpAdaptor adaptor,
3981 mlir::ConversionPatternRewriter &rewriter) const {
3983 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
3984}
3985
3986mlir::LogicalResult CIRToLLVMSubSatOpLowering::matchAndRewrite(
3987 cir::SubSatOp op, OpAdaptor adaptor,
3988 mlir::ConversionPatternRewriter &rewriter) const {
3990 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
3991}
3992
3993mlir::LogicalResult CIRToLLVMDivOpLowering::matchAndRewrite(
3994 cir::DivOp op, OpAdaptor adaptor,
3995 mlir::ConversionPatternRewriter &rewriter) const {
3997 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
3998}
3999
4000mlir::LogicalResult CIRToLLVMRemOpLowering::matchAndRewrite(
4001 cir::RemOp op, OpAdaptor adaptor,
4002 mlir::ConversionPatternRewriter &rewriter) const {
4004 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
4005}
4006
4007template <typename CIROp, typename UIntOp, typename SIntOp>
4008static mlir::LogicalResult
4009lowerMinMaxOp(CIROp op, typename CIROp::Adaptor adaptor,
4010 mlir::ConversionPatternRewriter &rewriter) {
4011 const mlir::Value lhs = adaptor.getLhs();
4012 const mlir::Value rhs = adaptor.getRhs();
4013 if (isIntTypeUnsigned(elementTypeIfVectorOrMatrix(op.getRhs().getType())))
4014 rewriter.replaceOpWithNewOp<UIntOp>(op, lhs, rhs);
4015 else
4016 rewriter.replaceOpWithNewOp<SIntOp>(op, lhs, rhs);
4017 return mlir::success();
4018}
4019
4020mlir::LogicalResult CIRToLLVMMaxOpLowering::matchAndRewrite(
4021 cir::MaxOp op, OpAdaptor adaptor,
4022 mlir::ConversionPatternRewriter &rewriter) const {
4024 op, adaptor, rewriter);
4025}
4026
4027mlir::LogicalResult CIRToLLVMMinOpLowering::matchAndRewrite(
4028 cir::MinOp op, OpAdaptor adaptor,
4029 mlir::ConversionPatternRewriter &rewriter) const {
4031 op, adaptor, rewriter);
4032}
4033
4034/// Convert from a CIR comparison kind to an LLVM IR integral comparison kind.
4035static mlir::LLVM::ICmpPredicate
4036convertCmpKindToICmpPredicate(cir::CmpOpKind kind, bool isSigned) {
4037 using CIR = cir::CmpOpKind;
4038 using LLVMICmp = mlir::LLVM::ICmpPredicate;
4039 switch (kind) {
4040 case CIR::eq:
4041 return LLVMICmp::eq;
4042 case CIR::ne:
4043 return LLVMICmp::ne;
4044 case CIR::lt:
4045 return (isSigned ? LLVMICmp::slt : LLVMICmp::ult);
4046 case CIR::le:
4047 return (isSigned ? LLVMICmp::sle : LLVMICmp::ule);
4048 case CIR::gt:
4049 return (isSigned ? LLVMICmp::sgt : LLVMICmp::ugt);
4050 case CIR::ge:
4051 return (isSigned ? LLVMICmp::sge : LLVMICmp::uge);
4052 case CIR::one:
4053 case CIR::uno:
4054 llvm_unreachable("FP-only comparison used with integer type");
4055 }
4056 llvm_unreachable("Unknown CmpOpKind");
4057}
4058
4059/// Convert from a CIR comparison kind to an LLVM IR floating-point comparison
4060/// kind.
4061static mlir::LLVM::FCmpPredicate
4063 using CIR = cir::CmpOpKind;
4064 using LLVMFCmp = mlir::LLVM::FCmpPredicate;
4065 switch (kind) {
4066 case CIR::eq:
4067 return LLVMFCmp::oeq;
4068 case CIR::ne:
4069 return LLVMFCmp::une;
4070 case CIR::lt:
4071 return LLVMFCmp::olt;
4072 case CIR::le:
4073 return LLVMFCmp::ole;
4074 case CIR::gt:
4075 return LLVMFCmp::ogt;
4076 case CIR::ge:
4077 return LLVMFCmp::oge;
4078 case CIR::one:
4079 return LLVMFCmp::one;
4080 case CIR::uno:
4081 return LLVMFCmp::uno;
4082 }
4083 llvm_unreachable("Unknown CmpOpKind");
4084}
4085
4086/// Convert from a CIR fp comparison kind to an LLVM IR floating-point
4087/// comparison kind.
4088static mlir::LLVM::FCmpPredicate
4090 using CIR = cir::FCmpOpKind;
4091 using LLVMFCmp = mlir::LLVM::FCmpPredicate;
4092 switch (kind) {
4093 case CIR::_false:
4094 return LLVMFCmp::_false;
4095 case CIR::oeq:
4096 return LLVMFCmp::oeq;
4097 case CIR::ogt:
4098 return LLVMFCmp::ogt;
4099 case CIR::oge:
4100 return LLVMFCmp::oge;
4101 case CIR::olt:
4102 return LLVMFCmp::olt;
4103 case CIR::ole:
4104 return LLVMFCmp::ole;
4105 case CIR::one:
4106 return LLVMFCmp::one;
4107 case CIR::ord:
4108 return LLVMFCmp::ord;
4109 case CIR::ueq:
4110 return LLVMFCmp::ueq;
4111 case CIR::ugt:
4112 return LLVMFCmp::ugt;
4113 case CIR::uge:
4114 return LLVMFCmp::uge;
4115 case CIR::ult:
4116 return LLVMFCmp::ult;
4117 case CIR::ule:
4118 return LLVMFCmp::ule;
4119 case CIR::une:
4120 return LLVMFCmp::une;
4121 case CIR::uno:
4122 return LLVMFCmp::uno;
4123 case CIR::_true:
4124 return LLVMFCmp::_true;
4125 }
4126 llvm_unreachable("Unknown FCmpOpKind");
4127}
4128
4129static llvm::StringRef
4131 using CIR = cir::CmpOpKind;
4132 switch (kind) {
4133 case CIR::eq:
4134 return "oeq";
4135 case CIR::ne:
4136 return "une";
4137 case CIR::lt:
4138 return "olt";
4139 case CIR::le:
4140 return "ole";
4141 case CIR::gt:
4142 return "ogt";
4143 case CIR::ge:
4144 return "oge";
4145 case CIR::one:
4146 return "one";
4147 case CIR::uno:
4148 return "uno";
4149 }
4150 llvm_unreachable("Unknown CmpOpKind");
4151}
4152
4153static bool isSignalingConstrainedFCmp(cir::CmpOpKind kind) {
4154 using CIR = cir::CmpOpKind;
4155 switch (kind) {
4156 case CIR::lt:
4157 case CIR::le:
4158 case CIR::gt:
4159 case CIR::ge:
4160 return true;
4161 case CIR::eq:
4162 case CIR::ne:
4163 case CIR::one:
4164 case CIR::uno:
4165 return false;
4166 }
4167 llvm_unreachable("Unknown CmpOpKind");
4168}
4169
4170static llvm::StringRef
4172 using CIR = cir::FCmpOpKind;
4173 switch (kind) {
4174 case CIR::_false:
4175 return "false";
4176 case CIR::oeq:
4177 return "oeq";
4178 case CIR::ogt:
4179 return "ogt";
4180 case CIR::oge:
4181 return "oge";
4182 case CIR::olt:
4183 return "olt";
4184 case CIR::ole:
4185 return "ole";
4186 case CIR::one:
4187 return "one";
4188 case CIR::ord:
4189 return "ord";
4190 case CIR::ueq:
4191 return "ueq";
4192 case CIR::ugt:
4193 return "ugt";
4194 case CIR::uge:
4195 return "uge";
4196 case CIR::ult:
4197 return "ult";
4198 case CIR::ule:
4199 return "ule";
4200 case CIR::une:
4201 return "une";
4202 case CIR::uno:
4203 return "uno";
4204 case CIR::_true:
4205 return "true";
4206 }
4207 llvm_unreachable("Unknown FCmpOpKind");
4208}
4209
4210template <typename OpKindTy>
4211static mlir::LLVM::CallIntrinsicOp
4212createConstrainedFCmpCall(mlir::ConversionPatternRewriter &rewriter,
4213 mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
4214 OpKindTy kind, bool isSignaling, cir::FenvAttr fenv,
4215 mlir::Type llvmResTy) {
4216 llvm::SmallVector<mlir::Value, 4> callOperands = {
4217 lhs, rhs,
4218 createFenvMetadataValue(rewriter, loc,
4220 createFenvMetadataValue(rewriter, loc,
4222 llvm::StringRef intrinsicName = isSignaling
4223 ? "llvm.experimental.constrained.fcmps"
4224 : "llvm.experimental.constrained.fcmp";
4225 return createCallLLVMIntrinsicOp(rewriter, loc, intrinsicName, llvmResTy,
4226 callOperands);
4227}
4228
4229mlir::LogicalResult CIRToLLVMCmpOpLowering::matchAndRewrite(
4230 cir::CmpOp cmpOp, OpAdaptor adaptor,
4231 mlir::ConversionPatternRewriter &rewriter) const {
4232 mlir::Type type = cmpOp.getLhs().getType();
4233
4234 if (mlir::isa<cir::IntType, mlir::IntegerType>(type)) {
4235 bool isSigned = mlir::isa<cir::IntType>(type)
4236 ? mlir::cast<cir::IntType>(type).isSigned()
4237 : mlir::cast<mlir::IntegerType>(type).isSigned();
4238 mlir::LLVM::ICmpPredicate kind =
4239 convertCmpKindToICmpPredicate(cmpOp.getKind(), isSigned);
4240 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
4241 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
4242 return mlir::success();
4243 }
4244
4245 if (mlir::isa<cir::BoolType, cir::PointerType, cir::VPtrType>(type)) {
4246 // Booleans, including enums with a boolean underlying type, compare as
4247 // unsigned integers, as do pointers and !cir.vptr, which lowers to a
4248 // pointer.
4249 mlir::LLVM::ICmpPredicate kind =
4250 convertCmpKindToICmpPredicate(cmpOp.getKind(), /*isSigned=*/false);
4251 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
4252 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
4253 return mlir::success();
4254 }
4255
4256 if (mlir::isa<cir::FPTypeInterface>(type)) {
4257 mlir::Type llvmResTy = getTypeConverter()->convertType(cmpOp.getType());
4258 if (cir::FenvAttr fenv = cmpOp.getFenvAttr()) {
4259 mlir::LLVM::CallIntrinsicOp call = createConstrainedFCmpCall(
4260 rewriter, cmpOp.getLoc(), adaptor.getLhs(), adaptor.getRhs(),
4261 cmpOp.getKind(), isSignalingConstrainedFCmp(cmpOp.getKind()), fenv,
4262 llvmResTy);
4263 rewriter.replaceOp(cmpOp, call.getResult(0));
4264 return mlir::success();
4265 }
4266 mlir::LLVM::FCmpPredicate kind =
4267 convertCmpKindToFCmpPredicate(cmpOp.getKind());
4268 rewriter.replaceOpWithNewOp<mlir::LLVM::FCmpOp>(
4269 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
4270 return mlir::success();
4271 }
4272
4273 if (mlir::isa<cir::ComplexType>(type)) {
4274 mlir::Value lhs = adaptor.getLhs();
4275 mlir::Value rhs = adaptor.getRhs();
4276 mlir::Location loc = cmpOp.getLoc();
4277
4278 auto complexType = mlir::cast<cir::ComplexType>(cmpOp.getLhs().getType());
4279 mlir::Type complexElemTy =
4280 getTypeConverter()->convertType(complexType.getElementType());
4281
4282 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
4283 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
4284 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
4285 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
4286 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
4287 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
4288 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
4289 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
4290
4291 if (cmpOp.getKind() == cir::CmpOpKind::eq) {
4292 if (complexElemTy.isInteger()) {
4293 auto realCmp = mlir::LLVM::ICmpOp::create(
4294 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, lhsReal, rhsReal);
4295 auto imagCmp = mlir::LLVM::ICmpOp::create(
4296 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, lhsImag, rhsImag);
4297 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(cmpOp, realCmp, imagCmp);
4298 return mlir::success();
4299 }
4300
4301 auto realCmp = mlir::LLVM::FCmpOp::create(
4302 rewriter, loc, mlir::LLVM::FCmpPredicate::oeq, lhsReal, rhsReal);
4303 auto imagCmp = mlir::LLVM::FCmpOp::create(
4304 rewriter, loc, mlir::LLVM::FCmpPredicate::oeq, lhsImag, rhsImag);
4305 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(cmpOp, realCmp, imagCmp);
4306 return mlir::success();
4307 }
4308
4309 if (cmpOp.getKind() == cir::CmpOpKind::ne) {
4310 if (complexElemTy.isInteger()) {
4311 auto realCmp = mlir::LLVM::ICmpOp::create(
4312 rewriter, loc, mlir::LLVM::ICmpPredicate::ne, lhsReal, rhsReal);
4313 auto imagCmp = mlir::LLVM::ICmpOp::create(
4314 rewriter, loc, mlir::LLVM::ICmpPredicate::ne, lhsImag, rhsImag);
4315 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(cmpOp, realCmp, imagCmp);
4316 return mlir::success();
4317 }
4318
4319 auto realCmp = mlir::LLVM::FCmpOp::create(
4320 rewriter, loc, mlir::LLVM::FCmpPredicate::une, lhsReal, rhsReal);
4321 auto imagCmp = mlir::LLVM::FCmpOp::create(
4322 rewriter, loc, mlir::LLVM::FCmpPredicate::une, lhsImag, rhsImag);
4323 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(cmpOp, realCmp, imagCmp);
4324 return mlir::success();
4325 }
4326 }
4327
4328 return cmpOp.emitError() << "unsupported type for CmpOp: " << type;
4329}
4330
4331mlir::LogicalResult CIRToLLVMFCmpOpLowering::matchAndRewrite(
4332 cir::FCmpOp fCmpOp, OpAdaptor adaptor,
4333 mlir::ConversionPatternRewriter &rewriter) const {
4334 assert(mlir::isa<cir::FPTypeInterface>(fCmpOp.getLhs().getType()) &&
4335 "unexpected fcmp type");
4336
4337 mlir::Type llvmResTy = getTypeConverter()->convertType(fCmpOp.getType());
4338 if (cir::FenvAttr fenv = fCmpOp.getFenvAttr()) {
4339 mlir::LLVM::CallIntrinsicOp call = createConstrainedFCmpCall(
4340 rewriter, fCmpOp.getLoc(), adaptor.getLhs(), adaptor.getRhs(),
4341 fCmpOp.getKind(), fCmpOp.getSignaling(), fenv, llvmResTy);
4342 rewriter.replaceOp(fCmpOp, call.getResult(0));
4343 return mlir::success();
4344 }
4345 mlir::LLVM::FCmpPredicate kind =
4346 convertCmpKindToFCmpPredicate(fCmpOp.getKind());
4347 rewriter.replaceOpWithNewOp<mlir::LLVM::FCmpOp>(
4348 fCmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
4349 return mlir::success();
4350}
4351
4352/// Shared lowering logic for checked binary arithmetic overflow operations.
4353/// The \p opStr parameter specifies the arithmetic operation name used in the
4354/// LLVM intrinsic (e.g., "add", "sub", "mul").
4355template <typename OpTy>
4356static mlir::LogicalResult
4357lowerBinOpOverflow(OpTy op, typename OpTy::Adaptor adaptor,
4358 mlir::ConversionPatternRewriter &rewriter,
4359 const mlir::TypeConverter *typeConverter,
4360 llvm::StringRef opStr) {
4361 mlir::Location loc = op.getLoc();
4362 cir::IntType operandTy = op.getLhs().getType();
4363 // The result type may be a `cir.bool`, which behaves as a 1-bit unsigned
4364 // integer for the purposes of the checked arithmetic.
4365 mlir::Type resultTy = op.getResult().getType();
4366 auto resultIntTy = mlir::dyn_cast<cir::IntType>(resultTy);
4367 unsigned resultWidth = resultIntTy ? resultIntTy.getWidth() : 1;
4368 bool resultSigned = resultIntTy && resultIntTy.getIsSigned();
4369
4370 bool sign = operandTy.getIsSigned() || resultSigned;
4371 unsigned width =
4372 std::max(operandTy.getWidth() + (sign && operandTy.isUnsigned()),
4373 resultWidth + (sign && !resultSigned));
4374
4375 mlir::IntegerType encompassedLLVMTy = rewriter.getIntegerType(width);
4376
4377 mlir::Value lhs = adaptor.getLhs();
4378 mlir::Value rhs = adaptor.getRhs();
4379 if (operandTy.getWidth() < width) {
4380 if (operandTy.isSigned()) {
4381 lhs = mlir::LLVM::SExtOp::create(rewriter, loc, encompassedLLVMTy, lhs);
4382 rhs = mlir::LLVM::SExtOp::create(rewriter, loc, encompassedLLVMTy, rhs);
4383 } else {
4384 lhs = mlir::LLVM::ZExtOp::create(rewriter, loc, encompassedLLVMTy, lhs);
4385 rhs = mlir::LLVM::ZExtOp::create(rewriter, loc, encompassedLLVMTy, rhs);
4386 }
4387 }
4388
4389 // The intrinsic name is `@llvm.{s|u}{op}.with.overflow.i{width}`
4390 std::string intrinName = ("llvm." + llvm::Twine(sign ? 's' : 'u') + opStr +
4391 ".with.overflow.i" + llvm::Twine(width))
4392 .str();
4393 auto intrinNameAttr = mlir::StringAttr::get(op.getContext(), intrinName);
4394
4395 mlir::IntegerType overflowLLVMTy = rewriter.getI1Type();
4396 auto intrinRetTy = mlir::LLVM::LLVMStructType::getLiteral(
4397 rewriter.getContext(), {encompassedLLVMTy, overflowLLVMTy});
4398
4399 auto callLLVMIntrinOp = mlir::LLVM::CallIntrinsicOp::create(
4400 rewriter, loc, intrinRetTy, intrinNameAttr, mlir::ValueRange{lhs, rhs});
4401 mlir::Value intrinRet = callLLVMIntrinOp.getResult(0);
4402
4403 mlir::Value result = mlir::LLVM::ExtractValueOp::create(
4404 rewriter, loc, intrinRet, ArrayRef<int64_t>{0})
4405 .getResult();
4406 mlir::Value overflow = mlir::LLVM::ExtractValueOp::create(
4407 rewriter, loc, intrinRet, ArrayRef<int64_t>{1})
4408 .getResult();
4409
4410 if (resultWidth < width) {
4411 mlir::Type resultLLVMTy = typeConverter->convertType(resultTy);
4412 auto truncResult =
4413 mlir::LLVM::TruncOp::create(rewriter, loc, resultLLVMTy, result);
4414
4415 // Extend the truncated result back to the encompassing type to check for
4416 // any overflows during the truncation.
4417 mlir::Value truncResultExt;
4418 if (resultSigned)
4419 truncResultExt = mlir::LLVM::SExtOp::create(
4420 rewriter, loc, encompassedLLVMTy, truncResult);
4421 else
4422 truncResultExt = mlir::LLVM::ZExtOp::create(
4423 rewriter, loc, encompassedLLVMTy, truncResult);
4424 auto truncOverflow = mlir::LLVM::ICmpOp::create(
4425 rewriter, loc, mlir::LLVM::ICmpPredicate::ne, truncResultExt, result);
4426
4427 result = truncResult;
4428 overflow = mlir::LLVM::OrOp::create(rewriter, loc, overflow, truncOverflow);
4429 }
4430
4431 mlir::Type boolLLVMTy =
4432 typeConverter->convertType(op.getOverflow().getType());
4433 if (boolLLVMTy != rewriter.getI1Type())
4434 overflow = mlir::LLVM::ZExtOp::create(rewriter, loc, boolLLVMTy, overflow);
4435
4436 rewriter.replaceOp(op, mlir::ValueRange{result, overflow});
4437
4438 return mlir::success();
4439}
4440
4441mlir::LogicalResult CIRToLLVMAddOverflowOpLowering::matchAndRewrite(
4442 cir::AddOverflowOp op, OpAdaptor adaptor,
4443 mlir::ConversionPatternRewriter &rewriter) const {
4444 return lowerBinOpOverflow(op, adaptor, rewriter, getTypeConverter(), "add");
4445}
4446
4447mlir::LogicalResult CIRToLLVMSubOverflowOpLowering::matchAndRewrite(
4448 cir::SubOverflowOp op, OpAdaptor adaptor,
4449 mlir::ConversionPatternRewriter &rewriter) const {
4450 return lowerBinOpOverflow(op, adaptor, rewriter, getTypeConverter(), "sub");
4451}
4452
4453mlir::LogicalResult CIRToLLVMMulOverflowOpLowering::matchAndRewrite(
4454 cir::MulOverflowOp op, OpAdaptor adaptor,
4455 mlir::ConversionPatternRewriter &rewriter) const {
4456 return lowerBinOpOverflow(op, adaptor, rewriter, getTypeConverter(), "mul");
4457}
4458
4459mlir::LogicalResult CIRToLLVMFrexpOpLowering::matchAndRewrite(
4460 cir::FrexpOp op, OpAdaptor adaptor,
4461 mlir::ConversionPatternRewriter &rewriter) const {
4462 mlir::Location loc = op.getLoc();
4463 mlir::Type fpLLVMTy =
4464 getTypeConverter()->convertType(op.getResult().getType());
4465 mlir::Type intLLVMTy = getTypeConverter()->convertType(op.getExp().getType());
4466
4467 auto structTy = mlir::LLVM::LLVMStructType::getLiteral(rewriter.getContext(),
4468 {fpLLVMTy, intLLVMTy});
4469
4470 auto callOp = createCallLLVMIntrinsicOp(rewriter, loc, "llvm.frexp", structTy,
4471 adaptor.getSrc());
4472 mlir::Value result = callOp.getResult(0);
4473
4474 mlir::Value mantissa =
4475 mlir::LLVM::ExtractValueOp::create(rewriter, loc, result, 0);
4476 mlir::Value exponent =
4477 mlir::LLVM::ExtractValueOp::create(rewriter, loc, result, 1);
4478 rewriter.replaceOp(op, mlir::ValueRange{mantissa, exponent});
4479 return mlir::success();
4480}
4481
4482mlir::LogicalResult CIRToLLVMModfOpLowering::matchAndRewrite(
4483 cir::ModfOp op, OpAdaptor adaptor,
4484 mlir::ConversionPatternRewriter &rewriter) const {
4485 mlir::Location loc = op.getLoc();
4486 mlir::Type fpLLVMTy =
4487 getTypeConverter()->convertType(op.getFractional().getType());
4488
4489 auto structTy = mlir::LLVM::LLVMStructType::getLiteral(rewriter.getContext(),
4490 {fpLLVMTy, fpLLVMTy});
4491
4492 auto callOp = createCallLLVMIntrinsicOp(rewriter, loc, "llvm.modf", structTy,
4493 adaptor.getSrc());
4494 mlir::Value result = callOp.getResult(0);
4495
4496 mlir::Value fractional =
4497 mlir::LLVM::ExtractValueOp::create(rewriter, loc, result, 0);
4498 mlir::Value integral =
4499 mlir::LLVM::ExtractValueOp::create(rewriter, loc, result, 1);
4500 rewriter.replaceOp(op, mlir::ValueRange{fractional, integral});
4501 return mlir::success();
4502}
4503
4504mlir::LogicalResult CIRToLLVMShiftOpLowering::matchAndRewrite(
4505 cir::ShiftOp op, OpAdaptor adaptor,
4506 mlir::ConversionPatternRewriter &rewriter) const {
4507 assert((op.getValue().getType() == op.getType()) &&
4508 "inconsistent operands' types NYI");
4509
4510 const mlir::Type llvmTy = getTypeConverter()->convertType(op.getType());
4511 mlir::Value amt = adaptor.getAmount();
4512 mlir::Value val = adaptor.getValue();
4513
4514 auto cirAmtTy = mlir::dyn_cast<cir::IntType>(op.getAmount().getType());
4515 bool isUnsigned;
4516 if (cirAmtTy) {
4517 auto cirValTy = mlir::cast<cir::IntType>(op.getValue().getType());
4518 isUnsigned = cirValTy.isUnsigned();
4519
4520 // Ensure shift amount is the same type as the value. Some undefined
4521 // behavior might occur in the casts below as per [C99 6.5.7.3].
4522 // Vector type shift amount needs no cast as type consistency is expected to
4523 // be already be enforced at CIRGen.
4524 if (cirAmtTy)
4525 amt = getLLVMIntCast(rewriter, amt, llvmTy, true, cirAmtTy.getWidth(),
4526 cirValTy.getWidth());
4527 } else {
4528 auto cirValVTy = mlir::cast<cir::VectorType>(op.getValue().getType());
4529 isUnsigned =
4530 mlir::cast<cir::IntType>(cirValVTy.getElementType()).isUnsigned();
4531 }
4532
4533 // Lower to the proper LLVM shift operation.
4534 if (op.getIsShiftleft()) {
4535 rewriter.replaceOpWithNewOp<mlir::LLVM::ShlOp>(op, llvmTy, val, amt);
4536 return mlir::success();
4537 }
4538
4539 if (isUnsigned)
4540 rewriter.replaceOpWithNewOp<mlir::LLVM::LShrOp>(op, llvmTy, val, amt);
4541 else
4542 rewriter.replaceOpWithNewOp<mlir::LLVM::AShrOp>(op, llvmTy, val, amt);
4543 return mlir::success();
4544}
4545
4546mlir::LogicalResult CIRToLLVMSelectOpLowering::matchAndRewrite(
4547 cir::SelectOp op, OpAdaptor adaptor,
4548 mlir::ConversionPatternRewriter &rewriter) const {
4549 // Two special cases in the LLVMIR codegen of select op:
4550 // - select %0, %1, false => and %0, %1
4551 // - select %0, true, %1 => or %0, %1
4552 // Match the (possibly already converted) adaptor operands: without pattern
4553 // rollback the producer may be an LLVM constant by the time this runs.
4554 if (mlir::isa<cir::BoolType>(op.getType())) {
4555 if (mlir::matchPattern(adaptor.getFalseValue(), mlir::m_Zero())) {
4556 // select %0, %1, false => and %0, %1
4557 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(op, adaptor.getCondition(),
4558 adaptor.getTrueValue());
4559 return mlir::success();
4560 }
4561 if (mlir::matchPattern(adaptor.getTrueValue(), mlir::m_One())) {
4562 // select %0, true, %1 => or %0, %1
4563 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(op, adaptor.getCondition(),
4564 adaptor.getFalseValue());
4565 return mlir::success();
4566 }
4567 }
4568
4569 mlir::Value llvmCondition = adaptor.getCondition();
4570 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(
4571 op, llvmCondition, adaptor.getTrueValue(), adaptor.getFalseValue());
4572
4573 return mlir::success();
4574}
4575
4576static void prepareTypeConverter(mlir::LLVMTypeConverter &converter,
4577 mlir::DataLayout &dataLayout) {
4578 converter.addConversion([&](cir::PointerType type) -> mlir::Type {
4579 mlir::ptr::MemorySpaceAttrInterface addrSpaceAttr = type.getAddrSpace();
4580 unsigned numericAS = 0;
4581
4582 if (mlir::isa_and_present<cir::LangAddressSpaceAttr>(addrSpaceAttr))
4583 return {};
4584
4585 if (auto targetAsAttr =
4586 mlir::dyn_cast_if_present<cir::TargetAddressSpaceAttr>(
4587 addrSpaceAttr))
4588 numericAS = targetAsAttr.getValue();
4589 return mlir::LLVM::LLVMPointerType::get(type.getContext(), numericAS);
4590 });
4591 converter.addConversion([&](cir::VPtrType type) -> mlir::Type {
4593 return mlir::LLVM::LLVMPointerType::get(type.getContext());
4594 });
4595 // On the device side, surface reference is represented as an object handle
4596 // in 64-bit integer.
4597 converter.addConversion([&](cir::CUDADeviceSurfaceType type) -> mlir::Type {
4598 return mlir::IntegerType::get(type.getContext(), 64);
4599 });
4600 converter.addConversion([&](cir::CUDADeviceTextureType type) -> mlir::Type {
4601 return mlir::IntegerType::get(type.getContext(), 64);
4602 });
4603 converter.addConversion([&](cir::ArrayType type) -> mlir::Type {
4604 mlir::Type ty =
4605 convertTypeForMemory(converter, dataLayout, type.getElementType());
4606 // A null element type means an unsupported member (e.g. a _BitInt with
4607 // byte-array storage); propagate the conversion failure.
4608 if (!ty)
4609 return {};
4610 return mlir::LLVM::LLVMArrayType::get(ty, type.getSize());
4611 });
4612 converter.addConversion([&](cir::SveCountType type) -> mlir::Type {
4613 return mlir::LLVM::LLVMTargetExtType::get(type.getContext(),
4614 "aarch64.svcount", {}, {});
4615 });
4616 converter.addConversion([&](cir::VectorType type) -> mlir::Type {
4617 // Vector-of-_BitInt memory layout is not modeled here (the element would
4618 // stay at its literal width); report a conversion failure rather than emit
4619 // an unvalidated vector.
4620 if (cir::isBitIntType(type.getElementType()))
4621 return {};
4622 mlir::Type ty = converter.convertType(type.getElementType());
4623 if (!ty)
4624 return {};
4625 // A scalar opaque float is lowered to a one-element vector of an integer
4626 // of the same width. A vector of opaque floats has that integer as its
4627 // element type.
4628 if (cir::isAnyOpaqueFloatingPointType(type.getElementType()))
4629 ty = mlir::cast<mlir::VectorType>(ty).getElementType();
4630 return mlir::VectorType::get(type.getSize().getKnownMinValue(), ty,
4631 {type.isScalable()});
4632 });
4633 converter.addConversion([&](cir::MatrixType type) -> mlir::Type {
4634 const uint64_t size = type.getNumRows() * type.getNumColumns();
4635 const mlir::Type elemTy = converter.convertType(type.getElementType());
4636 return mlir::VectorType::get(size, elemTy);
4637 });
4638 converter.addConversion([&](cir::BoolType type) -> mlir::Type {
4639 return mlir::IntegerType::get(type.getContext(), 1,
4640 mlir::IntegerType::Signless);
4641 });
4642 converter.addConversion([&](cir::IntType type) -> mlir::Type {
4643 // LLVM doesn't work with signed types, so we drop the CIR signs here.
4644 return mlir::IntegerType::get(type.getContext(), type.getWidth());
4645 });
4646 converter.addConversion([&](cir::SingleType type) -> mlir::Type {
4647 return mlir::Float32Type::get(type.getContext());
4648 });
4649 converter.addConversion([&](cir::DoubleType type) -> mlir::Type {
4650 return mlir::Float64Type::get(type.getContext());
4651 });
4652 converter.addConversion([&](cir::FP80Type type) -> mlir::Type {
4653 return mlir::Float80Type::get(type.getContext());
4654 });
4655 converter.addConversion([&](cir::FP128Type type) -> mlir::Type {
4656 return mlir::Float128Type::get(type.getContext());
4657 });
4658 converter.addConversion([&](cir::LongDoubleType type) -> mlir::Type {
4659 return converter.convertType(type.getUnderlying());
4660 });
4661 converter.addConversion([&](cir::FP16Type type) -> mlir::Type {
4662 return mlir::Float16Type::get(type.getContext());
4663 });
4664 converter.addConversion([&](cir::BF16Type type) -> mlir::Type {
4665 return mlir::BFloat16Type::get(type.getContext());
4666 });
4667 // LLVM IR has no type for a floating-point value whose format is not fixed.
4668 // A scalar opaque float is lowered to a one-element vector of an integer of
4669 // the same width.
4670 converter.addConversion([&](cir::MFloat8Type type) -> mlir::Type {
4671 return mlir::VectorType::get(
4672 1, mlir::IntegerType::get(type.getContext(), type.getWidth()));
4673 });
4674 converter.addConversion([&](cir::ComplexType type) -> mlir::Type {
4675 // A complex type is lowered to an LLVM struct that contains the real and
4676 // imaginary part as data fields.
4677 mlir::Type elementTy = converter.convertType(type.getElementType());
4678 mlir::Type structFields[2] = {elementTy, elementTy};
4679 return mlir::LLVM::LLVMStructType::getLiteral(type.getContext(),
4680 structFields);
4681 });
4682 converter.addConversion([&](cir::FuncType type) -> std::optional<mlir::Type> {
4683 auto result = converter.convertType(type.getReturnType());
4684 if (!result)
4685 return std::nullopt;
4687 arguments.reserve(type.getNumInputs());
4688 if (converter.convertTypes(type.getInputs(), arguments).failed())
4689 return std::nullopt;
4690 auto varArg = type.isVarArg();
4691 return mlir::LLVM::LLVMFunctionType::get(result, arguments, varArg);
4692 });
4693 converter.addConversion([&](cir::StructType type) -> mlir::Type {
4695 for (mlir::Type ty : type.getMembers()) {
4696 // A bit-field that shares an earlier field's access unit, and a
4697 // zero-width bit-field, own no bytes, so they get no field of their own.
4698 // StructType::getLLVMFieldIndex maps the two numberings.
4699 if (!cir::memberOwnsBytes(ty))
4700 continue;
4701 mlir::Type memberTy = convertTypeForMemory(converter, dataLayout,
4703 // A null member means an unsupported type (e.g. a _BitInt with byte-array
4704 // storage); propagate the conversion failure instead of building an
4705 // invalid struct body.
4706 if (!memberTy)
4707 return {};
4708 llvmMembers.push_back(memberTy);
4709 }
4710
4711 mlir::LLVM::LLVMStructType llvmStruct;
4712 if (type.getName()) {
4713 llvmStruct = mlir::LLVM::LLVMStructType::getIdentified(
4714 type.getContext(), type.getPrefixedName());
4715 if (llvmStruct.setBody(llvmMembers, type.getPacked()).failed())
4716 llvm_unreachable("Failed to set body of record");
4717 } else {
4718 llvmStruct = mlir::LLVM::LLVMStructType::getLiteral(
4719 type.getContext(), llvmMembers, type.getPacked());
4720 }
4721 return llvmStruct;
4722 });
4723 // Unions are lowered as only the largest member.
4724 converter.addConversion([&](cir::UnionType type) -> mlir::Type {
4726 if (!type.getMembers().empty())
4727 if (auto storage = type.getUnionStorageType(dataLayout)) {
4728 mlir::Type storageTy =
4729 convertTypeForMemory(converter, dataLayout, storage);
4730 if (!storageTy)
4731 return {};
4732 llvmMembers.push_back(storageTy);
4733 }
4734 if (mlir::Type pad = type.getPadding()) {
4735 mlir::Type padTy = convertTypeForMemory(converter, dataLayout, pad);
4736 if (!padTy)
4737 return {};
4738 llvmMembers.push_back(padTy);
4739 }
4740
4741 mlir::LLVM::LLVMStructType llvmStruct;
4742 if (type.getName()) {
4743 llvmStruct = mlir::LLVM::LLVMStructType::getIdentified(
4744 type.getContext(), type.getPrefixedName());
4745 if (llvmStruct.setBody(llvmMembers, type.getPacked()).failed())
4746 llvm_unreachable("Failed to set body of record");
4747 } else {
4748 llvmStruct = mlir::LLVM::LLVMStructType::getLiteral(
4749 type.getContext(), llvmMembers, type.getPacked());
4750 }
4751 return llvmStruct;
4752 });
4753 converter.addConversion([&](cir::VoidType type) -> mlir::Type {
4754 return mlir::LLVM::LLVMVoidType::get(type.getContext());
4755 });
4756}
4758 mlir::ModuleOp module, StringRef globalXtorName, StringRef llvmXtorName,
4759 llvm::function_ref<cir::GlobalCtorDtorEntry(mlir::Attribute)> createXtor) {
4761 if (auto attr =
4762 module->getDiscardableAttrOfType<mlir::ArrayAttr>(globalXtorName))
4763 for (mlir::Attribute element : attr)
4764 globalXtors.emplace_back(createXtor(element));
4765
4766 if (globalXtors.empty())
4767 return;
4768
4769 mlir::OpBuilder builder(module.getContext());
4770 builder.setInsertionPointToEnd(&module.getBodyRegion().back());
4771
4772 // Create a global array llvm.global_ctors with element type of
4773 // struct { i32, ptr, ptr }
4774 cir::CIRDataLayout cirDataLayout(module);
4775 auto ctorPFTy = mlir::LLVM::LLVMPointerType::get(
4776 builder.getContext(), cirDataLayout.getProgramAddressSpace());
4777 llvm::SmallVector<mlir::Type> ctorStructFields;
4778 ctorStructFields.push_back(builder.getI32Type());
4779 ctorStructFields.push_back(ctorPFTy);
4780 ctorStructFields.push_back(ctorPFTy);
4781
4782 auto ctorStructTy = mlir::LLVM::LLVMStructType::getLiteral(
4783 builder.getContext(), ctorStructFields);
4784 auto ctorStructArrayTy =
4785 mlir::LLVM::LLVMArrayType::get(ctorStructTy, globalXtors.size());
4786
4787 mlir::Location loc = module.getLoc();
4788 auto newGlobalOp = mlir::LLVM::GlobalOp::create(
4789 builder, loc, ctorStructArrayTy, /*constant=*/false,
4790 mlir::LLVM::Linkage::Appending, llvmXtorName, mlir::Attribute());
4791
4792 builder.createBlock(&newGlobalOp.getRegion());
4793 builder.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
4794
4795 mlir::Value result =
4796 mlir::LLVM::UndefOp::create(builder, loc, ctorStructArrayTy);
4797
4798 for (auto [index, xtorInfo] : llvm::enumerate(globalXtors)) {
4799 mlir::Value structInit =
4800 mlir::LLVM::UndefOp::create(builder, loc, ctorStructTy);
4801 mlir::Value initPriority = mlir::LLVM::ConstantOp::create(
4802 builder, loc, ctorStructFields[0], xtorInfo.priority);
4803 mlir::Value initFuncAddr = mlir::LLVM::AddressOfOp::create(
4804 builder, loc, ctorStructFields[1], xtorInfo.name);
4805 mlir::Value initAssociate =
4806 xtorInfo.associated.empty()
4807 ? mlir::LLVM::ZeroOp::create(builder, loc, ctorStructFields[2])
4808 .getResult()
4809 : mlir::LLVM::AddressOfOp::create(builder, loc, ctorStructFields[2],
4810 xtorInfo.associated)
4811 .getResult();
4812 // Literal zero makes the InsertValueOp::create ambiguous.
4814 structInit = mlir::LLVM::InsertValueOp::create(builder, loc, structInit,
4815 initPriority, zero);
4816 structInit = mlir::LLVM::InsertValueOp::create(builder, loc, structInit,
4817 initFuncAddr, 1);
4818 structInit = mlir::LLVM::InsertValueOp::create(builder, loc, structInit,
4819 initAssociate, 2);
4820 result = mlir::LLVM::InsertValueOp::create(builder, loc, result, structInit,
4821 index);
4822 }
4823
4824 mlir::LLVM::ReturnOp::create(builder, loc, result);
4825}
4826
4827mlir::LogicalResult CIRToLLVMObjSizeOpLowering::matchAndRewrite(
4828 cir::ObjSizeOp op, OpAdaptor adaptor,
4829 mlir::ConversionPatternRewriter &rewriter) const {
4830 mlir::Type llvmResTy = getTypeConverter()->convertType(op.getType());
4831 mlir::Location loc = op->getLoc();
4832
4833 mlir::IntegerType i1Ty = rewriter.getI1Type();
4834
4835 auto i1Val = [&rewriter, &loc, &i1Ty](bool val) {
4836 return mlir::LLVM::ConstantOp::create(rewriter, loc, i1Ty, val);
4837 };
4838
4839 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.objectsize", llvmResTy,
4840 {
4841 adaptor.getPtr(),
4842 i1Val(op.getMin()),
4843 i1Val(op.getNullunknown()),
4844 i1Val(op.getDynamic()),
4845 });
4846
4847 return mlir::LogicalResult::success();
4848}
4849
4850//===----------------------------------------------------------------------===//
4851// @llvm.global.annotations emission
4852//===----------------------------------------------------------------------===//
4853
4854/// Annotation strings and arguments, shared by all annotations in a module.
4856 explicit LLVMAnnotationGlobals(mlir::ModuleOp module) {
4858 auto asAttr = mlir::dyn_cast_if_present<mlir::IntegerAttr>(
4859 mlir::DataLayout(module).getGlobalMemorySpace());
4860 addrSpace = asAttr ? asAttr.getUInt() : 0;
4861 }
4862
4863 unsigned addrSpace;
4864 llvm::StringMap<mlir::LLVM::GlobalOp> stringCache;
4865 llvm::StringMap<mlir::LLVM::GlobalOp> argStringCache;
4866 llvm::MapVector<mlir::ArrayAttr, mlir::LLVM::GlobalOp> argsCache;
4867};
4868
4869namespace {
4870constexpr StringRef llvmMetadataSectionName = "llvm.metadata";
4871
4872/// Get-or-create a private constant string global in the llvm.metadata
4873/// section, deduplicated by string content.
4874mlir::LLVM::GlobalOp
4875getOrCreateAnnotationStringGlobal(mlir::OpBuilder &builder, mlir::Location loc,
4876 mlir::ModuleOp module, llvm::StringRef str,
4877 llvm::StringMap<mlir::LLVM::GlobalOp> &cache,
4878 bool isArg, unsigned addrSpace) {
4879 auto it = cache.find(str);
4880 if (it != cache.end())
4881 return it->second;
4882
4883 auto i8Ty = mlir::IntegerType::get(module.getContext(), 8);
4884 auto arrayTy = mlir::LLVM::LLVMArrayType::get(i8Ty, str.size() + 1);
4885 std::string name = ".str";
4886 if (!cache.empty())
4887 name += "." + std::to_string(cache.size());
4888 name += ".annotation";
4889 if (isArg)
4890 name += ".arg";
4891
4892 mlir::LLVM::GlobalOp strGlobal = mlir::LLVM::GlobalOp::create(
4893 builder, loc, arrayTy, /*isConstant=*/true, mlir::LLVM::Linkage::Private,
4894 name, mlir::StringAttr::get(module.getContext(), std::string(str) + '\0'),
4895 /*alignment=*/isArg ? 1 : 0, addrSpace);
4896 if (!isArg)
4897 strGlobal.setSection(llvmMetadataSectionName);
4898 strGlobal.setUnnamedAddr(mlir::LLVM::UnnamedAddr::Global);
4899 strGlobal.setDsoLocal(true);
4900 cache[str] = strGlobal;
4901 return strGlobal;
4902}
4903
4904/// Get-or-create a private constant struct holding the annotation arguments,
4905/// deduplicated by ArrayAttr identity.
4906mlir::LLVM::GlobalOp getOrCreateAnnotationArgsVar(
4907 mlir::OpBuilder &builder, mlir::Location loc, mlir::ModuleOp module,
4908 mlir::ArrayAttr argsAttr,
4909 llvm::StringMap<mlir::LLVM::GlobalOp> &argStringCache,
4910 llvm::MapVector<mlir::ArrayAttr, mlir::LLVM::GlobalOp> &argsCache,
4911 unsigned addrSpace) {
4912 auto it = argsCache.find(argsAttr);
4913 if (it != argsCache.end())
4914 return it->second;
4915
4916 auto ptrTy =
4917 mlir::LLVM::LLVMPointerType::get(builder.getContext(), addrSpace);
4918
4920 for (mlir::Attribute arg : argsAttr) {
4921 if (mlir::isa<mlir::StringAttr>(arg))
4922 fieldTypes.push_back(ptrTy);
4923 else if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(arg))
4924 fieldTypes.push_back(intAttr.getType());
4925 else
4926 llvm_unreachable("Unsupported annotation arg type");
4927 }
4928
4929 auto structTy =
4930 mlir::LLVM::LLVMStructType::getLiteral(builder.getContext(), fieldTypes);
4931 std::string name = ".args";
4932 if (!argsCache.empty())
4933 name += "." + std::to_string(argsCache.size());
4934 name += ".annotation";
4935
4936 mlir::LLVM::GlobalOp argsGlobal = mlir::LLVM::GlobalOp::create(
4937 builder, loc, structTy, /*isConstant=*/true, mlir::LLVM::Linkage::Private,
4938 name, mlir::Attribute(), /*alignment=*/0, addrSpace);
4939 argsGlobal.setSection(llvmMetadataSectionName);
4940 argsGlobal.setUnnamedAddr(mlir::LLVM::UnnamedAddr::Global);
4941 argsGlobal.setDsoLocal(true);
4942
4943 // Build the initializer block.
4944 argsGlobal.getRegion().push_back(new mlir::Block());
4945 mlir::OpBuilder initBuilder(module.getContext());
4946 initBuilder.setInsertionPointToEnd(argsGlobal.getInitializerBlock());
4947
4948 mlir::Value structInit =
4949 mlir::LLVM::UndefOp::create(initBuilder, loc, structTy);
4950 for (auto [idx, arg] : llvm::enumerate(argsAttr)) {
4951 if (auto strArg = mlir::dyn_cast<mlir::StringAttr>(arg)) {
4952 mlir::LLVM::GlobalOp strGlobal = getOrCreateAnnotationStringGlobal(
4953 builder, loc, module, strArg.getValue(), argStringCache,
4954 /*isArg=*/true, addrSpace);
4955 mlir::LLVM::AddressOfOp strAddr = mlir::LLVM::AddressOfOp::create(
4956 initBuilder, loc, ptrTy, strGlobal.getSymName());
4957 structInit = mlir::LLVM::InsertValueOp::create(initBuilder, loc,
4958 structInit, strAddr, idx);
4959 } else if (auto intArg = mlir::dyn_cast<mlir::IntegerAttr>(arg)) {
4960 mlir::LLVM::ConstantOp intConst = mlir::LLVM::ConstantOp::create(
4961 initBuilder, loc, intArg.getType(), intArg.getValue());
4962 structInit = mlir::LLVM::InsertValueOp::create(initBuilder, loc,
4963 structInit, intConst, idx);
4964 } else {
4965 llvm_unreachable("Unsupported annotation arg type");
4966 }
4967 }
4968 mlir::LLVM::ReturnOp::create(initBuilder, loc, structInit);
4969
4970 argsCache[argsAttr] = argsGlobal;
4971 return argsGlobal;
4972}
4973
4974/// Resolve a possibly-fused MLIR Location to a FileLineColLoc, returning
4975/// {filename, line}. Returns {empty, 0} if no usable file location is found.
4976std::pair<llvm::StringRef, unsigned> extractFileLine(mlir::Location loc) {
4977 mlir::Location resolved = loc;
4978 if (auto fused = mlir::dyn_cast<mlir::FusedLoc>(resolved)) {
4979 if (!fused.getLocations().empty())
4980 resolved = fused.getLocations()[0];
4981 }
4982 if (auto fl = mlir::dyn_cast<mlir::FileLineColLoc>(resolved))
4983 return {fl.getFilename().getValue(), fl.getLine()};
4984 return {"", 0};
4985}
4986
4987/// The name, file, line, and args operands of the llvm.*annotation intrinsics.
4988struct AnnotationOperands {
4989 mlir::Value name, file, line, args;
4990};
4991AnnotationOperands getAnnotationOperands(mlir::OpBuilder &builder,
4992 mlir::Location loc,
4993 cir::AnnotationAttr annotation,
4994 LLVMAnnotationGlobals &globals) {
4995 auto module = builder.getInsertionBlock()
4996 ->getParentOp()
4997 ->getParentOfType<mlir::ModuleOp>();
4998 auto [filename, line] = extractFileLine(loc);
4999 mlir::ArrayAttr args = annotation.getArgs();
5000 mlir::LLVM::GlobalOp nameGlobal, fileGlobal, argsGlobal;
5001 {
5002 mlir::OpBuilder::InsertionGuard guard(builder);
5003 builder.setInsertionPointToEnd(module.getBody());
5004 nameGlobal = getOrCreateAnnotationStringGlobal(
5005 builder, loc, module, annotation.getName().getValue(),
5006 globals.stringCache, /*isArg=*/false, globals.addrSpace);
5007 fileGlobal = getOrCreateAnnotationStringGlobal(
5008 builder, loc, module, filename, globals.stringCache, /*isArg=*/false,
5009 globals.addrSpace);
5010 if (args && !args.empty())
5011 argsGlobal = getOrCreateAnnotationArgsVar(
5012 builder, loc, module, args, globals.argStringCache, globals.argsCache,
5013 globals.addrSpace);
5014 }
5015
5016 auto ptrTy =
5017 mlir::LLVM::LLVMPointerType::get(builder.getContext(), globals.addrSpace);
5018 AnnotationOperands ops;
5019 ops.name = mlir::LLVM::AddressOfOp::create(builder, loc, ptrTy,
5020 nameGlobal.getSymName());
5021 ops.file = mlir::LLVM::AddressOfOp::create(builder, loc, ptrTy,
5022 fileGlobal.getSymName());
5023 ops.line =
5024 mlir::LLVM::ConstantOp::create(builder, loc, builder.getI32Type(), line);
5025 if (argsGlobal)
5026 ops.args = mlir::LLVM::AddressOfOp::create(builder, loc, ptrTy,
5027 argsGlobal.getSymName());
5028 else
5029 ops.args = mlir::LLVM::ZeroOp::create(builder, loc, ptrTy);
5030 return ops;
5031}
5032} // namespace
5033
5034mlir::LogicalResult CIRToLLVMVarAnnotationOpLowering::matchAndRewrite(
5035 cir::VarAnnotationOp op, OpAdaptor adaptor,
5036 mlir::ConversionPatternRewriter &rewriter) const {
5037 AnnotationOperands ops = getAnnotationOperands(
5038 rewriter, op.getLoc(), op.getAnnotation(), annotationGlobals);
5039 rewriter.replaceOpWithNewOp<mlir::LLVM::VarAnnotation>(
5040 op, adaptor.getAddr(), ops.name, ops.file, ops.line, ops.args);
5041 return mlir::success();
5042}
5043
5044mlir::LogicalResult CIRToLLVMPtrAnnotationOpLowering::matchAndRewrite(
5045 cir::PtrAnnotationOp op, OpAdaptor adaptor,
5046 mlir::ConversionPatternRewriter &rewriter) const {
5047 AnnotationOperands ops = getAnnotationOperands(
5048 rewriter, op.getLoc(), op.getAnnotation(), annotationGlobals);
5049 rewriter.replaceOpWithNewOp<mlir::LLVM::PtrAnnotation>(
5050 op, adaptor.getAddr().getType(), adaptor.getAddr(), ops.name, ops.file,
5051 ops.line, ops.args);
5052 return mlir::success();
5053}
5054
5055mlir::LogicalResult CIRToLLVMAnnotationOpLowering::matchAndRewrite(
5056 cir::AnnotationOp op, OpAdaptor adaptor,
5057 mlir::ConversionPatternRewriter &rewriter) const {
5058 AnnotationOperands ops = getAnnotationOperands(
5059 rewriter, op.getLoc(), op.getAnnotation(), annotationGlobals);
5060 rewriter.replaceOpWithNewOp<mlir::LLVM::Annotation>(
5061 op, adaptor.getValue().getType(), adaptor.getValue(), ops.name, ops.file,
5062 ops.line);
5063 return mlir::success();
5064}
5065
5067 auto handleArray = [&](mlir::StringAttr symName, mlir::ArrayAttr arr,
5068 mlir::Location loc) {
5069 if (!arr)
5070 return;
5071 for (mlir::Attribute a : arr)
5072 if (auto annot = mlir::dyn_cast<cir::AnnotationAttr>(a))
5073 collectedAnnotations.emplace_back(symName, annot, loc);
5074 };
5075
5076 // Walk in IR order: GlobalOps first (they appear before functions in the
5077 // module body), then FuncOps. This matches OGCG's emission order.
5078 module.walk([&](cir::GlobalOp op) {
5079 handleArray(op.getSymNameAttr(), op.getAnnotationsAttr(), op.getLoc());
5080 });
5081 module.walk([&](cir::FuncOp op) {
5082 handleArray(op.getSymNameAttr(), op.getAnnotationsAttr(), op.getLoc());
5083 });
5084}
5085
5087 mlir::ModuleOp module, LLVMAnnotationGlobals &annotationGlobals) {
5088 if (collectedAnnotations.empty())
5089 return;
5090
5091 mlir::MLIRContext *ctx = module.getContext();
5092 mlir::OpBuilder builder(ctx);
5093 builder.setInsertionPointToEnd(&module.getBodyRegion().back());
5094
5095 unsigned addrSpace = annotationGlobals.addrSpace;
5096 auto ptrTy = mlir::LLVM::LLVMPointerType::get(ctx, addrSpace);
5097 auto i32Ty = builder.getI32Type();
5098
5099 // Each entry: { ptr, ptr, ptr, i32, ptr }.
5100 auto entryTy = mlir::LLVM::LLVMStructType::getLiteral(
5101 ctx, {ptrTy, ptrTy, ptrTy, i32Ty, ptrTy});
5102 auto arrayTy =
5103 mlir::LLVM::LLVMArrayType::get(entryTy, collectedAnnotations.size());
5104
5105 mlir::Location moduleLoc = module.getLoc();
5106 auto annotationsGlobal = mlir::LLVM::GlobalOp::create(
5107 builder, moduleLoc, arrayTy, /*isConstant=*/false,
5108 mlir::LLVM::Linkage::Appending, "llvm.global.annotations",
5109 mlir::Attribute(), /*alignment=*/0, addrSpace);
5110 annotationsGlobal.setSection(llvmMetadataSectionName);
5111
5112 // Strings/args constants must come *before* @llvm.global.annotations to
5113 // match OGCG output order. Insert them just before the annotations global.
5114 mlir::OpBuilder constsBuilder(ctx);
5115 constsBuilder.setInsertionPoint(annotationsGlobal);
5116
5117 llvm::StringMap<mlir::LLVM::GlobalOp> &stringCache =
5118 annotationGlobals.stringCache;
5119 llvm::StringMap<mlir::LLVM::GlobalOp> &argStringCache =
5120 annotationGlobals.argStringCache;
5121 llvm::MapVector<mlir::ArrayAttr, mlir::LLVM::GlobalOp> &argsCache =
5122 annotationGlobals.argsCache;
5123
5124 // Build the initializer block of @llvm.global.annotations.
5125 annotationsGlobal.getRegion().push_back(new mlir::Block());
5126 mlir::OpBuilder initBuilder(ctx);
5127 initBuilder.setInsertionPointToEnd(annotationsGlobal.getInitializerBlock());
5128
5129 mlir::Value arrayVal =
5130 mlir::LLVM::UndefOp::create(initBuilder, moduleLoc, arrayTy);
5131
5132 for (auto [idx, entry] : llvm::enumerate(collectedAnnotations)) {
5133 mlir::Value entryVal =
5134 mlir::LLVM::UndefOp::create(initBuilder, moduleLoc, entryTy);
5135
5136 // Field 0: ptr to the annotated symbol. (Literal zero is ambiguous on
5137 // InsertValueOp::create, wrap in a SmallVector.)
5139 unsigned symAddrSpace = 0;
5140 if (auto global = mlir::dyn_cast_if_present<mlir::LLVM::GlobalOp>(
5141 mlir::SymbolTable::lookupSymbolIn(module, entry.symName)))
5142 symAddrSpace = global.getAddrSpace();
5143 mlir::Value symAddr = mlir::LLVM::AddressOfOp::create(
5144 initBuilder, moduleLoc,
5145 mlir::LLVM::LLVMPointerType::get(ctx, symAddrSpace),
5146 entry.symName.getValue());
5147 if (symAddrSpace != addrSpace)
5148 symAddr = mlir::LLVM::AddrSpaceCastOp::create(initBuilder, moduleLoc,
5149 ptrTy, symAddr);
5150 entryVal = mlir::LLVM::InsertValueOp::create(initBuilder, moduleLoc,
5151 entryVal, symAddr, zero);
5152
5153 // Field 1: ptr to the annotation name string.
5154 mlir::LLVM::GlobalOp nameGlobal = getOrCreateAnnotationStringGlobal(
5155 constsBuilder, moduleLoc, module, entry.annotation.getName().getValue(),
5156 stringCache, /*isArg=*/false, addrSpace);
5157 mlir::LLVM::AddressOfOp nameAddr = mlir::LLVM::AddressOfOp::create(
5158 initBuilder, moduleLoc, ptrTy, nameGlobal.getSymName());
5159 entryVal = mlir::LLVM::InsertValueOp::create(initBuilder, moduleLoc,
5160 entryVal, nameAddr, 1);
5161
5162 // Fields 2 and 3: ptr to filename string and line number.
5163 auto [filename, line] = extractFileLine(entry.loc);
5164 mlir::LLVM::GlobalOp fileGlobal = getOrCreateAnnotationStringGlobal(
5165 constsBuilder, moduleLoc, module, filename, stringCache,
5166 /*isArg=*/false, addrSpace);
5167 mlir::LLVM::AddressOfOp fileAddr = mlir::LLVM::AddressOfOp::create(
5168 initBuilder, moduleLoc, ptrTy, fileGlobal.getSymName());
5169 entryVal = mlir::LLVM::InsertValueOp::create(initBuilder, moduleLoc,
5170 entryVal, fileAddr, 2);
5171 mlir::LLVM::ConstantOp lineConst =
5172 mlir::LLVM::ConstantOp::create(initBuilder, moduleLoc, i32Ty, line);
5173 entryVal = mlir::LLVM::InsertValueOp::create(initBuilder, moduleLoc,
5174 entryVal, lineConst, 3);
5175
5176 // Field 4: ptr to args, or null if none.
5177 mlir::ArrayAttr args = entry.annotation.getArgs();
5178 mlir::Value argsField;
5179 if (!args || args.empty()) {
5180 argsField = mlir::LLVM::ZeroOp::create(initBuilder, moduleLoc, ptrTy);
5181 } else {
5182 mlir::LLVM::GlobalOp argsGlobal =
5183 getOrCreateAnnotationArgsVar(constsBuilder, moduleLoc, module, args,
5184 argStringCache, argsCache, addrSpace);
5185 argsField = mlir::LLVM::AddressOfOp::create(initBuilder, moduleLoc, ptrTy,
5186 argsGlobal.getSymName());
5187 }
5188 entryVal = mlir::LLVM::InsertValueOp::create(initBuilder, moduleLoc,
5189 entryVal, argsField, 4);
5190
5191 arrayVal = mlir::LLVM::InsertValueOp::create(initBuilder, moduleLoc,
5192 arrayVal, entryVal, idx);
5193 }
5194
5195 mlir::LLVM::ReturnOp::create(initBuilder, moduleLoc, arrayVal);
5196}
5197
5199 LLVMBlockAddressInfo &blockInfoAddr) {
5200
5201 mlir::ModuleOp module = getOperation();
5202 mlir::OpBuilder opBuilder(module.getContext());
5203 for (auto &[blockAddOp, blockInfo] :
5204 blockInfoAddr.getUnresolvedBlockAddress()) {
5205 mlir::LLVM::BlockTagOp resolvedLabel =
5206 blockInfoAddr.lookupBlockTag(blockInfo);
5207 assert(resolvedLabel && "expected BlockTagOp to already be emitted");
5208 mlir::FlatSymbolRefAttr fnSym = blockInfo.getFunc();
5209 auto blkAddTag = mlir::LLVM::BlockAddressAttr::get(
5210 opBuilder.getContext(), fnSym, resolvedLabel.getTagAttr());
5211 blockAddOp.setBlockAddrAttr(blkAddTag);
5212 }
5213 blockInfoAddr.clearUnresolvedMap();
5214}
5215
5216void ConvertCIRToLLVMPass::processCIRAttrs(mlir::ModuleOp module) {
5217 // Lower the module attributes to LLVM equivalents.
5218 if (mlir::Attribute tripleAttr =
5219 module->getAttr(cir::CIRDialect::getTripleAttrName()))
5220 module->setAttr(mlir::LLVM::LLVMDialect::getTargetTripleAttrName(),
5221 tripleAttr);
5222
5223 if (mlir::Attribute asmAttr =
5224 module->getAttr(cir::CIRDialect::getModuleLevelAsmAttrName()))
5225 module->setAttr(mlir::LLVM::LLVMDialect::getModuleLevelAsmAttrName(),
5226 asmAttr);
5227
5228 if (auto framePointerAttr = module->getAttrOfType<cir::FramePointerKindAttr>(
5229 cir::CIRDialect::getModuleFramePointerAttrName())) {
5230 mlir::OpBuilder builder(module.getContext());
5231 builder.setInsertionPointToEnd(module.getBody());
5232 auto flag = mlir::LLVM::ModuleFlagAttr::get(
5233 module.getContext(), mlir::LLVM::ModFlagBehavior::Max,
5234 builder.getStringAttr("frame-pointer"),
5235 builder.getI32IntegerAttr(static_cast<int32_t>(
5236 convertFramePointerKindToLLVMIR(framePointerAttr.getValue()))));
5237 mlir::LLVM::ModuleFlagsOp::create(builder, module.getLoc(),
5238 builder.getArrayAttr({flag}));
5239 }
5240
5242}
5243
5244namespace {
5245/// Convert the kernel operands of gpu.launch_func to the types expected by the
5246/// converted kernel signature.
5247struct GPULaunchFuncOperandLowering : public mlir::ConversionPattern {
5248 GPULaunchFuncOperandLowering(const mlir::TypeConverter &converter,
5249 mlir::MLIRContext *ctx)
5250 : ConversionPattern(converter, "gpu.launch_func", /*benefit=*/1, ctx) {}
5251
5252 mlir::LogicalResult
5253 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
5254 mlir::ConversionPatternRewriter &rewriter) const override {
5255 rewriter.modifyOpInPlace(op,
5256 [operands, &op] { op->setOperands(operands); });
5257 return mlir::success();
5258 }
5259};
5260} // namespace
5261
5263 llvm::TimeTraceScope scope("Convert CIR to LLVM Pass");
5264
5265 mlir::ModuleOp module = getOperation();
5266 // CIR type of each symbol before lowering, for lookups that find the
5267 // already-lowered LLVM symbol after replacement. This must cover every
5268 // symbol kind that can be replaced: a kind missing from this loop
5269 // quietly falls back to the adjusted LLVM type in readers (here and in
5270 // LoweringHelpers).
5271 // Aliases are covered: they are GlobalOp and FuncOp ops with an
5272 // aliasee, not separate symbol kinds.
5273 CIRPreConversionTypeMap preConversionTypes;
5274 for (mlir::Operation &op : module.getBody()->getOperations()) {
5275 if (auto globalOp = mlir::dyn_cast<cir::GlobalOp>(op))
5276 preConversionTypes[globalOp.getSymName()] = globalOp.getSymType();
5277 else if (auto funcOp = mlir::dyn_cast<cir::FuncOp>(op))
5278 preConversionTypes[funcOp.getSymName()] = funcOp.getFunctionType();
5279 }
5280 mlir::DataLayout dl(module);
5281 mlir::LLVMTypeConverter converter(&getContext());
5282 prepareTypeConverter(converter, dl);
5283
5284 /// Tracks the state required to lower CIR `LabelOp` and `BlockAddressOp`.
5285 /// Maps labels to their corresponding `BlockTagOp` and keeps bookkeeping
5286 /// of unresolved `BlockAddressOp`s until they are matched with the
5287 /// corresponding `BlockTagOp` in `resolveBlockAddressOp`.
5288 LLVMBlockAddressInfo blockInfoAddr;
5289 /// Cached symbol table collection used by call lowering patterns to avoid
5290 /// repeated O(M) module-wide symbol scans for every call site.
5291 mlir::SymbolTableCollection symbolTables;
5292 LLVMAnnotationGlobals annotationGlobals(module);
5293 mlir::RewritePatternSet patterns(&getContext());
5294 patterns.add<CIRToLLVMVarAnnotationOpLowering,
5295 CIRToLLVMPtrAnnotationOpLowering, CIRToLLVMAnnotationOpLowering>(
5296 converter, patterns.getContext(), dl, symbolTables, annotationGlobals);
5297 patterns.add<CIRToLLVMBlockAddressOpLowering, CIRToLLVMLabelOpLowering>(
5298 converter, patterns.getContext(), dl, symbolTables, blockInfoAddr);
5299 patterns.add<CIRToLLVMGlobalOpLowering, CIRToLLVMConstantOpLowering>(
5300 converter, patterns.getContext(), dl, symbolTables, blockInfoAddr,
5301 preConversionTypes);
5302
5303 patterns.add<
5304#define GET_LLVM_LOWERING_PATTERNS_LIST
5305#include "clang/CIR/Dialect/IR/CIRLowering.inc"
5306#undef GET_LLVM_LOWERING_PATTERNS_LIST
5307 >(converter, patterns.getContext(), dl, symbolTables);
5308 // Patterns reading replaced symbols take the pre-conversion type map.
5309 patterns
5310 .add<CIRToLLVMVTableAddrPointOpLowering, CIRToLLVMVTTAddrPointOpLowering>(
5311 converter, patterns.getContext(), dl, symbolTables,
5312 preConversionTypes);
5313
5314 processCIRAttrs(module);
5315
5316 // Collect annotation info from cir.func / cir.global before conversion;
5317 // the annotations attribute is filtered out during FuncOp/GlobalOp lowering.
5319
5320 // Resolve constant printf strings while their producers are still CIR.
5321 annotateAMDGPUPrintfStrings(module, symbolTables);
5322
5323 mlir::ConversionTarget target(getContext());
5324 target.addLegalOp<mlir::ModuleOp>();
5325 target.addLegalDialect<mlir::LLVM::LLVMDialect>();
5326 mlir::configureOpenMPToLLVMConversionLegality(target, converter);
5327 target.addLegalDialect<mlir::omp::OpenMPDialect>();
5328 mlir::populateOpenMPToLLVMConversionPatterns(converter, patterns);
5329 target.addIllegalDialect<mlir::BuiltinDialect, cir::CIRDialect,
5330 mlir::func::FuncDialect>();
5331 // Kernels outlined from CIR keep CIR types in their signature and launch
5332 // operands; convert them so later GPU-to-LLVM lowerings see LLVM types.
5333 mlir::populateFunctionOpInterfaceTypeConversionPattern("gpu.func", patterns,
5334 converter);
5335 patterns.add<GPULaunchFuncOperandLowering>(converter, &getContext());
5336 mlir::MLIRContext *ctx = &getContext();
5337 target.addDynamicallyLegalOp(
5338 mlir::OperationName("gpu.func", ctx), [&](mlir::Operation *op) {
5339 return converter.isSignatureLegal(mlir::cast<mlir::FunctionType>(
5340 mlir::cast<mlir::FunctionOpInterface>(op).getFunctionType()));
5341 });
5342 target.addDynamicallyLegalOp(
5343 mlir::OperationName("gpu.launch_func", ctx), [&](mlir::Operation *op) {
5344 return converter.isLegal(op->getOperandTypes());
5345 });
5346
5348 ops.push_back(module);
5349 cir::collectUnreachable(module, ops);
5350
5351 // One-shot conversion (no pattern rollback): rewrites materialize
5352 // immediately, skipping the IRRewrite/value-mapping bookkeeping. The
5353 // CIR patterns here are compatible: nothing dereferences the root op
5354 // after replacement, and the cached symbol table is maintained
5355 // explicitly at every module-symbol replacement.
5356 mlir::ConversionConfig config;
5357 config.allowPatternRollback = false;
5358 if (failed(
5359 applyPartialConversion(ops, target, std::move(patterns), config))) {
5360 signalPassFailure();
5361 return;
5362 }
5363
5364 // Drop CIR-native data-layout entries.
5365 if (auto dlSpec = mlir::dyn_cast_or_null<mlir::DataLayoutSpecAttr>(
5366 module->getAttr(mlir::DLTIDialect::kDataLayoutAttrName))) {
5368 for (mlir::DataLayoutEntryInterface entry : dlSpec.getEntries()) {
5369 if (entry.isTypeEntry()) {
5370 mlir::Type key = mlir::cast<mlir::Type>(entry.getKey());
5371 if (mlir::isa<cir::PointerType, cir::IntType, cir::VectorType>(key))
5372 continue;
5373 }
5374 kept.push_back(entry);
5375 }
5376 module->setAttr(mlir::DLTIDialect::kDataLayoutAttrName,
5377 mlir::DataLayoutSpecAttr::get(module.getContext(), kept));
5378 }
5379
5380 // Emit the llvm.global_ctors array.
5382 module, cir::CIRDialect::getGlobalCtorsAttrName(), "llvm.global_ctors",
5383 [](mlir::Attribute attr) {
5384 auto ctorAttr = mlir::cast<cir::GlobalCtorAttr>(attr);
5385 StringRef associated;
5386 if (mlir::FlatSymbolRefAttr assoc = ctorAttr.getAssociated())
5387 associated = assoc.getValue();
5388 return cir::GlobalCtorDtorEntry(ctorAttr.getName(),
5389 ctorAttr.getPriority(), associated);
5390 });
5391 // Emit the llvm.global_dtors array.
5393 module, cir::CIRDialect::getGlobalDtorsAttrName(), "llvm.global_dtors",
5394 [](mlir::Attribute attr) {
5395 auto dtorAttr = mlir::cast<cir::GlobalDtorAttr>(attr);
5396 StringRef associated;
5397 if (mlir::FlatSymbolRefAttr assoc = dtorAttr.getAssociated())
5398 associated = assoc.getValue();
5399 return cir::GlobalCtorDtorEntry(dtorAttr.getName(),
5400 dtorAttr.getPriority(), associated);
5401 });
5402 // Emit @llvm.global.annotations from the previously-collected entries.
5403 buildGlobalAnnotationsVar(module, annotationGlobals);
5404
5405 resolveBlockAddressOp(blockInfoAddr);
5406}
5407
5408mlir::LogicalResult CIRToLLVMBrOpLowering::matchAndRewrite(
5409 cir::BrOp op, OpAdaptor adaptor,
5410 mlir::ConversionPatternRewriter &rewriter) const {
5411 rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(op, adaptor.getOperands(),
5412 op.getDest());
5413 return mlir::LogicalResult::success();
5414}
5415
5416mlir::LogicalResult CIRToLLVMGetMemberOpLowering::matchAndRewrite(
5417 cir::GetMemberOp op, OpAdaptor adaptor,
5418 mlir::ConversionPatternRewriter &rewriter) const {
5419 mlir::Type llResTy = getTypeConverter()->convertType(op.getType());
5420 if (!llResTy)
5421 return emitTypeConversionError(op, op.getType());
5422 mlir::Type pointee = op.getAddrTy().getPointee();
5423
5424 if (mlir::isa<cir::UnionType>(pointee)) {
5425 // Union members share the address space, so we just need a bitcast to
5426 // conform to type-checking.
5427 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(op, llResTy,
5428 adaptor.getAddr());
5429 return mlir::success();
5430 }
5431
5432 auto structTy = mlir::cast<cir::StructType>(pointee);
5433 // Since the base address is a pointer to an aggregate, the first offset
5434 // is always zero. The second offset tells us which member it will access.
5435 // Members that own no bytes are left out of the LLVM body, so the CIR member
5436 // index has to be mapped rather than used directly.
5438 0, static_cast<int32_t>(structTy.getLLVMFieldIndex(op.getIndex()))};
5439 const mlir::Type elementTy = getTypeConverter()->convertType(structTy);
5440 if (!elementTy)
5441 return emitTypeConversionError(op, structTy);
5442 // Struct member accesses are always inbounds and nuw: the base pointer
5443 // is valid and the member offset is a positive, constant offset within
5444 // the struct layout, so it cannot wrap. This matches LLVM's
5445 // IRBuilder::CreateStructGEP.
5446 mlir::LLVM::GEPNoWrapFlags flags =
5447 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
5448 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
5449 op, llResTy, elementTy, adaptor.getAddr(), offset, flags);
5450 return mlir::success();
5451}
5452
5453mlir::LogicalResult CIRToLLVMExtractMemberOpLowering::matchAndRewrite(
5454 cir::ExtractMemberOp op, OpAdaptor adaptor,
5455 mlir::ConversionPatternRewriter &rewriter) const {
5456 if (mlir::isa<cir::UnionType>(op.getRecord().getType())) {
5457 op.emitError("cir.extract_member cannot extract member from a union");
5458 return mlir::failure();
5459 }
5460
5461 auto structTy = mlir::cast<cir::StructType>(op.getRecord().getType());
5462 std::int64_t indices[1] = {
5463 static_cast<std::int64_t>(structTy.getLLVMFieldIndex(op.getIndex()))};
5464 rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractValueOp>(
5465 op, adaptor.getRecord(), indices);
5466 return mlir::success();
5467}
5468
5469mlir::LogicalResult CIRToLLVMInsertMemberOpLowering::matchAndRewrite(
5470 cir::InsertMemberOp op, OpAdaptor adaptor,
5471 mlir::ConversionPatternRewriter &rewriter) const {
5472 if (mlir::isa<cir::UnionType>(op.getRecord().getType())) {
5473 op.emitError("cir.update_member cannot update member of a union");
5474 return mlir::failure();
5475 }
5476
5477 auto structTy = mlir::cast<cir::StructType>(op.getRecord().getType());
5478 std::int64_t indices[1] = {
5479 static_cast<std::int64_t>(structTy.getLLVMFieldIndex(op.getIndex()))};
5480 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
5481 op, adaptor.getRecord(), adaptor.getValue(), indices);
5482 return mlir::success();
5483}
5484
5485void createLLVMFuncOpIfNotExist(mlir::ConversionPatternRewriter &rewriter,
5486 mlir::SymbolTableCollection &symbolTables,
5487 mlir::Operation *srcOp, llvm::StringRef fnName,
5488 mlir::Type fnTy, mlir::ArrayAttr argAttrs,
5489 mlir::ArrayAttr resAttrs) {
5490 mlir::ModuleOp modOp = srcOp->getParentOfType<mlir::ModuleOp>();
5491 mlir::Operation *sourceSymbol = symbolTables.lookupSymbolIn(
5492 modOp, mlir::StringAttr::get(fnTy.getContext(), fnName));
5493 if (!sourceSymbol) {
5494 mlir::OpBuilder::InsertionGuard guard(rewriter);
5495 auto enclosingFnOp = srcOp->getParentOfType<mlir::LLVM::LLVMFuncOp>();
5496 rewriter.setInsertionPoint(enclosingFnOp);
5497 auto fn =
5498 mlir::LLVM::LLVMFuncOp::create(rewriter, srcOp->getLoc(), fnName, fnTy);
5499 if (argAttrs)
5500 fn.setArgAttrsAttr(argAttrs);
5501 if (resAttrs)
5502 fn.setResAttrsAttr(resAttrs);
5503 // Update the symbol table.
5504 symbolTables.getSymbolTable(fn->getParentOp()).insert(fn);
5505 }
5506}
5507
5508mlir::LogicalResult CIRToLLVMThrowOpLowering::matchAndRewrite(
5509 cir::ThrowOp op, OpAdaptor adaptor,
5510 mlir::ConversionPatternRewriter &rewriter) const {
5511 mlir::Location loc = op.getLoc();
5512 auto voidTy = mlir::LLVM::LLVMVoidType::get(getContext());
5513
5514 // TODO(cir): set the runtime calling convention on the runtime calls below.
5516
5517 if (op.rethrows()) {
5518 auto funcTy = mlir::LLVM::LLVMFunctionType::get(voidTy, {});
5519
5520 // Get or create `declare void @__cxa_rethrow()`
5521 const llvm::StringRef functionName = "__cxa_rethrow";
5522 createLLVMFuncOpIfNotExist(rewriter, symbolTables, op, functionName,
5523 funcTy);
5524
5525 auto cxaRethrow = mlir::LLVM::CallOp::create(
5526 rewriter, loc, mlir::TypeRange{}, functionName);
5527
5528 rewriter.replaceOp(op, cxaRethrow);
5529 return mlir::success();
5530 }
5531
5532 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5533 auto fnTy = mlir::LLVM::LLVMFunctionType::get(
5534 voidTy, {llvmPtrTy, llvmPtrTy, llvmPtrTy});
5535
5536 // Get or create `declare void @__cxa_throw(ptr, ptr, ptr)`
5537 const llvm::StringRef fnName = "__cxa_throw";
5538 createLLVMFuncOpIfNotExist(rewriter, symbolTables, op, fnName, fnTy);
5539
5540 mlir::Value typeInfo = mlir::LLVM::AddressOfOp::create(
5541 rewriter, loc, mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
5542 adaptor.getTypeInfoAttr());
5543
5544 mlir::Value dtor;
5545 if (op.getDtor()) {
5546 dtor = mlir::LLVM::AddressOfOp::create(rewriter, loc, llvmPtrTy,
5547 adaptor.getDtorAttr());
5548 } else {
5549 dtor = mlir::LLVM::ZeroOp::create(rewriter, loc, llvmPtrTy);
5550 }
5551
5552 auto cxaThrowCall = mlir::LLVM::CallOp::create(
5553 rewriter, loc, mlir::TypeRange{}, fnName,
5554 mlir::ValueRange{adaptor.getExceptionPtr(), typeInfo, dtor});
5555
5556 rewriter.replaceOp(op, cxaThrowCall);
5557 return mlir::success();
5558}
5559
5560mlir::LogicalResult CIRToLLVMAllocExceptionOpLowering::matchAndRewrite(
5561 cir::AllocExceptionOp op, OpAdaptor adaptor,
5562 mlir::ConversionPatternRewriter &rewriter) const {
5563 // Get or create `declare ptr @__cxa_allocate_exception(i64)`
5564 StringRef fnName = "__cxa_allocate_exception";
5565 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5566 auto int64Ty = mlir::IntegerType::get(rewriter.getContext(), 64);
5567 auto fnTy = mlir::LLVM::LLVMFunctionType::get(llvmPtrTy, {int64Ty});
5568
5569 createLLVMFuncOpIfNotExist(rewriter, symbolTables, op, fnName, fnTy);
5570 auto exceptionSize = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
5571 adaptor.getSizeAttr());
5572
5573 auto allocaExceptionCall = mlir::LLVM::CallOp::create(
5574 rewriter, op.getLoc(), mlir::TypeRange{llvmPtrTy}, fnName,
5575 mlir::ValueRange{exceptionSize});
5576
5577 rewriter.replaceOp(op, allocaExceptionCall);
5578 return mlir::success();
5579}
5580
5581static mlir::LLVM::LLVMStructType
5582getLLVMLandingPadStructTy(mlir::ConversionPatternRewriter &rewriter) {
5583 // Create the landing pad type: struct { ptr, i32 }
5584 mlir::MLIRContext *ctx = rewriter.getContext();
5585 auto llvmPtr = mlir::LLVM::LLVMPointerType::get(ctx);
5586 llvm::SmallVector<mlir::Type> structFields = {llvmPtr, rewriter.getI32Type()};
5587 return mlir::LLVM::LLVMStructType::getLiteral(ctx, structFields);
5588}
5589
5590mlir::LogicalResult CIRToLLVMEhInflightOpLowering::matchAndRewrite(
5591 cir::EhInflightOp op, OpAdaptor adaptor,
5592 mlir::ConversionPatternRewriter &rewriter) const {
5593 auto llvmFn = op->getParentOfType<mlir::LLVM::LLVMFuncOp>();
5594 assert(llvmFn && "expected LLVM function parent");
5595 mlir::Block *entryBlock = &llvmFn.getRegion().front();
5596 assert(entryBlock->isEntryBlock());
5597
5598 mlir::ArrayAttr catchListAttr = op.getCatchTypeListAttr();
5599 mlir::ArrayAttr filterListAttr = op.getFilterTypeListAttr();
5600 mlir::SmallVector<mlir::Value> landingPadClauses;
5601
5602 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5603 mlir::Location loc = op.getLoc();
5604
5605 // %landingpad = landingpad { ptr, i32 }
5606 // Note that since llvm.landingpad has to be the first operation on the
5607 // block, any needed value for its operands has to be added somewhere else.
5608 if (catchListAttr) {
5609 // catch ptr @_ZTIi
5610 // catch ptr @_ZTIPKc
5611 for (mlir::Attribute catchAttr : catchListAttr) {
5612 auto symAttr = cast<mlir::FlatSymbolRefAttr>(catchAttr);
5613 // Generate `llvm.mlir.addressof` for each symbol, and place those
5614 // operations in the LLVM function entry basic block.
5615 mlir::OpBuilder::InsertionGuard guard(rewriter);
5616 rewriter.setInsertionPointToStart(entryBlock);
5617 mlir::Value addrOp = mlir::LLVM::AddressOfOp::create(
5618 rewriter, loc, llvmPtrTy, symAttr.getValue());
5619 landingPadClauses.push_back(addrOp);
5620 }
5621 }
5622
5623 // Emit a catch-all clause (catch ptr null) when:
5624 // - The catch_all attribute is set (typed catches + catch-all), or
5625 // - No typed catches, no cleanup, and no filter (legacy pure catch-all)
5626 if (op.getCatchAll() ||
5627 (!catchListAttr && !op.getCleanup() && !filterListAttr)) {
5628 mlir::OpBuilder::InsertionGuard guard(rewriter);
5629 rewriter.setInsertionPointToStart(entryBlock);
5630 mlir::Value nullOp = mlir::LLVM::ZeroOp::create(rewriter, loc, llvmPtrTy);
5631 landingPadClauses.push_back(nullOp);
5632 }
5633
5634 if (filterListAttr) {
5635 // Filter clauses are array-typed landingpad operands:
5636 // filter [N x ptr] [ptr @_ZTIi, ...]
5637 // An empty list is throw() and lowers to [0 x ptr] zeroinitializer.
5638 mlir::OpBuilder::InsertionGuard guard(rewriter);
5639 rewriter.setInsertionPointToStart(entryBlock);
5640 auto filterArrayTy =
5641 mlir::LLVM::LLVMArrayType::get(llvmPtrTy, filterListAttr.size());
5642 mlir::Value filterVal;
5643 if (filterListAttr.empty()) {
5644 filterVal = mlir::LLVM::ZeroOp::create(rewriter, loc, filterArrayTy);
5645 } else {
5646 filterVal = mlir::LLVM::UndefOp::create(rewriter, loc, filterArrayTy);
5647 for (auto [i, filterAttr] : llvm::enumerate(filterListAttr)) {
5648 auto symAttr = mlir::cast<mlir::FlatSymbolRefAttr>(filterAttr);
5649 mlir::Value addrOp = mlir::LLVM::AddressOfOp::create(
5650 rewriter, loc, llvmPtrTy, symAttr.getValue());
5651 filterVal = mlir::LLVM::InsertValueOp::create(
5652 rewriter, loc, filterVal, addrOp,
5653 llvm::ArrayRef<int64_t>{static_cast<int64_t>(i)});
5654 }
5655 }
5656 landingPadClauses.push_back(filterVal);
5657 }
5658
5659 // %slot = extractvalue { ptr, i32 } %x, 0
5660 // %selector = extractvalue { ptr, i32 } %x, 1
5661 mlir::LLVM::LLVMStructType llvmLandingPadStructTy =
5662 getLLVMLandingPadStructTy(rewriter);
5663 auto landingPadOp = mlir::LLVM::LandingpadOp::create(
5664 rewriter, loc, llvmLandingPadStructTy, landingPadClauses);
5665
5666 // The LLVM cleanup flag is only needed when there is no catch-all handler,
5667 // since catch-all (catch ptr null) already ensures the personality function
5668 // enters the landing pad for all exception types.
5669 if (op.getCleanup() && !op.getCatchAll())
5670 landingPadOp.setCleanup(true);
5671
5672 mlir::Value slot =
5673 mlir::LLVM::ExtractValueOp::create(rewriter, loc, landingPadOp, 0);
5674 mlir::Value selector =
5675 mlir::LLVM::ExtractValueOp::create(rewriter, loc, landingPadOp, 1);
5676 rewriter.replaceOp(op, mlir::ValueRange{slot, selector});
5677
5678 return mlir::success();
5679}
5680
5681mlir::LogicalResult CIRToLLVMResumeFlatOpLowering::matchAndRewrite(
5682 cir::ResumeFlatOp op, OpAdaptor adaptor,
5683 mlir::ConversionPatternRewriter &rewriter) const {
5684 // %lpad.val = insertvalue { ptr, i32 } poison, ptr %exception_ptr, 0
5685 // %lpad.val2 = insertvalue { ptr, i32 } %lpad.val, i32 %selector, 1
5686 // resume { ptr, i32 } %lpad.val2
5687 mlir::Type llvmLandingPadStructTy = getLLVMLandingPadStructTy(rewriter);
5688 mlir::Value poison = mlir::LLVM::PoisonOp::create(rewriter, op.getLoc(),
5689 llvmLandingPadStructTy);
5690
5691 SmallVector<int64_t> slotIdx = {0};
5692 mlir::Value slot = mlir::LLVM::InsertValueOp::create(
5693 rewriter, op.getLoc(), poison, adaptor.getExceptionPtr(), slotIdx);
5694
5695 SmallVector<int64_t> selectorIdx = {1};
5696 mlir::Value selector = mlir::LLVM::InsertValueOp::create(
5697 rewriter, op.getLoc(), slot, adaptor.getTypeId(), selectorIdx);
5698
5699 rewriter.replaceOpWithNewOp<mlir::LLVM::ResumeOp>(op, selector);
5700 return mlir::success();
5701}
5702
5703mlir::LogicalResult CIRToLLVMEhTypeIdOpLowering::matchAndRewrite(
5704 cir::EhTypeIdOp op, OpAdaptor adaptor,
5705 mlir::ConversionPatternRewriter &rewriter) const {
5706 mlir::Value addrOp = mlir::LLVM::AddressOfOp::create(
5707 rewriter, op.getLoc(),
5708 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
5709 op.getTypeSymAttr());
5710 rewriter.replaceOpWithNewOp<mlir::LLVM::EhTypeidForOp>(
5711 op, rewriter.getI32Type(), addrOp);
5712 return mlir::success();
5713}
5714
5715mlir::LogicalResult CIRToLLVMEhSetjmpOpLowering::matchAndRewrite(
5716 cir::EhSetjmpOp op, OpAdaptor adaptor,
5717 mlir::ConversionPatternRewriter &rewriter) const {
5718 mlir::Type returnType = typeConverter->convertType(op.getType());
5719 mlir::LLVM::CallIntrinsicOp newOp =
5720 createCallLLVMIntrinsicOp(rewriter, op.getLoc(), "llvm.eh.sjlj.setjmp",
5721 returnType, adaptor.getEnv());
5722 rewriter.replaceOp(op, newOp);
5723 return mlir::success();
5724}
5725
5726mlir::LogicalResult CIRToLLVMEhLongjmpOpLowering::matchAndRewrite(
5727 cir::EhLongjmpOp op, OpAdaptor adaptor,
5728 mlir::ConversionPatternRewriter &rewriter) const {
5729 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.eh.sjlj.longjmp",
5730 /*resultTy=*/{}, adaptor.getOperands());
5731 return mlir::success();
5732}
5733
5734mlir::LogicalResult CIRToLLVMTrapOpLowering::matchAndRewrite(
5735 cir::TrapOp op, OpAdaptor adaptor,
5736 mlir::ConversionPatternRewriter &rewriter) const {
5737 mlir::Location loc = op->getLoc();
5738 rewriter.eraseOp(op);
5739
5740 mlir::LLVM::Trap::create(rewriter, loc);
5741
5742 // Note that the call to llvm.trap is not a terminator in LLVM dialect.
5743 // So we must emit an additional llvm.unreachable to terminate the current
5744 // block.
5745 mlir::LLVM::UnreachableOp::create(rewriter, loc);
5746
5747 return mlir::success();
5748}
5749
5750static mlir::Value
5751getValueForVTableSymbol(mlir::Operation *op,
5752 mlir::ConversionPatternRewriter &rewriter,
5753 mlir::SymbolTableCollection &symbolTables,
5754 const mlir::TypeConverter *converter,
5755 const CIRPreConversionTypeMap &preConversionTypes,
5756 mlir::FlatSymbolRefAttr nameAttr, mlir::Type &eltType) {
5757 auto module = op->getParentOfType<mlir::ModuleOp>();
5758 mlir::Operation *symbol = symbolTables.lookupSymbolIn(module, nameAttr);
5759 if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(symbol)) {
5760 if (mlir::Type preType = preConversionTypes.lookup(nameAttr.getValue())) {
5761 eltType = converter->convertType(preType);
5762 if (!eltType) {
5763 emitTypeConversionError(op, preType)
5764 << " for vtable symbol " << nameAttr;
5765 return {};
5766 }
5767 } else {
5768 eltType = llvmSymbol.getType();
5769 }
5770 } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(symbol)) {
5771 eltType = converter->convertType(cirSymbol.getSymType());
5772 if (!eltType) {
5773 emitTypeConversionError(op, cirSymbol.getSymType())
5774 << " for vtable symbol " << nameAttr;
5775 return {};
5776 }
5777 } else {
5778 op->emitError() << "unexpected symbol type for " << symbol;
5779 return {};
5780 }
5781
5782 return mlir::LLVM::AddressOfOp::create(
5783 rewriter, op->getLoc(),
5784 mlir::LLVM::LLVMPointerType::get(op->getContext()), nameAttr.getValue());
5785}
5786
5787mlir::LogicalResult CIRToLLVMVTableAddrPointOpLowering::matchAndRewrite(
5788 cir::VTableAddrPointOp op, OpAdaptor adaptor,
5789 mlir::ConversionPatternRewriter &rewriter) const {
5791 if (usesRelativeVTables(op->getParentOfType<mlir::ModuleOp>()))
5792 return op.emitError("NYI: address point of a relative layout vtable");
5793
5794 const mlir::TypeConverter *converter = getTypeConverter();
5795 mlir::Type targetType = converter->convertType(op.getType());
5797 mlir::Type eltType;
5798 mlir::Value symAddr =
5799 getValueForVTableSymbol(op, rewriter, symbolTables, converter,
5800 preConversionTypes, op.getNameAttr(), eltType);
5801 if (!symAddr)
5802 return mlir::failure();
5803
5805 0, op.getAddressPointAttr().getIndex(),
5806 op.getAddressPointAttr().getOffset()};
5807
5808 assert(eltType && "Shouldn't ever be missing an eltType here");
5809 mlir::LLVM::GEPNoWrapFlags inboundsNuw =
5810 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
5811 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(op, targetType, eltType,
5812 symAddr, offsets, inboundsNuw);
5813 return mlir::success();
5814}
5815
5816mlir::LogicalResult CIRToLLVMVTableGetVPtrOpLowering::matchAndRewrite(
5817 cir::VTableGetVPtrOp op, OpAdaptor adaptor,
5818 mlir::ConversionPatternRewriter &rewriter) const {
5819 // cir.vtable.get_vptr is equivalent to a bitcast from the source object
5820 // pointer to the vptr type. Since the LLVM dialect uses opaque pointers
5821 // we can just replace uses of this operation with the original pointer.
5822 mlir::Value srcVal = adaptor.getSrc();
5823 rewriter.replaceOp(op, srcVal);
5824 return mlir::success();
5825}
5826
5827/// Read the pointer that is stored in the vtable \p vptr as the 32-bit offset
5828/// of the entry at \p byteOffset, relative to the address of that entry. The
5829/// width of the integer \p byteOffset selects the form of the intrinsic.
5830static mlir::Value
5831createVTableLoadRelative(mlir::ConversionPatternRewriter &rewriter,
5832 mlir::Location loc, mlir::Value vptr,
5833 mlir::Value byteOffset) {
5834 unsigned offsetWidth =
5835 mlir::cast<mlir::IntegerType>(byteOffset.getType()).getWidth();
5837 rewriter, loc, "llvm.load.relative.i" + llvm::Twine(offsetWidth),
5838 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
5839 mlir::ValueRange{vptr, byteOffset})
5840 .getResult(0);
5841}
5842
5843mlir::LogicalResult CIRToLLVMVTableGetVirtualFnOpLowering::matchAndRewrite(
5844 cir::VTableGetVirtualFnOp op, OpAdaptor adaptor,
5845 mlir::ConversionPatternRewriter &rewriter) const {
5846 mlir::Type resultType = getTypeConverter()->convertType(op.getType());
5847 if (!resultType)
5848 return emitTypeConversionError(op, op.getType());
5849
5850 mlir::ModuleOp mod = op->getParentOfType<mlir::ModuleOp>();
5851 if (usesRelativeVTables(mod)) {
5852 // The entry is a function pointer relative to the address point.
5853 int64_t byteOffset =
5854 op.getIndex() * cir::getVTableEntrySize(mod, dataLayout);
5855 rewriter.replaceOp(op, createVTableLoadRelative(
5856 rewriter, op.getLoc(), adaptor.getVptr(),
5857 mlir::LLVM::ConstantOp::create(
5858 rewriter, op.getLoc(), rewriter.getI32Type(),
5859 rewriter.getI32IntegerAttr(byteOffset))));
5860 return mlir::success();
5861 }
5862
5863 // The entry is the function pointer itself: load it from its slot.
5864 auto ptrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5865 mlir::Value slot = mlir::LLVM::GEPOp::create(
5866 rewriter, op.getLoc(), ptrTy, ptrTy, adaptor.getVptr(),
5867 llvm::ArrayRef<mlir::LLVM::GEPArg>{static_cast<int32_t>(op.getIndex())},
5868 mlir::LLVM::GEPNoWrapFlags::inbounds);
5869 rewriter.replaceOpWithNewOp<mlir::LLVM::LoadOp>(
5870 op, resultType, slot, dataLayout.getTypeABIAlignment(ptrTy),
5871 /*isVolatile=*/false, /*isNonTemporal=*/false,
5872 /*isInvariant=*/op.getInvariant(), /*isInvariantGroup=*/false);
5873 return mlir::success();
5874}
5875
5876mlir::LogicalResult
5877CIRToLLVMVTableGetVirtualFnByOffsetOpLowering::matchAndRewrite(
5878 cir::VTableGetVirtualFnByOffsetOp op, OpAdaptor adaptor,
5879 mlir::ConversionPatternRewriter &rewriter) const {
5880 mlir::Type resultType = getTypeConverter()->convertType(op.getType());
5881 if (!resultType)
5882 return emitTypeConversionError(op, op.getType());
5883
5884 if (usesRelativeVTables(op->getParentOfType<mlir::ModuleOp>())) {
5885 // The entry is a function pointer relative to the address point.
5886 rewriter.replaceOp(op, createVTableLoadRelative(rewriter, op.getLoc(),
5887 adaptor.getVptr(),
5888 adaptor.getOffset()));
5889 return mlir::success();
5890 }
5891
5892 // The entry is the function pointer itself: load it from its slot, addressed
5893 // by its byte offset.
5894 auto ptrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5895 mlir::Value slot = mlir::LLVM::GEPOp::create(
5896 rewriter, op.getLoc(), ptrTy, rewriter.getI8Type(), adaptor.getVptr(),
5897 llvm::ArrayRef<mlir::LLVM::GEPArg>{adaptor.getOffset()});
5898 rewriter.replaceOpWithNewOp<mlir::LLVM::LoadOp>(
5899 op, resultType, slot, dataLayout.getTypeABIAlignment(ptrTy));
5900 return mlir::success();
5901}
5902
5903mlir::LogicalResult CIRToLLVMVTableGetOffsetOpLowering::matchAndRewrite(
5904 cir::VTableGetOffsetOp op, OpAdaptor adaptor,
5905 mlir::ConversionPatternRewriter &rewriter) const {
5906 mlir::Type resultType = getTypeConverter()->convertType(op.getType());
5907 if (!resultType)
5908 return emitTypeConversionError(op, op.getType());
5909
5910 // The entry is the offset itself: load it from its slot, addressed by its
5911 // byte offset.
5912 mlir::ModuleOp mod = op->getParentOfType<mlir::ModuleOp>();
5913 int64_t byteOffset = op.getIndex() * cir::getVTableEntrySize(mod, dataLayout);
5914
5915 if (usesRelativeVTables(mod)) {
5916 // The offset is stored as a plain 32-bit integer, unlike the entries that
5917 // refer to other symbols.
5918 mlir::Type entryTy =
5919 rewriter.getIntegerType(cir::getVTableEntrySize(mod, dataLayout) * 8);
5920 mlir::Value byteOffsetVal = mlir::LLVM::ConstantOp::create(
5921 rewriter, op.getLoc(), rewriter.getI64Type(),
5922 rewriter.getI64IntegerAttr(byteOffset));
5923 mlir::Value slot = mlir::LLVM::GEPOp::create(
5924 rewriter, op.getLoc(),
5925 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
5926 rewriter.getI8Type(), adaptor.getVptr(),
5927 llvm::ArrayRef<mlir::LLVM::GEPArg>{byteOffsetVal});
5928 mlir::Value offset =
5929 mlir::LLVM::LoadOp::create(rewriter, op.getLoc(), entryTy, slot,
5930 dataLayout.getTypeABIAlignment(entryTy));
5931 rewriter.replaceOpWithNewOp<mlir::LLVM::SExtOp>(op, resultType, offset);
5932 return mlir::success();
5933 }
5934
5935 auto ptrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5936 mlir::Value byteOffsetVal = mlir::LLVM::ConstantOp::create(
5937 rewriter, op.getLoc(), rewriter.getI64Type(),
5938 rewriter.getI64IntegerAttr(byteOffset));
5939 mlir::Value slot = mlir::LLVM::GEPOp::create(
5940 rewriter, op.getLoc(), ptrTy, rewriter.getI8Type(), adaptor.getVptr(),
5941 llvm::ArrayRef<mlir::LLVM::GEPArg>{byteOffsetVal});
5942 rewriter.replaceOpWithNewOp<mlir::LLVM::LoadOp>(
5943 op, resultType, slot, dataLayout.getTypeABIAlignment(ptrTy));
5944 return mlir::success();
5945}
5946
5947mlir::LogicalResult CIRToLLVMVTableGetEntryOpLowering::matchAndRewrite(
5948 cir::VTableGetEntryOp op, OpAdaptor adaptor,
5949 mlir::ConversionPatternRewriter &rewriter) const {
5950 mlir::Type resultType = getTypeConverter()->convertType(op.getType());
5951 if (!resultType)
5952 return emitTypeConversionError(op, op.getType());
5953
5954 mlir::ModuleOp mod = op->getParentOfType<mlir::ModuleOp>();
5955 if (usesRelativeVTables(mod)) {
5956 // The entry is a pointer relative to the address point.
5957 int64_t byteOffset =
5958 op.getIndex() * cir::getVTableEntrySize(mod, dataLayout);
5959 rewriter.replaceOp(op, createVTableLoadRelative(
5960 rewriter, op.getLoc(), adaptor.getVptr(),
5961 mlir::LLVM::ConstantOp::create(
5962 rewriter, op.getLoc(), rewriter.getI32Type(),
5963 rewriter.getI32IntegerAttr(byteOffset))));
5964 return mlir::success();
5965 }
5966
5967 // The entry is the pointer itself: load it from its slot.
5968 auto ptrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5969 mlir::Value index = mlir::LLVM::ConstantOp::create(
5970 rewriter, op.getLoc(), rewriter.getI64Type(),
5971 rewriter.getI64IntegerAttr(op.getIndex()));
5972 mlir::Value slot = mlir::LLVM::GEPOp::create(
5973 rewriter, op.getLoc(), ptrTy, ptrTy, adaptor.getVptr(),
5975 mlir::LLVM::GEPNoWrapFlags::inbounds);
5976 rewriter.replaceOpWithNewOp<mlir::LLVM::LoadOp>(
5977 op, resultType, slot, dataLayout.getTypeABIAlignment(ptrTy));
5978 return mlir::success();
5979}
5980
5981mlir::LogicalResult CIRToLLVMVTTAddrPointOpLowering::matchAndRewrite(
5982 cir::VTTAddrPointOp op, OpAdaptor adaptor,
5983 mlir::ConversionPatternRewriter &rewriter) const {
5984 const mlir::Type resultType = getTypeConverter()->convertType(op.getType());
5985 if (!resultType)
5986 return emitTypeConversionError(op, op.getType());
5988 mlir::Type eltType;
5989 mlir::Value llvmAddr = adaptor.getSymAddr();
5990
5991 if (op.getSymAddr()) {
5992 if (op.getOffset() == 0) {
5993 rewriter.replaceOp(op, {llvmAddr});
5994 return mlir::success();
5995 }
5996
5997 offsets.push_back(adaptor.getOffset());
5998 eltType = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
5999 } else {
6000 llvmAddr =
6001 getValueForVTableSymbol(op, rewriter, symbolTables, getTypeConverter(),
6002 preConversionTypes, op.getNameAttr(), eltType);
6003 if (!llvmAddr)
6004 return mlir::failure();
6005 assert(eltType && "Shouldn't ever be missing an eltType here");
6006 offsets.push_back(0);
6007 offsets.push_back(adaptor.getOffset());
6008 }
6009 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
6010 op, resultType, eltType, llvmAddr, offsets,
6011 mlir::LLVM::GEPNoWrapFlags::inbounds);
6012 return mlir::success();
6013}
6014
6015/// Converts \p value, the lowered form of a scalar of CIR type \p cirTy, to
6016/// the LLVM vector element type for \p cirTy. A scalar opaque float is lowered
6017/// to a one-element vector, which is bitcast to its element type.
6018static mlir::Value toVectorElement(mlir::OpBuilder &builder, mlir::Location loc,
6019 mlir::Type cirTy, mlir::Value value) {
6020 if (!cir::isAnyOpaqueFloatingPointType(cirTy))
6021 return value;
6022 auto vecTy = mlir::cast<mlir::VectorType>(value.getType());
6023 return mlir::LLVM::BitcastOp::create(builder, loc, vecTy.getElementType(),
6024 value);
6025}
6026
6027/// Converts \p element, an LLVM vector element of CIR type \p cirTy, to the
6028/// lowered form of a scalar of that type. An opaque float element is inserted
6029/// into a one-element vector.
6030static mlir::Value fromVectorElement(mlir::OpBuilder &builder,
6031 mlir::Location loc,
6032 const mlir::TypeConverter &converter,
6033 mlir::Type cirTy, mlir::Value element) {
6034 if (!cir::isAnyOpaqueFloatingPointType(cirTy))
6035 return element;
6036 mlir::Value poison =
6037 mlir::LLVM::PoisonOp::create(builder, loc, converter.convertType(cirTy));
6038 mlir::Value zero =
6039 mlir::LLVM::ConstantOp::create(builder, loc, builder.getI64Type(), 0);
6040 return mlir::LLVM::InsertElementOp::create(builder, loc, poison, element,
6041 zero);
6042}
6043
6044mlir::LogicalResult CIRToLLVMVecExtractOpLowering::matchAndRewrite(
6045 cir::VecExtractOp op, OpAdaptor adaptor,
6046 mlir::ConversionPatternRewriter &rewriter) const {
6047 const mlir::Location loc = op.getLoc();
6048 mlir::Value vec = adaptor.getVec();
6049 mlir::Type eltTy =
6050 mlir::cast<mlir::VectorType>(vec.getType()).getElementType();
6051 mlir::Value element = mlir::LLVM::ExtractElementOp::create(
6052 rewriter, loc, eltTy, vec, adaptor.getIndex());
6053 rewriter.replaceOp(op, fromVectorElement(rewriter, loc, *typeConverter,
6054 op.getType(), element));
6055 return mlir::success();
6056}
6057
6058mlir::LogicalResult CIRToLLVMVecInsertOpLowering::matchAndRewrite(
6059 cir::VecInsertOp op, OpAdaptor adaptor,
6060 mlir::ConversionPatternRewriter &rewriter) const {
6061 mlir::Value element = toVectorElement(
6062 rewriter, op.getLoc(), op.getValue().getType(), adaptor.getValue());
6063 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertElementOp>(
6064 op, adaptor.getVec(), element, adaptor.getIndex());
6065 return mlir::success();
6066}
6067
6068mlir::LogicalResult CIRToLLVMVecCreateOpLowering::matchAndRewrite(
6069 cir::VecCreateOp op, OpAdaptor adaptor,
6070 mlir::ConversionPatternRewriter &rewriter) const {
6071 // Start with an 'undef' value for the vector. Then 'insertelement' for
6072 // each of the vector elements.
6073 const cir::VectorType vecTy = op.getType();
6074 const mlir::Type llvmTy = typeConverter->convertType(vecTy);
6075 const mlir::Location loc = op.getLoc();
6076 mlir::Value result = mlir::LLVM::PoisonOp::create(rewriter, loc, llvmTy);
6077 const uint64_t vectorSize = vecTy.getFixedSize();
6078 assert(vectorSize == op.getElements().size() &&
6079 "cir.vec.create op count doesn't match vector type elements count");
6080
6081 for (uint64_t i = 0; i < vectorSize; ++i) {
6082 const mlir::Value indexValue =
6083 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), i);
6084 mlir::Value element = toVectorElement(rewriter, loc, vecTy.getElementType(),
6085 adaptor.getElements()[i]);
6086 result = mlir::LLVM::InsertElementOp::create(rewriter, loc, result, element,
6087 indexValue);
6088 }
6089
6090 rewriter.replaceOp(op, result);
6091 return mlir::success();
6092}
6093
6094mlir::LogicalResult CIRToLLVMVecCmpOpLowering::matchAndRewrite(
6095 cir::VecCmpOp op, OpAdaptor adaptor,
6096 mlir::ConversionPatternRewriter &rewriter) const {
6097 mlir::Type elementType = op.getLhs().getType().getElementType();
6098 mlir::Value bitResult;
6099 if (auto intType = mlir::dyn_cast<cir::IntType>(elementType)) {
6100 bitResult = mlir::LLVM::ICmpOp::create(
6101 rewriter, op.getLoc(),
6102 convertCmpKindToICmpPredicate(op.getKind(), intType.isSigned()),
6103 adaptor.getLhs(), adaptor.getRhs());
6104 } else if (auto boolType = mlir::dyn_cast<cir::BoolType>(elementType)) {
6105 bitResult = mlir::LLVM::ICmpOp::create(
6106 rewriter, op.getLoc(),
6107 convertCmpKindToICmpPredicate(op.getKind(), /*isSigned=*/false),
6108 adaptor.getLhs(), adaptor.getRhs());
6109 } else {
6110 return op.emitError() << "unsupported type for VecCmpOp: " << elementType;
6111 }
6112
6113 // LLVM IR vector comparison returns a vector of i1. This one-bit vector
6114 // must be sign-extended to the correct result type, unless a vector of i1 is
6115 // the type we need.
6116 mlir::Type vecElemTy = op.getType().getElementType();
6117 if (isa<cir::IntType>(vecElemTy) &&
6118 cast<cir::IntType>(vecElemTy).getWidth() > 1)
6119 rewriter.replaceOpWithNewOp<mlir::LLVM::SExtOp>(
6120 op, typeConverter->convertType(op.getType()), bitResult);
6121 else
6122 rewriter.replaceOp(op, bitResult);
6123 return mlir::success();
6124}
6125
6126mlir::LogicalResult CIRToLLVMVecFCmpOpLowering::matchAndRewrite(
6127 cir::VecFCmpOp op, OpAdaptor adaptor,
6128 mlir::ConversionPatternRewriter &rewriter) const {
6129 mlir::Type elementType = op.getLhs().getType().getElementType();
6130 if (!mlir::isa<cir::FPTypeInterface>(elementType))
6131 return op.emitError() << "unsupported type for VecFCmpOp: " << elementType;
6132
6133 mlir::Value bitResult;
6134 if (cir::FenvAttr fenv = op.getFenvAttr()) {
6135 llvm::ElementCount size = op.getLhs().getType().getSize();
6136 auto i1VecTy = mlir::VectorType::get(
6137 size.getKnownMinValue(), rewriter.getI1Type(), {size.isScalable()});
6138 mlir::LLVM::CallIntrinsicOp CFCmpCall = createConstrainedFCmpCall(
6139 rewriter, op.getLoc(), adaptor.getLhs(), adaptor.getRhs(), op.getKind(),
6140 op.getSignaling(), fenv, i1VecTy);
6141 bitResult = CFCmpCall.getResult(0);
6142 } else {
6143 bitResult = mlir::LLVM::FCmpOp::create(
6144 rewriter, op.getLoc(), convertCmpKindToFCmpPredicate(op.getKind()),
6145 adaptor.getLhs(), adaptor.getRhs());
6146 }
6147
6148 // LLVM IR vector comparison returns a vector of i1. This one-bit vector
6149 // must be sign-extended to the correct result type, unless a vector of i1 is
6150 // the type we need.
6151 mlir::Type vecElemTy = op.getType().getElementType();
6152 if (isa<cir::IntType>(vecElemTy) &&
6153 cast<cir::IntType>(vecElemTy).getWidth() > 1)
6154 rewriter.replaceOpWithNewOp<mlir::LLVM::SExtOp>(
6155 op, typeConverter->convertType(op.getType()), bitResult);
6156 else
6157 rewriter.replaceOp(op, bitResult);
6158 return mlir::success();
6159}
6160
6161mlir::LogicalResult CIRToLLVMVecSplatOpLowering::matchAndRewrite(
6162 cir::VecSplatOp op, OpAdaptor adaptor,
6163 mlir::ConversionPatternRewriter &rewriter) const {
6164 // Vector splat can be implemented with an `insertelement` and a
6165 // `shufflevector`, which is better than an `insertelement` for each
6166 // element in the vector. Start with an undef vector. Insert the value into
6167 // the first element. Then use a `shufflevector` with a mask of all 0 to
6168 // fill out the entire vector with that value.
6169 mlir::Type llvmTy = typeConverter->convertType(op.getType());
6170 mlir::Location loc = op.getLoc();
6171 mlir::Value poison = mlir::LLVM::PoisonOp::create(rewriter, loc, llvmTy);
6172
6173 mlir::Value elementValue = toVectorElement(
6174 rewriter, loc, op.getValue().getType(), adaptor.getValue());
6175 if (elementValue.getDefiningOp<mlir::LLVM::PoisonOp>()) {
6176 // If the splat value is poison, then we can just use poison value
6177 // for the entire vector.
6178 rewriter.replaceOp(op, poison);
6179 return mlir::success();
6180 }
6181
6182 if (auto constValue = elementValue.getDefiningOp<mlir::LLVM::ConstantOp>()) {
6183 if (auto intAttr = dyn_cast<mlir::IntegerAttr>(constValue.getValue())) {
6184 mlir::DenseIntElementsAttr denseVec = mlir::DenseIntElementsAttr::get(
6185 mlir::cast<mlir::ShapedType>(llvmTy), intAttr.getValue());
6186 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
6187 op, denseVec.getType(), denseVec);
6188 return mlir::success();
6189 }
6190
6191 if (auto fpAttr = dyn_cast<mlir::FloatAttr>(constValue.getValue())) {
6192 mlir::DenseFPElementsAttr denseVec = mlir::DenseFPElementsAttr::get(
6193 mlir::cast<mlir::ShapedType>(llvmTy), fpAttr.getValue());
6194 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
6195 op, denseVec.getType(), denseVec);
6196 return mlir::success();
6197 }
6198 }
6199
6200 mlir::Value indexValue =
6201 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), 0);
6202 mlir::Value oneElement = mlir::LLVM::InsertElementOp::create(
6203 rewriter, loc, poison, elementValue, indexValue);
6204 SmallVector<int32_t> zeroValues(
6205 mlir::cast<mlir::VectorType>(llvmTy).getNumElements(), 0);
6206 rewriter.replaceOpWithNewOp<mlir::LLVM::ShuffleVectorOp>(op, oneElement,
6207 poison, zeroValues);
6208 return mlir::success();
6209}
6210
6211mlir::LogicalResult CIRToLLVMVecShuffleOpLowering::matchAndRewrite(
6212 cir::VecShuffleOp op, OpAdaptor adaptor,
6213 mlir::ConversionPatternRewriter &rewriter) const {
6214 // LLVM::ShuffleVectorOp takes an ArrayRef of int for the list of indices.
6215 // Convert the ClangIR ArrayAttr of IntAttr constants into a
6216 // SmallVector<int>.
6217 SmallVector<int, 8> indices;
6218 std::transform(
6219 op.getIndices().begin(), op.getIndices().end(),
6220 std::back_inserter(indices), [](mlir::Attribute intAttr) {
6221 return mlir::cast<cir::IntAttr>(intAttr).getValue().getSExtValue();
6222 });
6223 rewriter.replaceOpWithNewOp<mlir::LLVM::ShuffleVectorOp>(
6224 op, adaptor.getVec1(), adaptor.getVec2(), indices);
6225 return mlir::success();
6226}
6227
6228mlir::LogicalResult CIRToLLVMVecShuffleDynamicOpLowering::matchAndRewrite(
6229 cir::VecShuffleDynamicOp op, OpAdaptor adaptor,
6230 mlir::ConversionPatternRewriter &rewriter) const {
6231 // LLVM IR does not have an operation that corresponds to this form of
6232 // the built-in.
6233 // __builtin_shufflevector(V, I)
6234 // is implemented as this pseudocode, where the for loop is unrolled
6235 // and N is the number of elements:
6236 //
6237 // result = undef
6238 // maskbits = NextPowerOf2(N - 1)
6239 // masked = I & maskbits
6240 // for (i in 0 <= i < N)
6241 // result[i] = V[masked[i]]
6242 mlir::Location loc = op.getLoc();
6243 mlir::Value input = adaptor.getVec();
6244 mlir::Type llvmIndexVecType =
6245 getTypeConverter()->convertType(op.getIndices().getType());
6246 mlir::Type llvmIndexType = getTypeConverter()->convertType(
6247 op.getIndices().getType().getElementType());
6248 uint64_t numElements = op.getVec().getType().getFixedSize();
6249
6250 uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
6251 mlir::Value maskValue = mlir::LLVM::ConstantOp::create(
6252 rewriter, loc, llvmIndexType,
6253 rewriter.getIntegerAttr(llvmIndexType, maskBits));
6254 mlir::Value maskVector =
6255 mlir::LLVM::UndefOp::create(rewriter, loc, llvmIndexVecType);
6256
6257 for (uint64_t i = 0; i < numElements; ++i) {
6258 mlir::Value idxValue =
6259 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), i);
6260 maskVector = mlir::LLVM::InsertElementOp::create(rewriter, loc, maskVector,
6261 maskValue, idxValue);
6262 }
6263
6264 mlir::Value maskedIndices = mlir::LLVM::AndOp::create(
6265 rewriter, loc, llvmIndexVecType, adaptor.getIndices(), maskVector);
6266 mlir::Value result = mlir::LLVM::UndefOp::create(
6267 rewriter, loc, getTypeConverter()->convertType(op.getVec().getType()));
6268 for (uint64_t i = 0; i < numElements; ++i) {
6269 mlir::Value iValue =
6270 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), i);
6271 mlir::Value indexValue = mlir::LLVM::ExtractElementOp::create(
6272 rewriter, loc, maskedIndices, iValue);
6273 mlir::Value valueAtIndex =
6274 mlir::LLVM::ExtractElementOp::create(rewriter, loc, input, indexValue);
6275 result = mlir::LLVM::InsertElementOp::create(rewriter, loc, result,
6276 valueAtIndex, iValue);
6277 }
6278 rewriter.replaceOp(op, result);
6279 return mlir::success();
6280}
6281
6282mlir::LogicalResult CIRToLLVMVecTernaryOpLowering::matchAndRewrite(
6283 cir::VecTernaryOp op, OpAdaptor adaptor,
6284 mlir::ConversionPatternRewriter &rewriter) const {
6285 mlir::Value bitVec = adaptor.getCond();
6286
6287 if (!isa<cir::BoolType>(op.getCond().getType().getElementType())) {
6288 // Convert `cond` into a vector of i1, then use that in a `select` op.
6289 bitVec = mlir::LLVM::ICmpOp::create(
6290 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::ne, adaptor.getCond(),
6291 mlir::LLVM::ZeroOp::create(
6292 rewriter, op.getCond().getLoc(),
6293 typeConverter->convertType(op.getCond().getType())));
6294 }
6295
6296 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(
6297 op, bitVec, adaptor.getLhs(), adaptor.getRhs());
6298 return mlir::success();
6299}
6300
6301/// Computes the column-major flat index (columnIdx * numRows) + rowIdx.
6302static mlir::Value
6303computeMatrixFlatIndex(mlir::ConversionPatternRewriter &rewriter,
6304 mlir::Location loc, cir::MatrixType matrixTy,
6305 mlir::Value rowIdx, mlir::Value columnIdx) {
6306 rowIdx = createIntCast(rewriter, rowIdx, rewriter.getI64Type(), false);
6307 columnIdx = createIntCast(rewriter, columnIdx, rewriter.getI64Type(), false);
6308 mlir::Type indexTy = rowIdx.getType();
6309 mlir::Value numRows = mlir::LLVM::ConstantOp::create(
6310 rewriter, loc, indexTy,
6311 rewriter.getIntegerAttr(indexTy, matrixTy.getNumRows()));
6312 mlir::Value flatIndex = mlir::LLVM::MulOp::create(
6313 rewriter, loc, {columnIdx, numRows}, /*properties=*/{},
6314 /*discardableAttributes=*/{});
6315 return mlir::LLVM::AddOp::create(rewriter, loc, flatIndex, rowIdx,
6316 /*overflowFlags=*/{});
6317}
6318
6319mlir::LogicalResult CIRToLLVMMatrixExtractOpLowering::matchAndRewrite(
6320 cir::MatrixExtractOp op, OpAdaptor adaptor,
6321 mlir::ConversionPatternRewriter &rewriter) const {
6322 mlir::Value flatIndex =
6323 computeMatrixFlatIndex(rewriter, op.getLoc(), op.getMatrix().getType(),
6324 adaptor.getRowIdx(), adaptor.getColumnIdx());
6325 rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractElementOp>(
6326 op, adaptor.getMatrix(), flatIndex);
6327 return mlir::success();
6328}
6329
6330mlir::LogicalResult CIRToLLVMMatrixExtractRowOpLowering::matchAndRewrite(
6331 cir::MatrixExtractRowOp op, OpAdaptor adaptor,
6332 mlir::ConversionPatternRewriter &rewriter) const {
6333 cir::MatrixType matrixTy = op.getMatrix().getType();
6334 mlir::Type elementType =
6335 typeConverter->convertType(matrixTy.getElementType());
6336 mlir::Type resultTy =
6337 mlir::VectorType::get(matrixTy.getNumColumns(), elementType);
6338 mlir::Value rowVec =
6339 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), resultTy);
6340
6341 for (unsigned col = 0; col != matrixTy.getNumColumns(); ++col) {
6342 mlir::Value columnIdx = mlir::LLVM::ConstantOp::create(
6343 rewriter, op.getLoc(), rewriter.getI32Type(),
6344 rewriter.getIntegerAttr(rewriter.getI32Type(), col));
6345 mlir::Value flatIndex = computeMatrixFlatIndex(
6346 rewriter, op.getLoc(), matrixTy, adaptor.getRowIdx(), columnIdx);
6347
6348 auto element = mlir::LLVM::ExtractElementOp::create(
6349 rewriter, op->getLoc(), elementType, adaptor.getMatrix(), flatIndex);
6350 rowVec = mlir::LLVM::InsertElementOp::create(rewriter, op->getLoc(), rowVec,
6351 element, columnIdx);
6352 }
6353 rewriter.replaceOp(op, rowVec);
6354 return mlir::success();
6355}
6356
6357mlir::LogicalResult CIRToLLVMMatrixInsertOpLowering::matchAndRewrite(
6358 cir::MatrixInsertOp op, OpAdaptor adaptor,
6359 mlir::ConversionPatternRewriter &rewriter) const {
6360 mlir::Value flatIndex =
6361 computeMatrixFlatIndex(rewriter, op.getLoc(), op.getMatrix().getType(),
6362 adaptor.getRowIdx(), adaptor.getColumnIdx());
6363 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertElementOp>(
6364 op, adaptor.getMatrix(), adaptor.getValue(), flatIndex);
6365 return mlir::success();
6366}
6367
6368mlir::LogicalResult CIRToLLVMMatrixColumnMajorLoadOpLowering::matchAndRewrite(
6369 cir::MatrixColumnMajorLoadOp op, OpAdaptor adaptor,
6370 mlir::ConversionPatternRewriter &rewriter) const {
6371 cir::MatrixType resultMatrixTy = op.getResult().getType();
6372 mlir::Type resultTy = typeConverter->convertType(resultMatrixTy);
6373 rewriter.replaceOpWithNewOp<mlir::LLVM::MatrixColumnMajorLoadOp>(
6374 op, resultTy, adaptor.getValue(), adaptor.getStride(),
6375 rewriter.getBoolAttr(op.getIsVolatile()),
6376 rewriter.getI32IntegerAttr(resultMatrixTy.getNumRows()),
6377 rewriter.getI32IntegerAttr(resultMatrixTy.getNumColumns()));
6378 return mlir::success();
6379}
6380
6381mlir::LogicalResult CIRToLLVMMatrixColumnMajorStoreOpLowering::matchAndRewrite(
6382 cir::MatrixColumnMajorStoreOp op, OpAdaptor adaptor,
6383 mlir::ConversionPatternRewriter &rewriter) const {
6384 cir::MatrixType matrixTy = op.getMatrix().getType();
6385 rewriter.replaceOpWithNewOp<mlir::LLVM::MatrixColumnMajorStoreOp>(
6386 op, adaptor.getMatrix(), adaptor.getValue(), adaptor.getStride(),
6387 rewriter.getBoolAttr(op.getIsVolatile()),
6388 rewriter.getI32IntegerAttr(matrixTy.getNumRows()),
6389 rewriter.getI32IntegerAttr(matrixTy.getNumColumns()));
6390 return mlir::success();
6391}
6392
6393mlir::LogicalResult CIRToLLVMMatrixMultiplyOpLowering::matchAndRewrite(
6394 cir::MatrixMultiplyOp op, OpAdaptor adaptor,
6395 mlir::ConversionPatternRewriter &rewriter) const {
6396 cir::MatrixType lhsTy = op.getLhs().getType();
6397 cir::MatrixType rhsTy = op.getRhs().getType();
6398 mlir::Type resultTy = typeConverter->convertType(op.getResult().getType());
6399 rewriter.replaceOpWithNewOp<mlir::LLVM::MatrixMultiplyOp>(
6400 op, resultTy, adaptor.getLhs(), adaptor.getRhs(), lhsTy.getNumRows(),
6401 lhsTy.getNumColumns(), rhsTy.getNumColumns());
6402 return mlir::success();
6403}
6404
6405mlir::LogicalResult CIRToLLVMMatrixTransposeOpLowering::matchAndRewrite(
6406 cir::MatrixTransposeOp op, OpAdaptor adaptor,
6407 mlir::ConversionPatternRewriter &rewriter) const {
6408 cir::MatrixType resultMatrixTy = op.getValue().getType();
6409 mlir::Type resultTy = typeConverter->convertType(resultMatrixTy);
6410 rewriter.replaceOpWithNewOp<mlir::LLVM::MatrixTransposeOp>(
6411 op, resultTy, adaptor.getValue(), resultMatrixTy.getNumRows(),
6412 resultMatrixTy.getNumColumns());
6413 return mlir::success();
6414}
6415
6416mlir::LogicalResult CIRToLLVMComplexCreateOpLowering::matchAndRewrite(
6417 cir::ComplexCreateOp op, OpAdaptor adaptor,
6418 mlir::ConversionPatternRewriter &rewriter) const {
6419 mlir::Type complexLLVMTy =
6420 getTypeConverter()->convertType(op.getResult().getType());
6421 auto initialComplex =
6422 mlir::LLVM::UndefOp::create(rewriter, op->getLoc(), complexLLVMTy);
6423
6424 auto realComplex = mlir::LLVM::InsertValueOp::create(
6425 rewriter, op->getLoc(), initialComplex, adaptor.getReal(),
6426 ArrayRef(int64_t{0}));
6427
6428 auto complex = mlir::LLVM::InsertValueOp::create(
6429 rewriter, op->getLoc(), realComplex, adaptor.getImag(),
6430 ArrayRef(int64_t{1}));
6431
6432 rewriter.replaceOp(op, complex);
6433 return mlir::success();
6434}
6435
6436mlir::LogicalResult CIRToLLVMComplexRealOpLowering::matchAndRewrite(
6437 cir::ComplexRealOp op, OpAdaptor adaptor,
6438 mlir::ConversionPatternRewriter &rewriter) const {
6439 mlir::Value operand = adaptor.getOperand();
6440 if (mlir::isa<cir::ComplexType>(op.getOperand().getType())) {
6441 operand = rewriter.createOrFold<mlir::LLVM::ExtractValueOp>(
6442 op.getLoc(), operand, llvm::ArrayRef<std::int64_t>{0});
6443 }
6444 rewriter.replaceOp(op, operand);
6445 return mlir::success();
6446}
6447
6448mlir::LogicalResult CIRToLLVMComplexImagOpLowering::matchAndRewrite(
6449 cir::ComplexImagOp op, OpAdaptor adaptor,
6450 mlir::ConversionPatternRewriter &rewriter) const {
6451 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
6452 mlir::Value operand = adaptor.getOperand();
6453 mlir::Location loc = op.getLoc();
6454
6455 if (mlir::isa<cir::ComplexType>(op.getOperand().getType())) {
6456 operand = rewriter.createOrFold<mlir::LLVM::ExtractValueOp>(
6457 loc, operand, llvm::ArrayRef<std::int64_t>{1});
6458 } else {
6459 mlir::TypedAttr zeroAttr = rewriter.getZeroAttr(resultLLVMTy);
6460 operand =
6461 mlir::LLVM::ConstantOp::create(rewriter, loc, resultLLVMTy, zeroAttr);
6462 }
6463
6464 rewriter.replaceOp(op, operand);
6465 return mlir::success();
6466}
6467
6468mlir::LogicalResult CIRToLLVMComplexAddOpLowering::matchAndRewrite(
6469 cir::ComplexAddOp op, OpAdaptor adaptor,
6470 mlir::ConversionPatternRewriter &rewriter) const {
6471 mlir::Value lhs = adaptor.getLhs();
6472 mlir::Value rhs = adaptor.getRhs();
6473 mlir::Location loc = op.getLoc();
6474
6475 auto complexType = mlir::cast<cir::ComplexType>(op.getLhs().getType());
6476 mlir::Type complexElemTy =
6477 getTypeConverter()->convertType(complexType.getElementType());
6478 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
6479 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
6480 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
6481 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
6482 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
6483 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
6484 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
6485 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
6486
6487 mlir::Value newReal;
6488 mlir::Value newImag;
6489 if (complexElemTy.isInteger()) {
6490 newReal = mlir::LLVM::AddOp::create(rewriter, loc, complexElemTy, lhsReal,
6491 rhsReal);
6492 newImag = mlir::LLVM::AddOp::create(rewriter, loc, complexElemTy, lhsImag,
6493 rhsImag);
6494 } else {
6497 newReal = mlir::LLVM::FAddOp::create(rewriter, loc, complexElemTy, lhsReal,
6498 rhsReal);
6499 newImag = mlir::LLVM::FAddOp::create(rewriter, loc, complexElemTy, lhsImag,
6500 rhsImag);
6501 }
6502
6503 mlir::Type complexLLVMTy =
6504 getTypeConverter()->convertType(op.getResult().getType());
6505 auto initialComplex =
6506 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), complexLLVMTy);
6507
6508 auto realComplex = mlir::LLVM::InsertValueOp::create(
6509 rewriter, op->getLoc(), initialComplex, newReal, ArrayRef(int64_t{0}));
6510
6511 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
6512 op, realComplex, newImag, ArrayRef(int64_t{1}));
6513
6514 return mlir::success();
6515}
6516
6517mlir::LogicalResult CIRToLLVMComplexSubOpLowering::matchAndRewrite(
6518 cir::ComplexSubOp op, OpAdaptor adaptor,
6519 mlir::ConversionPatternRewriter &rewriter) const {
6520 mlir::Value lhs = adaptor.getLhs();
6521 mlir::Value rhs = adaptor.getRhs();
6522 mlir::Location loc = op.getLoc();
6523
6524 auto complexType = mlir::cast<cir::ComplexType>(op.getLhs().getType());
6525 mlir::Type complexElemTy =
6526 getTypeConverter()->convertType(complexType.getElementType());
6527 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
6528 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
6529 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
6530 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
6531 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
6532 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
6533 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
6534 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
6535
6536 mlir::Value newReal;
6537 mlir::Value newImag;
6538 if (complexElemTy.isInteger()) {
6539 newReal = mlir::LLVM::SubOp::create(rewriter, loc, complexElemTy, lhsReal,
6540 rhsReal);
6541 newImag = mlir::LLVM::SubOp::create(rewriter, loc, complexElemTy, lhsImag,
6542 rhsImag);
6543 } else {
6546 newReal = mlir::LLVM::FSubOp::create(rewriter, loc, complexElemTy, lhsReal,
6547 rhsReal);
6548 newImag = mlir::LLVM::FSubOp::create(rewriter, loc, complexElemTy, lhsImag,
6549 rhsImag);
6550 }
6551
6552 mlir::Type complexLLVMTy =
6553 getTypeConverter()->convertType(op.getResult().getType());
6554 auto initialComplex =
6555 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), complexLLVMTy);
6556
6557 auto realComplex = mlir::LLVM::InsertValueOp::create(
6558 rewriter, op->getLoc(), initialComplex, newReal, ArrayRef(int64_t{0}));
6559
6560 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
6561 op, realComplex, newImag, ArrayRef(int64_t{1}));
6562
6563 return mlir::success();
6564}
6565
6566mlir::LogicalResult CIRToLLVMComplexFAddOpLowering::matchAndRewrite(
6567 cir::ComplexFAddOp op, OpAdaptor adaptor,
6568 mlir::ConversionPatternRewriter &rewriter) const {
6569 mlir::Value lhs = adaptor.getLhs();
6570 mlir::Value rhs = adaptor.getRhs();
6571 mlir::Location loc = op.getLoc();
6572
6573 auto complexType = mlir::cast<cir::ComplexType>(op.getLhs().getType());
6574 mlir::Type complexElemTy =
6575 getTypeConverter()->convertType(complexType.getElementType());
6576 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
6577 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
6578 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
6579 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
6580 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
6581 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
6582 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
6583 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
6584
6586 mlir::Value newReal;
6587 mlir::Value newImag;
6588 if (cir::FenvAttr fenv = op.getFenvAttr()) {
6590 rewriter, loc, {lhsReal, rhsReal}, complexElemTy, fenv,
6591 /*constrainedMnemonic=*/"fadd",
6592 /*hasRoundingMode=*/true);
6593
6595 rewriter, loc, {lhsImag, rhsImag}, complexElemTy, fenv,
6596 /*constrainedMnemonic=*/"fadd",
6597 /*hasRoundingMode=*/true);
6598 } else {
6599 newReal = mlir::LLVM::FAddOp::create(rewriter, loc, complexElemTy, lhsReal,
6600 rhsReal);
6601 newImag = mlir::LLVM::FAddOp::create(rewriter, loc, complexElemTy, lhsImag,
6602 rhsImag);
6603 }
6604
6605 mlir::Type complexLLVMTy =
6606 getTypeConverter()->convertType(op.getResult().getType());
6607 auto initialComplex =
6608 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), complexLLVMTy);
6609
6610 auto realComplex = mlir::LLVM::InsertValueOp::create(
6611 rewriter, op->getLoc(), initialComplex, newReal, ArrayRef(int64_t{0}));
6612
6613 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
6614 op, realComplex, newImag, ArrayRef(int64_t{1}));
6615
6616 return mlir::success();
6617}
6618
6619mlir::LogicalResult CIRToLLVMComplexFSubOpLowering::matchAndRewrite(
6620 cir::ComplexFSubOp op, OpAdaptor adaptor,
6621 mlir::ConversionPatternRewriter &rewriter) const {
6622 mlir::Value lhs = adaptor.getLhs();
6623 mlir::Value rhs = adaptor.getRhs();
6624 mlir::Location loc = op.getLoc();
6625
6626 auto complexType = mlir::cast<cir::ComplexType>(op.getLhs().getType());
6627 mlir::Type complexElemTy =
6628 getTypeConverter()->convertType(complexType.getElementType());
6629 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
6630 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
6631 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
6632 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
6633 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
6634 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
6635 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
6636 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
6637
6639 mlir::Value newReal;
6640 mlir::Value newImag;
6641 if (cir::FenvAttr fenv = op.getFenvAttr()) {
6643 rewriter, loc, {lhsReal, rhsReal}, complexElemTy, fenv,
6644 /*constrainedMnemonic=*/"fsub",
6645 /*hasRoundingMode=*/true);
6646
6648 rewriter, loc, {lhsImag, rhsImag}, complexElemTy, fenv,
6649 /*constrainedMnemonic=*/"fsub",
6650 /*hasRoundingMode=*/true);
6651 } else {
6652 newReal = mlir::LLVM::FSubOp::create(rewriter, loc, complexElemTy, lhsReal,
6653 rhsReal);
6654 newImag = mlir::LLVM::FSubOp::create(rewriter, loc, complexElemTy, lhsImag,
6655 rhsImag);
6656 }
6657
6658 mlir::Type complexLLVMTy =
6659 getTypeConverter()->convertType(op.getResult().getType());
6660 auto initialComplex =
6661 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), complexLLVMTy);
6662
6663 auto realComplex = mlir::LLVM::InsertValueOp::create(
6664 rewriter, op->getLoc(), initialComplex, newReal, ArrayRef(int64_t{0}));
6665
6666 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
6667 op, realComplex, newImag, ArrayRef(int64_t{1}));
6668
6669 return mlir::success();
6670}
6671
6672mlir::IntegerType computeBitfieldIntType(mlir::Type storageType,
6673 mlir::MLIRContext *context,
6674 unsigned &storageSize) {
6675 return TypeSwitch<mlir::Type, mlir::IntegerType>(storageType)
6676 .Case<cir::ArrayType>([&](cir::ArrayType atTy) {
6677 storageSize = atTy.getSize() * 8;
6678 return mlir::IntegerType::get(context, storageSize);
6679 })
6680 .Case<cir::IntType>([&](cir::IntType intTy) {
6681 storageSize = intTy.getWidth();
6682 return mlir::IntegerType::get(context, storageSize);
6683 })
6684 .Default([](mlir::Type) -> mlir::IntegerType {
6685 llvm_unreachable(
6686 "Either ArrayType or IntType expected for bitfields storage");
6687 });
6688}
6689
6690mlir::LogicalResult CIRToLLVMSetBitfieldOpLowering::matchAndRewrite(
6691 cir::SetBitfieldOp op, OpAdaptor adaptor,
6692 mlir::ConversionPatternRewriter &rewriter) const {
6693 mlir::OpBuilder::InsertionGuard guard(rewriter);
6694 rewriter.setInsertionPoint(op);
6695
6696 cir::BitfieldInfoAttr info = op.getBitfieldInfo();
6697 uint64_t size = info.getSize();
6698 uint64_t offset = info.getOffset();
6699 mlir::Type storageType = info.getStorageType();
6700 mlir::MLIRContext *context = storageType.getContext();
6701
6702 unsigned storageSize = 0;
6703
6704 mlir::IntegerType intType =
6705 computeBitfieldIntType(storageType, context, storageSize);
6706
6707 mlir::Value srcVal = createIntCast(rewriter, adaptor.getSrc(), intType);
6708 unsigned srcWidth = storageSize;
6709 mlir::Value resultVal = srcVal;
6710
6711 if (storageSize != size) {
6712 assert(storageSize > size && "Invalid bitfield size.");
6713
6714 mlir::Value val = mlir::LLVM::LoadOp::create(
6715 rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignment(),
6716 op.getIsVolatile());
6717
6718 srcVal =
6719 createAnd(rewriter, srcVal, llvm::APInt::getLowBitsSet(srcWidth, size));
6720 resultVal = srcVal;
6721 srcVal = createShL(rewriter, srcVal, offset);
6722
6723 // Mask out the original value.
6724 val = createAnd(rewriter, val,
6725 ~llvm::APInt::getBitsSet(srcWidth, offset, offset + size));
6726
6727 // Or together the unchanged values and the source value.
6728 srcVal = mlir::LLVM::OrOp::create(rewriter, op.getLoc(), val, srcVal);
6729 }
6730
6731 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), srcVal, adaptor.getAddr(),
6732 op.getAlignment(), op.getIsVolatile());
6733
6734 mlir::Type resultTy = getTypeConverter()->convertType(op.getType());
6735
6736 if (info.getIsSigned()) {
6737 assert(size <= storageSize);
6738 unsigned highBits = storageSize - size;
6739
6740 if (highBits) {
6741 resultVal = createShL(rewriter, resultVal, highBits);
6742 resultVal = createAShR(rewriter, resultVal, highBits);
6743 }
6744 }
6745
6746 resultVal = createIntCast(rewriter, resultVal,
6747 mlir::cast<mlir::IntegerType>(resultTy),
6748 info.getIsSigned());
6749
6750 rewriter.replaceOp(op, resultVal);
6751 return mlir::success();
6752}
6753
6754mlir::LogicalResult CIRToLLVMComplexImagPtrOpLowering::matchAndRewrite(
6755 cir::ComplexImagPtrOp op, OpAdaptor adaptor,
6756 mlir::ConversionPatternRewriter &rewriter) const {
6757 cir::PointerType operandTy = op.getOperand().getType();
6758 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
6759 if (!resultLLVMTy)
6760 return emitTypeConversionError(op, op.getType());
6761 mlir::Type elementLLVMTy =
6762 getTypeConverter()->convertType(operandTy.getPointee());
6763
6764 mlir::LLVM::GEPArg gepIndices[2] = {{0}, {1}};
6765 mlir::LLVM::GEPNoWrapFlags inboundsNuw =
6766 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
6767 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
6768 op, resultLLVMTy, elementLLVMTy, adaptor.getOperand(), gepIndices,
6769 inboundsNuw);
6770 return mlir::success();
6771}
6772
6773mlir::LogicalResult CIRToLLVMComplexRealPtrOpLowering::matchAndRewrite(
6774 cir::ComplexRealPtrOp op, OpAdaptor adaptor,
6775 mlir::ConversionPatternRewriter &rewriter) const {
6776 cir::PointerType operandTy = op.getOperand().getType();
6777 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
6778 if (!resultLLVMTy)
6779 return emitTypeConversionError(op, op.getType());
6780 mlir::Type elementLLVMTy =
6781 getTypeConverter()->convertType(operandTy.getPointee());
6782
6783 mlir::LLVM::GEPArg gepIndices[2] = {0, 0};
6784 mlir::LLVM::GEPNoWrapFlags inboundsNuw =
6785 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
6786 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
6787 op, resultLLVMTy, elementLLVMTy, adaptor.getOperand(), gepIndices,
6788 inboundsNuw);
6789 return mlir::success();
6790}
6791
6792mlir::LogicalResult CIRToLLVMGetBitfieldOpLowering::matchAndRewrite(
6793 cir::GetBitfieldOp op, OpAdaptor adaptor,
6794 mlir::ConversionPatternRewriter &rewriter) const {
6795
6796 mlir::OpBuilder::InsertionGuard guard(rewriter);
6797 rewriter.setInsertionPoint(op);
6798
6799 cir::BitfieldInfoAttr info = op.getBitfieldInfo();
6800 uint64_t size = info.getSize();
6801 uint64_t offset = info.getOffset();
6802 mlir::Type storageType = info.getStorageType();
6803 mlir::MLIRContext *context = storageType.getContext();
6804 unsigned storageSize = 0;
6805
6806 mlir::IntegerType intType =
6807 computeBitfieldIntType(storageType, context, storageSize);
6808
6809 mlir::Value val = mlir::LLVM::LoadOp::create(
6810 rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignment(),
6811 op.getIsVolatile());
6812 val = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), intType, val);
6813
6814 if (info.getIsSigned()) {
6815 assert(static_cast<unsigned>(offset + size) <= storageSize);
6816 unsigned highBits = storageSize - offset - size;
6817 val = createShL(rewriter, val, highBits);
6818 val = createAShR(rewriter, val, offset + highBits);
6819 } else {
6820 val = createLShR(rewriter, val, offset);
6821
6822 if (static_cast<unsigned>(offset) + size < storageSize)
6823 val = createAnd(rewriter, val,
6824 llvm::APInt::getLowBitsSet(storageSize, size));
6825 }
6826
6827 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
6828 mlir::Value newOp = createIntCast(
6829 rewriter, val, mlir::cast<mlir::IntegerType>(resTy), info.getIsSigned());
6830 rewriter.replaceOp(op, newOp);
6831 return mlir::success();
6832}
6833
6834mlir::LogicalResult CIRToLLVMInlineAsmOpLowering::matchAndRewrite(
6835 cir::InlineAsmOp op, OpAdaptor adaptor,
6836 mlir::ConversionPatternRewriter &rewriter) const {
6837 mlir::Type llResTy;
6838 if (op.getNumResults()) {
6839 llResTy = getTypeConverter()->convertType(op.getType(0));
6840 if (!llResTy)
6841 return emitTypeConversionError(op, op.getType(0));
6842 }
6843
6844 cir::AsmFlavor dialect = op.getAsmFlavor();
6845 mlir::LLVM::AsmDialect llDialect = dialect == cir::AsmFlavor::x86_att
6846 ? mlir::LLVM::AsmDialect::AD_ATT
6847 : mlir::LLVM::AsmDialect::AD_Intel;
6848
6850 StringRef llvmAttrName = mlir::LLVM::InlineAsmOp::getElementTypeAttrName();
6851
6852 // this is for the lowering to LLVM from LLVM dialect. Otherwise, if we
6853 // don't have the result (i.e. void type as a result of operation), the
6854 // element type attribute will be attached to the whole instruction, but not
6855 // to the operand
6856 if (!op.getNumResults())
6857 opAttrs.push_back(mlir::Attribute());
6858
6859 // so far we infer the llvm dialect element type attr from
6860 // CIR operand type.
6861 for (auto [index, cirOp] : llvm::enumerate(op->getOperands())) {
6862 if (!op.isMemoryOperand(index)) {
6863 opAttrs.push_back(mlir::Attribute());
6864 continue;
6865 }
6866
6868 cir::PointerType typ = mlir::cast<cir::PointerType>(cirOp.getType());
6869 mlir::Type elementTy =
6870 convertTypeForMemory(*getTypeConverter(), dataLayout, typ.getPointee());
6871 if (!elementTy)
6872 return emitTypeConversionError(op, typ.getPointee());
6873 mlir::TypeAttr typAttr = mlir::TypeAttr::get(elementTy);
6874
6875 attrs.push_back(rewriter.getNamedAttr(llvmAttrName, typAttr));
6876 mlir::DictionaryAttr newDict = rewriter.getDictionaryAttr(attrs);
6877 opAttrs.push_back(newDict);
6878 }
6879
6880 rewriter.replaceOpWithNewOp<mlir::LLVM::InlineAsmOp>(
6881 op, llResTy, adaptor.getOperands(), op.getAsmStringAttr(),
6882 op.getConstraintsAttr(), op.getSideEffectsAttr(),
6883 /*is_align_stack*/ mlir::UnitAttr(),
6884 /*tail_call_kind*/
6885 mlir::LLVM::TailCallKindAttr::get(
6886 getContext(), mlir::LLVM::tailcallkind::TailCallKind::None),
6887 op.getConvergentAttr(),
6888 mlir::LLVM::AsmDialectAttr::get(getContext(), llDialect),
6889 rewriter.getArrayAttr(opAttrs));
6890
6891 return mlir::success();
6892}
6893
6894mlir::LogicalResult CIRToLLVMVAStartOpLowering::matchAndRewrite(
6895 cir::VAStartOp op, OpAdaptor adaptor,
6896 mlir::ConversionPatternRewriter &rewriter) const {
6897 rewriter.replaceOpWithNewOp<mlir::LLVM::VaStartOp>(op, adaptor.getArgList());
6898 return mlir::success();
6899}
6900
6901mlir::LogicalResult CIRToLLVMVAEndOpLowering::matchAndRewrite(
6902 cir::VAEndOp op, OpAdaptor adaptor,
6903 mlir::ConversionPatternRewriter &rewriter) const {
6904 rewriter.replaceOpWithNewOp<mlir::LLVM::VaEndOp>(op, adaptor.getArgList());
6905 return mlir::success();
6906}
6907
6908mlir::LogicalResult CIRToLLVMVACopyOpLowering::matchAndRewrite(
6909 cir::VACopyOp op, OpAdaptor adaptor,
6910 mlir::ConversionPatternRewriter &rewriter) const {
6911 rewriter.replaceOpWithNewOp<mlir::LLVM::VaCopyOp>(op, adaptor.getDstList(),
6912 adaptor.getSrcList());
6913 return mlir::success();
6914}
6915
6916mlir::LogicalResult CIRToLLVMVAArgOpLowering::matchAndRewrite(
6917 cir::VAArgOp op, OpAdaptor adaptor,
6918 mlir::ConversionPatternRewriter &rewriter) const {
6920 mlir::Type llvmType =
6921 getTypeConverter()->convertType(op->getResultTypes().front());
6922 if (!llvmType)
6923 return mlir::failure();
6924
6925 rewriter.replaceOpWithNewOp<mlir::LLVM::VaArgOp>(op, llvmType,
6926 adaptor.getArgList());
6927 return mlir::success();
6928}
6929
6930mlir::LogicalResult CIRToLLVMLabelOpLowering::matchAndRewrite(
6931 cir::LabelOp op, OpAdaptor adaptor,
6932 mlir::ConversionPatternRewriter &rewriter) const {
6933 mlir::MLIRContext *ctx = rewriter.getContext();
6934 mlir::Block *block = op->getBlock();
6935 // A BlockTagOp cannot reside in the entry block. The address of the entry
6936 // block cannot be taken
6937 if (block->isEntryBlock()) {
6938 mlir::Block *newBlock =
6939 rewriter.splitBlock(op->getBlock(), mlir::Block::iterator(op));
6940 rewriter.setInsertionPointToEnd(block);
6941 mlir::LLVM::BrOp::create(rewriter, op.getLoc(), newBlock);
6942 }
6943 auto tagAttr =
6944 mlir::LLVM::BlockTagAttr::get(ctx, blockInfoAddr.getTagIndex());
6945 rewriter.setInsertionPoint(op);
6946
6947 auto blockTagOp =
6948 mlir::LLVM::BlockTagOp::create(rewriter, op->getLoc(), tagAttr);
6949 mlir::LLVM::LLVMFuncOp func = op->getParentOfType<mlir::LLVM::LLVMFuncOp>();
6950 auto blockInfoAttr =
6951 cir::BlockAddrInfoAttr::get(ctx, func.getSymName(), op.getLabel());
6952 blockInfoAddr.mapBlockTag(blockInfoAttr, blockTagOp);
6953 rewriter.eraseOp(op);
6954
6955 return mlir::success();
6956}
6957
6958mlir::LogicalResult CIRToLLVMBlockAddressOpLowering::matchAndRewrite(
6959 cir::BlockAddressOp op, OpAdaptor adaptor,
6960 mlir::ConversionPatternRewriter &rewriter) const {
6961 mlir::MLIRContext *ctx = rewriter.getContext();
6962
6963 mlir::LLVM::BlockTagOp matchLabel =
6964 blockInfoAddr.lookupBlockTag(op.getBlockAddrInfoAttr());
6965 mlir::LLVM::BlockTagAttr tagAttr;
6966 if (!matchLabel)
6967 // If the BlockTagOp has not been emitted yet, use a placeholder.
6968 // This will later be replaced with the correct tag index during
6969 // `resolveBlockAddressOp`.
6970 tagAttr = {};
6971 else
6972 tagAttr = matchLabel.getTag();
6973
6974 auto blkAddr = mlir::LLVM::BlockAddressAttr::get(
6975 rewriter.getContext(), op.getBlockAddrInfoAttr().getFunc(), tagAttr);
6976 rewriter.setInsertionPoint(op);
6977 auto newOp = mlir::LLVM::BlockAddressOp::create(
6978 rewriter, op.getLoc(), mlir::LLVM::LLVMPointerType::get(ctx), blkAddr);
6979 if (!matchLabel)
6980 blockInfoAddr.addUnresolvedBlockAddress(newOp, op.getBlockAddrInfoAttr());
6981 rewriter.replaceOp(op, newOp);
6982 return mlir::success();
6983}
6984
6985mlir::LogicalResult CIRToLLVMIndirectBrOpLowering::matchAndRewrite(
6986 cir::IndirectBrOp op, OpAdaptor adaptor,
6987 mlir::ConversionPatternRewriter &rewriter) const {
6988
6989 mlir::Value targetAddr = adaptor.getAddr();
6990
6991 // If the poison attribute is set, use llvm.mlir.poison as the address.
6992 // This happens when the block has no predecessors and is essentially
6993 // unreachable. Do NOT erase the block argument directly, as that violates
6994 // the MLIR dialect conversion framework contract (the framework tracks block
6995 // arguments and will clean them up). A block with no predecessors simply
6996 // produces no PHI node.
6997 if (op.getPoison()) {
6998 auto llvmPtrType = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
6999 targetAddr =
7000 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), llvmPtrType);
7001 }
7002
7003 rewriter.replaceOpWithNewOp<mlir::LLVM::IndirectBrOp>(
7004 op, targetAddr, adaptor.getSuccOperands(), op.getSuccessors());
7005 return mlir::success();
7006}
7007
7008mlir::LogicalResult CIRToLLVMTokenNoneOpLowering::matchAndRewrite(
7009 cir::TokenNoneOp op, OpAdaptor adaptor,
7010 mlir::ConversionPatternRewriter &rewriter) const {
7011 rewriter.replaceOpWithNewOp<mlir::LLVM::NoneTokenOp>(
7012 op, mlir::TokenType::get(rewriter.getContext()));
7013 return mlir::success();
7014}
7015
7016mlir::LogicalResult CIRToLLVMCpuIdOpLowering::matchAndRewrite(
7017 cir::CpuIdOp op, OpAdaptor adaptor,
7018 mlir::ConversionPatternRewriter &rewriter) const {
7019 mlir::ModuleOp moduleOp = op->getParentOfType<mlir::ModuleOp>();
7020 std::optional<llvm::Triple> triple = cir::getTripleFromModule(moduleOp);
7021 if (!triple)
7022 return op.emitOpError()
7023 << "requires a '" << cir::CIRDialect::getTripleAttrName()
7024 << "' module attribute";
7025
7026 mlir::Type i32Ty = rewriter.getI32Type();
7027 mlir::Type i64Ty = rewriter.getI64Type();
7028 mlir::Type i32PtrTy = mlir::LLVM::LLVMPointerType::get(i32Ty.getContext(), 0);
7029
7030 mlir::Type cpuidRetTy = mlir::LLVM::LLVMStructType::getLiteral(
7031 rewriter.getContext(), {i32Ty, i32Ty, i32Ty, i32Ty});
7032
7033 mlir::Value functionId = adaptor.getFunctionId();
7034 mlir::Value subFunctionId = adaptor.getSubFunctionId();
7035
7036 StringRef asmString, constraints;
7037 if (triple->getArch() == llvm::Triple::x86) {
7038 asmString = "cpuid";
7039 constraints = "={ax},={bx},={cx},={dx},{ax},{cx}";
7040 } else {
7041 // x86-64 uses %rbx as the base register, so preserve it.
7042 asmString = "xchgq %rbx, ${1:q}\n"
7043 "cpuid\n"
7044 "xchgq %rbx, ${1:q}";
7045 constraints = "={ax},=r,={cx},={dx},0,2";
7046 }
7047
7048 mlir::Value inlineAsm =
7049 mlir::LLVM::InlineAsmOp::create(
7050 rewriter, op.getLoc(), cpuidRetTy, {functionId, subFunctionId},
7051 rewriter.getStringAttr(asmString),
7052 rewriter.getStringAttr(constraints),
7053 /*has_side_effects=*/mlir::UnitAttr{},
7054 /*is_align_stack=*/mlir::UnitAttr{},
7055 /*tail_call_kind=*/mlir::LLVM::TailCallKindAttr{},
7056 /*convergent=*/{},
7057 /*asm_dialect=*/mlir::LLVM::AsmDialectAttr{},
7058 /*operand_attrs=*/mlir::ArrayAttr{})
7059 .getResult(0);
7060
7061 mlir::Value basePtr = adaptor.getCpuInfo();
7062
7063 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
7064 unsigned alignment = layout.getTypeABIAlignment(i32Ty);
7065 for (unsigned i = 0; i < 4; i++) {
7066 mlir::Value extracted =
7067 mlir::LLVM::ExtractValueOp::create(rewriter, op.getLoc(), inlineAsm, i)
7068 .getResult();
7069 mlir::Value index = mlir::LLVM::ConstantOp::create(
7070 rewriter, op.getLoc(), i64Ty, rewriter.getI64IntegerAttr(i));
7071 llvm::SmallVector<mlir::Value, 1> gepIndices = {index};
7072 mlir::Value storePtr = mlir::LLVM::GEPOp::create(
7073 rewriter, op.getLoc(), i32PtrTy, i32Ty, basePtr,
7074 gepIndices, mlir::LLVM::GEPNoWrapFlags::none)
7075 .getResult();
7076 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), extracted, storePtr,
7077 alignment);
7078 }
7079
7080 rewriter.eraseOp(op);
7081 return mlir::success();
7082}
7083
7084mlir::LogicalResult CIRToLLVMMemChrOpLowering::matchAndRewrite(
7085 cir::MemChrOp op, OpAdaptor adaptor,
7086 mlir::ConversionPatternRewriter &rewriter) const {
7087 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
7088 mlir::Type srcTy = getTypeConverter()->convertType(op.getSrc().getType());
7089 mlir::Type patternTy =
7090 getTypeConverter()->convertType(op.getPattern().getType());
7091 mlir::Type lenTy = getTypeConverter()->convertType(op.getLen().getType());
7092 auto fnTy =
7093 mlir::LLVM::LLVMFunctionType::get(llvmPtrTy, {srcTy, patternTy, lenTy},
7094 /*isVarArg=*/false);
7095 llvm::StringRef fnName = "memchr";
7096
7097 mlir::Builder b(rewriter.getContext());
7098 mlir::NamedAttribute noundefAttr =
7099 b.getNamedAttr("llvm.noundef", b.getUnitAttr());
7100 mlir::DictionaryAttr noundefDict = mlir::DictionaryAttr::get(
7101 rewriter.getContext(), llvm::ArrayRef(noundefAttr));
7102 SmallVector<mlir::Attribute> argAttrVec(3, noundefDict);
7103 mlir::ArrayAttr argAttrs =
7104 mlir::ArrayAttr::get(rewriter.getContext(), argAttrVec);
7105
7106 createLLVMFuncOpIfNotExist(rewriter, symbolTables, op, fnName, fnTy,
7107 argAttrs);
7108
7109 mlir::LLVM::CallOp newCall = rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
7110 op, mlir::TypeRange{llvmPtrTy}, fnName,
7111 mlir::ValueRange{adaptor.getSrc(), adaptor.getPattern(),
7112 adaptor.getLen()});
7113 newCall.setArgAttrsAttr(argAttrs);
7114 return mlir::success();
7115}
7116
7117// Function to do the clear-padding operation. This is a faithful translation of
7118// CGBuiltin.cpp's ClearPadding function.
7119static void clearPadding(mlir::ConversionPatternRewriter &rewriter,
7120 mlir::Location loc, mlir::Value inputPtr,
7121 uint64_t baseAlignment,
7122 cir::OffsetPairAttr paddingAttr) {
7123 // FIXME(cir): Classic-codegen pulls this from the data layout, but MLIR
7124 // DataLayout just assumes it is 8 everywhere (as does all our lowering).
7125 // Clang doesn't support any non-8-bit-CHAR_BIT architectures, but keeping
7126 // this separate so we can use it next time.
7127 uint64_t charWidth = 8;
7128 mlir::Type i8Ty = rewriter.getI8Type();
7129 mlir::Type ptrTy = mlir::LLVM::LLVMPointerType::get(i8Ty.getContext());
7130
7131 auto startByte = paddingAttr.getStart() / charWidth;
7132 auto startBit = paddingAttr.getStart() % charWidth;
7133 auto endByte = paddingAttr.getEnd() / charWidth;
7134 auto endBit = paddingAttr.getEnd() % charWidth;
7135
7136 if (startByte == endByte) {
7137 // Interval is within a single byte
7138 auto index = mlir::LLVM::ConstantOp::create(
7139 rewriter, loc, rewriter.getI32Type(), startByte);
7140 auto element = mlir::LLVM::GEPOp::create(rewriter, loc, ptrTy, i8Ty,
7141 inputPtr, {index});
7142
7143 uint64_t adjustedAlignment = llvm::MinAlign(baseAlignment, startByte);
7144
7145 auto value = mlir::LLVM::LoadOp::create(rewriter, loc, i8Ty, element,
7146 adjustedAlignment);
7147
7148 // Create mask to clear bits within the byte
7149 // We want to clear bits from StartBit to EndBit-1
7150 uint8_t bitsToClear = ((1 << endBit) - 1) & ~((1 << startBit) - 1);
7151 uint8_t bitsToKeep = ~bitsToClear;
7152 auto maskValue =
7153 mlir::LLVM::ConstantOp::create(rewriter, loc, i8Ty, bitsToKeep);
7154 auto newValue = mlir::LLVM::AndOp::create(rewriter, loc, value, maskValue);
7155
7156 mlir::LLVM::StoreOp::create(rewriter, loc, newValue, element,
7157 adjustedAlignment);
7158 } else {
7159 // Handle the start byte
7160 if (startBit != 0) {
7161 auto index = mlir::LLVM::ConstantOp::create(
7162 rewriter, loc, rewriter.getI32Type(), startByte);
7163 auto element = mlir::LLVM::GEPOp::create(rewriter, loc, ptrTy, i8Ty,
7164 inputPtr, {index});
7165 uint64_t adjustedAlignment = llvm::MinAlign(baseAlignment, startByte);
7166
7167 auto value = mlir::LLVM::LoadOp::create(rewriter, loc, i8Ty, element,
7168 adjustedAlignment);
7169
7170 uint8_t bitsToClear = ((1 << (charWidth - startBit)) - 1) << startBit;
7171 uint8_t bitsToKeep = ~bitsToClear;
7172 auto maskValue =
7173 mlir::LLVM::ConstantOp::create(rewriter, loc, i8Ty, bitsToKeep);
7174 auto newValue =
7175 mlir::LLVM::AndOp::create(rewriter, loc, value, maskValue);
7176
7177 mlir::LLVM::StoreOp::create(rewriter, loc, newValue, element,
7178 adjustedAlignment);
7179 ++startByte;
7180 }
7181
7182 // Handle full bytes in the middle
7183 for (auto offset = startByte; offset < endByte; ++offset) {
7184 auto index = mlir::LLVM::ConstantOp::create(
7185 rewriter, loc, rewriter.getI32Type(), offset);
7186 auto element = mlir::LLVM::GEPOp::create(rewriter, loc, ptrTy, i8Ty,
7187 inputPtr, {index});
7188 uint64_t adjustedAlignment = llvm::MinAlign(baseAlignment, offset);
7189
7190 auto zero = mlir::LLVM::ConstantOp::create(rewriter, loc, i8Ty, 0);
7191 mlir::LLVM::StoreOp::create(rewriter, loc, zero, element,
7192 adjustedAlignment);
7193 }
7194
7195 // Handle the end byte
7196 if (endBit != 0) {
7197 auto index = mlir::LLVM::ConstantOp::create(
7198 rewriter, loc, rewriter.getI32Type(), endByte);
7199 auto element = mlir::LLVM::GEPOp::create(rewriter, loc, ptrTy, i8Ty,
7200 inputPtr, {index});
7201 uint64_t adjustedAlignment = llvm::MinAlign(baseAlignment, endByte);
7202
7203 auto value = mlir::LLVM::LoadOp::create(rewriter, loc, i8Ty, element,
7204 adjustedAlignment);
7205
7206 uint8_t bitsToClear = (1 << endBit) - 1;
7207 uint8_t bitsToKeep = ~bitsToClear;
7208 auto maskValue =
7209 mlir::LLVM::ConstantOp::create(rewriter, loc, i8Ty, bitsToKeep);
7210 auto newValue =
7211 mlir::LLVM::AndOp::create(rewriter, loc, value, maskValue);
7212
7213 mlir::LLVM::StoreOp::create(rewriter, loc, newValue, element,
7214 adjustedAlignment);
7215 }
7216 }
7217}
7218
7219mlir::LogicalResult CIRToLLVMClearPaddingOpLowering::matchAndRewrite(
7220 cir::ClearPaddingOp op, OpAdaptor adaptor,
7221 mlir::ConversionPatternRewriter &rewriter) const {
7222
7223 mlir::Value inputPtr = adaptor.getArg();
7224 for (mlir::Attribute attr : op.getPadding())
7225 clearPadding(rewriter, op.getLoc(), inputPtr, op.getAlignment(),
7226 cast<cir::OffsetPairAttr>(attr));
7227
7228 rewriter.eraseOp(op);
7229 return mlir::success();
7230}
7231
7232std::unique_ptr<mlir::Pass> createConvertCIRToLLVMPass() {
7233 return std::make_unique<ConvertCIRToLLVMPass>();
7234}
7235
7236void populateCIRToLLVMPasses(mlir::OpPassManager &pm, bool enableOpenMP,
7237 bool enableOptimizations) {
7239 if (enableOpenMP)
7240 pm.addPass(mlir::omp::createMarkDeclareTargetPass());
7241 pm.addPass(createConvertCIRToLLVMPass());
7242 if (enableOpenMP) {
7243 pm.addPass(mlir::omp::createHostOpFilteringPass());
7244 pm.nest<mlir::LLVM::LLVMFuncOp>().addPass(
7245 mlir::omp::createStackToSharedPass());
7246 }
7247 if (enableOptimizations)
7248 pm.nest<mlir::LLVM::LLVMFuncOp>().addPass(
7249 mlir::LLVM::createLLVMSimplifyCFGPass());
7250}
7251
7252std::unique_ptr<llvm::Module>
7253lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp mlirModule, LLVMContext &llvmCtx,
7254 bool enableOpenMP, StringRef mlirSaveTempsOutFile,
7255 llvm::vfs::FileSystem *fs,
7256 bool enableOptimizations) {
7257 llvm::TimeTraceScope scope("lower from CIR to LLVM directly");
7258
7259 mlir::MLIRContext *mlirCtx = mlirModule.getContext();
7260
7261 mlir::PassManager pm(mlirCtx);
7262 populateCIRToLLVMPasses(pm, enableOpenMP, enableOptimizations);
7263
7264 (void)mlir::applyPassManagerCLOptions(pm);
7265
7266 // The failing pass has already reported its error through the MLIR
7267 // diagnostic engine.
7268 if (mlir::failed(pm.run(mlirModule)))
7269 return nullptr;
7270
7271 if (!mlirSaveTempsOutFile.empty()) {
7272 std::error_code ec;
7273 llvm::raw_fd_ostream out(mlirSaveTempsOutFile, ec);
7274 if (!ec)
7275 mlirModule->print(out);
7276 }
7277
7278 mlir::registerBuiltinDialectTranslation(*mlirCtx);
7279 mlir::registerLLVMDialectTranslation(*mlirCtx);
7280 mlir::registerOpenMPDialectTranslation(*mlirCtx);
7282
7283 llvm::TimeTraceScope translateScope("translateModuleToLLVMIR");
7284
7285 StringRef moduleName = mlirModule.getName().value_or("CIRToLLVMModule");
7286 std::unique_ptr<llvm::Module> llvmModule = mlir::translateModuleToLLVMIR(
7287 mlirModule, llvmCtx, moduleName, /*disableVerification=*/false, fs);
7288
7289 return llvmModule;
7290}
7291} // namespace direct
7292} // namespace cir
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
TokenType getType() const
Returns the token's type, e.g.
#define CHECK_ENUM(CIR, LLVM_VAL)
mlir::Attribute spellOutSplitTrailingZeros(mlir::Attribute attr)
Return attr with the trailing zeros of any array that adjustGlobalTypeForInit would split off written...
mlir::Value createLShR(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs)
mlir::Value createShL(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs)
mlir::Value createAShR(mlir::OpBuilder &bld, mlir::Value lhs, unsigned rhs)
mlir::Value createAnd(mlir::OpBuilder &bld, mlir::Value lhs, const llvm::APInt &rhs)
mlir::Type convertTypeForLoadStore(const mlir::TypeConverter &converter, mlir::DataLayout const &dataLayout, mlir::Type type)
The type of a load/store's value, as opposed to convertTypeForMemory's type of the memory it lives in...
mlir::Type adjustGlobalTypeForInit(mlir::Type llvmType, mlir::Attribute init, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout, mlir::Type *failedType=nullptr)
Adjust llvmType (the converted type of init) to the concrete LLVM type a global constant initialized ...
llvm::StringMap< mlir::Type > CIRPreConversionTypeMap
std::optional< mlir::Attribute > lowerConstArrayAttr(cir::ConstArrayAttr constArr, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, const CIRPreConversionTypeMap &preConversionTypes, mlir::ModuleOp moduleOp)
std::optional< mlir::Attribute > lowerConstRecordAttr(cir::ConstRecordAttr constRecord, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, const CIRPreConversionTypeMap &preConversionTypes, mlir::ModuleOp moduleOp)
mlir::Type convertTypeForMemory(const mlir::TypeConverter &converter, mlir::DataLayout const &dataLayout, mlir::Type type, bool isForHLSL=false)
mlir::Attribute getBitIntStorageAttr(mlir::ConversionPatternRewriter &rewriter, cir::IntAttr attr, const mlir::DataLayout &dataLayout)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
__DEVICE__ void * memset(void *__a, int __b, size_t __c)
uint64_t getTypeLanguageAlignment(mlir::Type ty) const
Returns the alignment, in bytes, that the source language requires for an object of type ty.
unsigned getProgramAddressSpace() const
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:153
CIRAttrToValue(mlir::Location parentLoc, mlir::ModuleOp parentModule, mlir::ConversionPatternRewriter &rewriter, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, const CIRPreConversionTypeMap &preConversionTypes, LLVMBlockAddressInfo *blockInfoAddr=nullptr)
GlobalInitAttrRewriter(mlir::Type type, mlir::DataLayout const &dataLayout, mlir::ConversionPatternRewriter &rewriter)
mlir::Attribute visit(mlir::Attribute attr)
mlir::Attribute visitCirAttr(cir::FPAttr attr)
mlir::Attribute visitCirAttr(cir::BoolAttr attr)
mlir::Attribute visitCirAttr(cir::IntAttr attr)
static mlir::LLVM::CConv convertCallingConv(cir::CallingConv callingConv)
static mlir::Value toVectorElement(mlir::OpBuilder &builder, mlir::Location loc, mlir::Type cirTy, mlir::Value value)
Converts value, the lowered form of a scalar of CIR type cirTy, to the LLVM vector element type for c...
static uint64_t getTypeAllocSize(mlir::Type type, mlir::Operation &op)
static mlir::LogicalResult lowerCallAttributes(cir::CIRCallOpInterface op, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout, LoweredCallAttributes &result)
static mlir::LLVM::FastmathFlags convertFastMathFlags(cir::FastMathFlags cirFlags)
static llvm::StringRef getLLVMSyncScope(cir::SyncScopeKind syncScope, mlir::ModuleOp moduleOp)
static void buildCtorDtorList(mlir::ModuleOp module, StringRef globalXtorName, StringRef llvmXtorName, llvm::function_ref< cir::GlobalCtorDtorEntry(mlir::Attribute)> createXtor)
static mlir::LogicalResult lowerIncDecOp(CIROp op, typename CIROp::Adaptor adaptor, mlir::ConversionPatternRewriter &rewriter)
static mlir::Value fromVectorElement(mlir::OpBuilder &builder, mlir::Location loc, const mlir::TypeConverter &converter, mlir::Type cirTy, mlir::Value element)
Converts element, an LLVM vector element of CIR type cirTy, to the lowered form of a scalar of that t...
static mlir::Value createVTableLoadRelative(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, mlir::Value vptr, mlir::Value byteOffset)
Read the pointer that is stored in the vtable vptr as the 32-bit offset of the entry at byteOffset,...
static bool isSignalingConstrainedFCmp(cir::CmpOpKind kind)
static mlir::LLVM::AtomicBinOp getLLVMAtomicBinOp(cir::AtomicFetchKind k, bool isInt, bool isSignedInt)
static mlir::SymbolRefAttr getComdatAttrHelper(mlir::ModuleOp modOp, mlir::OpBuilder &builder, StringRef symName, mlir::LLVM::ComdatOp &comdatOp, mlir::SymbolTableCollection &symbolTables)
static mlir::LLVM::ICmpPredicate convertCmpKindToICmpPredicate(cir::CmpOpKind kind, bool isSigned)
Convert from a CIR comparison kind to an LLVM IR integral comparison kind.
static bool isBulkLowerableConstArrayBaseElement(mlir::Type baseElemTy)
mlir::LogicalResult lowerFPOp(mlir::Operation *op, mlir::ValueRange operands, cir::FastMathFlagsAttr fastmath, const mlir::TypeConverter &typeConverter, mlir::ConversionPatternRewriter &rewriter)
static bool isHandledDiscardableFuncAttr(mlir::NamedAttribute attr)
Return true for discardable CIR markers handled explicitly below.
static void forwardAMDGPUAtomicOptionMarkers(mlir::Operation *op, mlir::Operation *llvmOp)
mlir::Value lowerCirAttrAsValue(mlir::Location parentLoc, mlir::ModuleOp parentModule, const mlir::Attribute attr, mlir::ConversionPatternRewriter &rewriter, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, const CIRPreConversionTypeMap &preConversionTypes, LLVMBlockAddressInfo *blockInfoAddr)
Switches on the type of attribute and calls the appropriate conversion.
static void setLoweredCallAttributes(CallLikeOp op, const LoweredCallAttributes &attributes)
static mlir::Value castBitIntMemoryStorage(mlir::ConversionPatternRewriter &rewriter, const mlir::DataLayout &dataLayout, cir::IntType intTy, mlir::Value value, bool toMemory)
Cast a _BitInt(N) value between its literal width iN and its padded in-memory storage iM (sign/zero-e...
static mlir::LLVM::CallIntrinsicOp createConstrainedFCmpCall(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OpKindTy kind, bool isSignaling, cir::FenvAttr fenv, mlir::Type llvmResTy)
static mlir::Value getLLVMIntCast(mlir::ConversionPatternRewriter &rewriter, mlir::Value llvmSrc, mlir::Type llvmDstIntTy, bool isUnsigned, uint64_t cirSrcWidth, uint64_t cirDstIntWidth)
static constexpr char kTypeConversionErrorMsg[]
static mlir::Value createConstrainedFPIntrinsicCall(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, mlir::ValueRange operands, mlir::Type llvmResTy, cir::FenvAttr fenv, llvm::StringRef constrainedMnemonic, bool hasRoundingMode, mlir::LLVM::FastmathFlags fastmathFlags={})
mlir::LogicalResult lowerToConstrainedFPIntrinsic(mlir::Operation *op, mlir::ValueRange operands, cir::FenvAttr fenv, mlir::Type llvmResTy, mlir::ConversionPatternRewriter &rewriter, llvm::StringRef constrainedMnemonic, bool hasRoundingMode, mlir::LLVM::FastmathFlags fastmathFlags)
mlir::IntegerType computeBitfieldIntType(mlir::Type storageType, mlir::MLIRContext *context, unsigned &storageSize)
static mlir::InFlightDiagnostic emitTypeConversionError(mlir::Operation *op, mlir::Type type)
static llvm::StringRef getConstrainedExceptMetadata(cir::FenvAttr fenv)
static mlir::Value getValueForVTableSymbol(mlir::Operation *op, mlir::ConversionPatternRewriter &rewriter, mlir::SymbolTableCollection &symbolTables, const mlir::TypeConverter *converter, const CIRPreConversionTypeMap &preConversionTypes, mlir::FlatSymbolRefAttr nameAttr, mlir::Type &eltType)
static mlir::LLVM::ThreadLocalMode convertTlsModelAttrToLLVM(TLSModelAttr attr)
static mlir::LLVM::CallIntrinsicOp replaceOpWithCallLLVMIntrinsicOp(mlir::ConversionPatternRewriter &rewriter, mlir::Operation *op, const llvm::Twine &intrinsicName, mlir::Type resultTy, mlir::ValueRange operands, mlir::LLVM::FastmathFlags fastmathFlags={})
static mlir::Value createFenvMetadataValue(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, llvm::StringRef str)
static mlir::Value computeMatrixFlatIndex(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, cir::MatrixType matrixTy, mlir::Value rowIdx, mlir::Value columnIdx)
Computes the column-major flat index (columnIdx * numRows) + rowIdx.
static mlir::LogicalResult lowerMinMaxOp(CIROp op, typename CIROp::Adaptor adaptor, mlir::ConversionPatternRewriter &rewriter)
std::unique_ptr< llvm::Module > lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp mlirModule, llvm::LLVMContext &llvmCtx, bool enableOpenMP, llvm::StringRef mlirSaveTempsOutFile={}, llvm::vfs::FileSystem *fs=nullptr, bool enableOptimizations=false)
Lowers mlirModule, a CIR module, to an LLVM module in llvmCtx.
static mlir::LLVM::LLVMStructType getLLVMLandingPadStructTy(mlir::ConversionPatternRewriter &rewriter)
static mlir::LLVM::CallIntrinsicOp createCallLLVMIntrinsicOp(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, const llvm::Twine &intrinsicName, mlir::Type resultTy, mlir::ValueRange operands, mlir::LLVM::FastmathFlags fastmathFlags={})
static llvm::StringRef getConstrainedRoundingMetadata(cir::FenvAttr fenv)
void populateCIRToLLVMPasses(mlir::OpPassManager &pm, bool enableOpenMP, bool enableOptimizations=false)
Adds passes that fully lower CIR to the LLVMIR dialect.
static mlir::LLVM::framePointerKind::FramePointerKind convertFramePointerKind(cir::FramePointerKind kind)
static mlir::LLVM::MemoryEffectsAttr convertMemoryEffects(mlir::MLIRContext *ctx, cir::MemoryEffectsAttr effects)
A null input stays null, which is how both dialects spell unknown effects.
static mlir::Value convertToIndexTy(mlir::ConversionPatternRewriter &rewriter, mlir::ModuleOp mod, mlir::Value index, mlir::Type baseTy, cir::IntType strideTy)
static mlir::LogicalResult lowerIntBinaryOp(CIROp op, mlir::Value lhs, mlir::Value rhs, mlir::ConversionPatternRewriter &rewriter)
Lower an integer op to its signed or unsigned LLVM counterpart.
static std::optional< mlir::ArrayAttr > convertTypedArgAttrs(mlir::ArrayAttr argAttrs, const mlir::TypeConverter &converter, const mlir::DataLayout &dataLayout, mlir::MLIRContext *ctx)
The llvm.byval, llvm.sret, and llvm.byref argument attributes carry the pointee type as a TypeAttr.
void createLLVMFuncOpIfNotExist(mlir::ConversionPatternRewriter &rewriter, mlir::SymbolTableCollection &symbolTables, mlir::Operation *srcOp, llvm::StringRef fnName, mlir::Type fnTy, mlir::ArrayAttr argAttrs, mlir::ArrayAttr resAttrs)
Declare fnName with type fnTy before the function enclosing srcOp, unless the module already has a sy...
static mlir::LLVM::uwtable::UWTableKind convertUWTableKind(cir::UnwindTableKind kind)
static llvm::FramePointerKind convertFramePointerKindToLLVMIR(cir::FramePointerKind kind)
The "frame-pointer" module flag holds an llvm::FramePointerKind value, as written by llvm::Module::se...
static void prepareTypeConverter(mlir::LLVMTypeConverter &converter, mlir::DataLayout &dataLayout)
static mlir::LLVM::AtomicOrdering getLLVMMemOrder(std::optional< cir::MemOrder > memorder)
std::unique_ptr< mlir::Pass > createConvertCIRToLLVMPass()
Create a pass that fully lowers CIR to the LLVMIR dialect.
static mlir::Type getConstArrayBaseElementType(mlir::Type ty)
static mlir::LLVM::FCmpPredicate convertCmpKindToFCmpPredicate(cir::CmpOpKind kind)
Convert from a CIR comparison kind to an LLVM IR floating-point comparison kind.
static uint64_t getMemoryFallbackAlignment(mlir::Operation *op, mlir::Type cirType, mlir::Type llvmMemType, const mlir::DataLayout &dataLayout)
Alignment to use for a memory access whose op carries no explicit alignment.
static llvm::StringRef convertCmpKindToConstrainedFCmpPredicate(cir::CmpOpKind kind)
static mlir::LLVM::Visibility lowerCIRVisibilityToLLVMVisibility(cir::VisibilityKind visibilityKind)
static mlir::LLVM::ModRefInfo convertModRefInfo(cir::ModRefInfo info)
static llvm::AtomicScope getAtomicScope(cir::SyncScopeKind syncScope)
mlir::LogicalResult lowerConstrainableFPOp(mlir::Operation *op, mlir::ValueRange operands, cir::FenvAttr fenv, cir::FastMathFlagsAttr fastmath, const mlir::TypeConverter &typeConverter, mlir::ConversionPatternRewriter &rewriter, llvm::StringRef constrainedMnemonic, bool hasRoundingMode)
static mlir::Value emitBoolVecConversion(mlir::ConversionPatternRewriter &rewriter, mlir::Value srcVec, unsigned numElementsDst)
static void convertCallEffects(mlir::Operation *callOp, bool isNothrow, cir::MemoryEffectsAttr effects, mlir::LLVM::MemoryEffectsAttr &memoryEffect, bool &noUnwind, bool &willReturn, bool &noReturn)
static mlir::LogicalResult lowerMemTransferOp(CIROp op, typename CIROp::Adaptor adaptor, mlir::ConversionPatternRewriter &rewriter)
void annotateAMDGPUPrintfStrings(mlir::ModuleOp module, mlir::SymbolTableCollection &symbolTables)
Resolve constant format strings for AMDGPU printf ops while their producers are still CIR,...
static llvm::StringLiteral getLLVMBinopForPostAtomic(cir::AtomicFetchKind k, bool isInt)
mlir::LLVM::Linkage convertLinkage(cir::GlobalLinkageKind linkage)
static mlir::LogicalResult lowerBinOpOverflow(OpTy op, typename OpTy::Adaptor adaptor, mlir::ConversionPatternRewriter &rewriter, const mlir::TypeConverter *typeConverter, llvm::StringRef opStr)
Shared lowering logic for checked binary arithmetic overflow operations.
void lowerOpenCLModuleMetadataAttrs(mlir::ModuleOp module)
static mlir::Value emitFromMemory(mlir::ConversionPatternRewriter &rewriter, const mlir::TypeConverter &converter, mlir::DataLayout const &dataLayout, cir::LoadOp op, mlir::Value value)
Emits the value from memory as expected by its users.
static mlir::Value createIntCast(mlir::OpBuilder &bld, mlir::Value src, mlir::IntegerType dstTy, bool isSigned=false)
static mlir::LLVM::IntegerOverflowFlags nswFlag(bool nsw)
static void clearPadding(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc, mlir::Value inputPtr, uint64_t baseAlignment, cir::OffsetPairAttr paddingAttr)
static mlir::Value emitToMemory(mlir::ConversionPatternRewriter &rewriter, mlir::DataLayout const &dataLayout, mlir::Type origType, mlir::Value value)
Emits a value to memory with the expected scalar type.
static mlir::LogicalResult rewriteCallOrInvoke(mlir::Operation *op, mlir::ValueRange callOperands, mlir::ConversionPatternRewriter &rewriter, const mlir::TypeConverter *converter, const mlir::DataLayout &dataLayout, mlir::SymbolTableCollection &symbolTables, mlir::FlatSymbolRefAttr calleeAttr, mlir::Block *continueBlock=nullptr, mlir::Block *landingPadBlock=nullptr)
static mlir::LLVM::GlobalOp replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op, mlir::Type llvmType, bool isConst, mlir::LLVM::Linkage linkage, llvm::StringRef symbol, mlir::Attribute init, uint64_t alignment, unsigned addrSpace, bool isDsoLocal, mlir::LLVM::ThreadLocalMode threadLocalMode, mlir::SymbolRefAttr comdatAttr, llvm::ArrayRef< mlir::NamedAttribute > attributes, mlir::ConversionPatternRewriter &rewriter)
static void forwardAMDGPUNoPrivateAddrSpace(mlir::Operation *op, mlir::Operation *llvmOp, mlir::Value llvmPtr)
mlir::LLVM::FastmathFlagsAttr convertToLLVMProperty(mlir::MLIRContext *ctx, std::optional< cir::FastMathFlags > flags)
static bool isIntTypeUnsigned(mlir::Type type)
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
Definition CIRTypes.h:138
void collectUnreachable(mlir::Operation *parent, llvm::SmallVectorImpl< mlir::Operation * > &ops)
Collect ops in blocks that are unreachable from their region's entry, appending them to ops.
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:129
Op::Properties getDefaultProperties(mlir::MLIRContext *context)
The properties of Op with every ODS-declared default applied.
Definition CIRDialect.h:85
uint64_t getVTableEntrySize(mlir::ModuleOp mod, const mlir::DataLayout &dataLayout)
The size in bytes of an entry of a C++ vtable in module.
bool isBitIntType(mlir::Type ty)
Returns true if the type is a cir::IntType representing a _BitInt.
Definition CIRTypes.cpp:43
bool usesRelativeVTables(mlir::ModuleOp mod)
Whether the C++ vtables of module use the relative layout.
std::optional< llvm::Triple > getTripleFromModule(mlir::ModuleOp mod)
Attempts to construct an llvm::Triple from a module's cir.triple attribute.
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ComplexType > complexType
llvm::APInt APInt
Definition FixedPoint.h:19
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
@ Default
Set to the current date and time.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
void populateCIRPreLoweringPasses(mlir::OpPassManager &pm)
void registerCIRDialectTranslation(mlir::MLIRContext &context)
int line
Definition c++config.h:31
char __ovld __cnfn clz(char)
Returns the number of leading 0-bits in x, starting at the most significant bit position.
char __ovld __cnfn ctz(char)
Returns the count of trailing 0-bits in x.
float __ovld __cnfn sign(float)
Returns 1.0 if x > 0, -0.0 if x = -0.0, +0.0 if x = +0.0, or -1.0 if x < 0.
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
char __ovld __cnfn select(char, char, char)
For each component of a vector type, result[i] = if MSB of c[i] is set ?
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t
Helper type for lowering global ctor/dtors, that contain all the values needed for transforming the v...
static bool dataMemberType()
static bool addressSpace()
static bool opCallInvokeAttrs()
static bool annotationConstantAddrSpace()
static bool opLoadStoreTbaa()
static bool opFuncPreferredAlignment()
static bool optInfoAttr()
static bool opFuncExtraAttrs()
static bool isPPC_FP128Ty()
static bool vaArgABILowering()
static bool fpConstraints()
static bool intrinsicElementTypeSupport()
static bool lowerModeOptLevel()
static bool opFuncCallingConv()
static bool aggValueSlotVolatile()
static bool fastMathFlags()
static bool llvmLoweringPtrDiffConsidersPointee()
static bool atomicSyncScopeID()
static bool vtableRelativeLayout()
static bool opFuncMultipleReturnVals()
void collectGlobalAnnotations(mlir::ModuleOp module)
Collect (symbol_name, annotations, loc) from cir.func and cir.global ops before the conversion runs (...
StringRef getDescription() const override
StringRef getArgument() const override
void getDependentDialects(mlir::DialectRegistry &registry) const override
void resolveBlockAddressOp(LLVMBlockAddressInfo &blockInfoAddr)
void processCIRAttrs(mlir::ModuleOp module)
void buildGlobalAnnotationsVar(mlir::ModuleOp module, LLVMAnnotationGlobals &annotationGlobals)
Emit @llvm.global.annotations and supporting string/args constants from the previously-collected anno...
Annotation strings and arguments, shared by all annotations in a module.
llvm::StringMap< mlir::LLVM::GlobalOp > stringCache
llvm::StringMap< mlir::LLVM::GlobalOp > argStringCache
LLVMAnnotationGlobals(mlir::ModuleOp module)
llvm::MapVector< mlir::ArrayAttr, mlir::LLVM::GlobalOp > argsCache
mlir::LLVM::BlockTagOp lookupBlockTag(cir::BlockAddrInfoAttr info) const
Definition LowerToLLVM.h:64
llvm::DenseMap< mlir::LLVM::BlockAddressOp, cir::BlockAddrInfoAttr > & getUnresolvedBlockAddress()
Definition LowerToLLVM.h:77
SmallVector< mlir::NamedAttribute > discardableAttrs