clang 24.0.0git
CIRGenExprScalar.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// Emit Expr nodes with scalar CIR types as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
15#include "CIRGenFunction.h"
16#include "CIRGenValue.h"
17
18#include "clang/AST/Expr.h"
23
24#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
25#include "mlir/IR/Location.h"
26#include "mlir/IR/Value.h"
27
28#include <cassert>
29#include <numeric>
30#include <utility>
31
32using namespace clang;
33using namespace clang::CIRGen;
34
35namespace {
36
37struct BinOpInfo {
38 mlir::Value lhs;
39 mlir::Value rhs;
40 SourceRange loc;
41 QualType fullType; // Type of operands and result
42 QualType compType; // Type used for computations. Element type
43 // for vectors, otherwise same as FullType.
44 BinaryOperator::Opcode opcode; // Opcode of BinOp to perform
45 FPOptions fpFeatures;
46 const Expr *e; // Entire expr, for error unsupported. May not be binop.
47
48 /// Check if the binop computes a division or a remainder.
49 bool isDivRemOp() const {
50 return opcode == BO_Div || opcode == BO_Rem || opcode == BO_DivAssign ||
51 opcode == BO_RemAssign;
52 }
53
54 /// Check if the binop can result in integer overflow.
55 bool mayHaveIntegerOverflow() const {
56 // Without constant input, we can't rule out overflow.
57 auto lhsci = lhs.getDefiningOp<cir::ConstantOp>();
58 auto rhsci = rhs.getDefiningOp<cir::ConstantOp>();
59 if (!lhsci || !rhsci)
60 return true;
61
63 // TODO(cir): For now we just assume that we might overflow
64 return true;
65 }
66
67 /// Check if at least one operand is a fixed point type. In such cases,
68 /// this operation did not follow usual arithmetic conversion and both
69 /// operands might not be of the same type.
70 bool isFixedPointOp() const {
71 // We cannot simply check the result type since comparison operations
72 // return an int.
73 if (const auto *binOp = llvm::dyn_cast<BinaryOperator>(e)) {
74 QualType lhstype = binOp->getLHS()->getType();
75 QualType rhstype = binOp->getRHS()->getType();
76 return lhstype->isFixedPointType() || rhstype->isFixedPointType();
77 }
78 if (const auto *unop = llvm::dyn_cast<UnaryOperator>(e))
79 return unop->getSubExpr()->getType()->isFixedPointType();
80 return false;
81 }
82};
83
84class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
85 CIRGenFunction &cgf;
86 CIRGenBuilderTy &builder;
87 // Unlike classic codegen we set this to false or use std::exchange to read
88 // the value instead of calling TestAndClearIgnoreResultAssign to make it
89 // explicit when the value is used
90 bool ignoreResultAssign;
91
92public:
93 ScalarExprEmitter(CIRGenFunction &cgf, CIRGenBuilderTy &builder,
94 bool ignoreResultAssign = false)
95 : cgf(cgf), builder(builder), ignoreResultAssign(ignoreResultAssign) {}
96
97 //===--------------------------------------------------------------------===//
98 // Utilities
99 //===--------------------------------------------------------------------===//
100 mlir::Type convertType(QualType ty) { return cgf.convertType(ty); }
101
102 mlir::Value emitComplexToScalarConversion(mlir::Location loc,
103 mlir::Value value, CastKind kind,
104 QualType destTy);
105
106 mlir::Value emitNullValue(QualType ty, mlir::Location loc) {
107 return cgf.cgm.emitNullConstant(ty, loc);
108 }
109
110 mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType) {
111 return builder.createFloatingCast(result, cgf.convertType(promotionType));
112 }
113
114 mlir::Value emitUnPromotedValue(mlir::Value result, QualType exprType) {
115 return builder.createFloatingCast(result, cgf.convertType(exprType));
116 }
117
118 mlir::Value emitPromoted(const Expr *e, QualType promotionType);
119
120 mlir::Value maybePromoteBoolResult(mlir::Value value,
121 mlir::Type dstTy) const {
122 if (mlir::isa<cir::IntType>(dstTy))
123 return builder.createBoolToInt(value, dstTy);
124 if (mlir::isa<cir::BoolType>(dstTy))
125 return value;
126 llvm_unreachable("Can only promote integer or boolean types");
127 }
128
129 //===--------------------------------------------------------------------===//
130 // Visitor Methods
131 //===--------------------------------------------------------------------===//
132
133 mlir::Value Visit(Expr *e) {
134 return StmtVisitor<ScalarExprEmitter, mlir::Value>::Visit(e);
135 }
136
137 mlir::Value VisitStmt(Stmt *s) {
138 llvm_unreachable("Statement passed to ScalarExprEmitter");
139 }
140
141 mlir::Value VisitExpr(Expr *e) {
142 cgf.getCIRGenModule().errorNYI(
143 e->getSourceRange(), "scalar expression kind: ", e->getStmtClassName());
144 return {};
145 }
146
147 mlir::Value VisitConstantExpr(ConstantExpr *e) {
148 // A constant expression of type 'void' generates no code and produces no
149 // value.
150 if (e->getType()->isVoidType())
151 return {};
152
153 if (mlir::Attribute result = ConstantEmitter(cgf).tryEmitConstantExpr(e)) {
154 mlir::Value val = builder.getConstant(
155 cgf.getLoc(e->getSourceRange()), mlir::cast<mlir::TypedAttr>(result));
156 // This was already converted to an rvalue when it was constant evaluated.
157 if (!e->isGLValue() ||
159 return val;
160 return cgf.emitLoadOfScalar(
161 cgf.makeNaturalAlignPointeeAddrLValue(val, e->getType()),
162 e->getExprLoc());
163 }
164
165 return Visit(e->getSubExpr());
166 }
167
168 mlir::Value VisitPackIndexingExpr(PackIndexingExpr *e) {
169 return Visit(e->getSelectedExpr());
170 }
171
172 mlir::Value VisitParenExpr(ParenExpr *pe) { return Visit(pe->getSubExpr()); }
173
174 mlir::Value VisitGenericSelectionExpr(GenericSelectionExpr *ge) {
175 return Visit(ge->getResultExpr());
176 }
177
178 /// Emits the address of the l-value, then loads and returns the result.
179 mlir::Value emitLoadOfLValue(const Expr *e) {
180 LValue lv = cgf.emitLValue(e);
181 // FIXME: add some akin to EmitLValueAlignmentAssumption(E, V);
182 return cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
183 }
184
185 mlir::Value VisitCoawaitExpr(CoawaitExpr *s) {
186 return cgf.emitCoawaitExpr(*s).getValue();
187 }
188
189 mlir::Value VisitCoyieldExpr(CoyieldExpr *e) {
190 return cgf.emitCoyieldExpr(*e).getValue();
191 }
192
193 mlir::Value VisitUnaryCoawait(const UnaryOperator *e) {
194 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: unary coawait");
195 return {};
196 }
197
198 mlir::Value emitLoadOfLValue(LValue lv, SourceLocation loc) {
199 return cgf.emitLoadOfLValue(lv, loc).getValue();
200 }
201
202 // l-values
203 mlir::Value VisitDeclRefExpr(DeclRefExpr *e) {
204 if (CIRGenFunction::ConstantEmission constant = cgf.tryEmitAsConstant(e))
205 return cgf.emitScalarConstant(constant, e);
206
207 return emitLoadOfLValue(e);
208 }
209
210 mlir::Value VisitAddrLabelExpr(const AddrLabelExpr *e) {
211 auto func = cast<cir::FuncOp>(cgf.curFn);
212 cir::BlockAddrInfoAttr blockInfoAttr = cir::BlockAddrInfoAttr::get(
213 &cgf.getMLIRContext(), func.getSymName(), e->getLabel()->getName());
214 // GotoSolver collects this cir.block_address op after FlattenCFG to keep
215 // the label and wire it as an indirect-branch successor.
216 return cir::BlockAddressOp::create(builder, cgf.getLoc(e->getSourceRange()),
217 cgf.convertType(e->getType()),
218 blockInfoAttr);
219 }
220
221 mlir::Value VisitIntegerLiteral(const IntegerLiteral *e) {
222 mlir::Type type = cgf.convertType(e->getType());
223 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
224 cir::IntAttr::get(type, e->getValue()));
225 }
226
227 mlir::Value VisitFixedPointLiteral(const FixedPointLiteral *e) {
228 mlir::Type type = cgf.convertType(e->getType());
229 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
230 cir::IntAttr::get(type, e->getValue()));
231 }
232
233 mlir::Value VisitFloatingLiteral(const FloatingLiteral *e) {
234 mlir::Type type = cgf.convertType(e->getType());
235 assert(mlir::isa<cir::FPTypeInterface>(type) &&
236 "expect floating-point type");
237 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
238 cir::FPAttr::get(type, e->getValue()));
239 }
240
241 mlir::Value VisitCharacterLiteral(const CharacterLiteral *e) {
242 mlir::Type ty = cgf.convertType(e->getType());
243 // Character literals are always stored in an unsigned (even for signed
244 // char), so allow implicit truncation here.
245 auto intTy = mlir::cast<cir::IntTypeInterface>(ty);
246 llvm::APInt apValue(intTy.getWidth(), e->getValue(),
247 /*isSigned=*/false, /*implicitTrunc=*/true);
248 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
249 cir::IntAttr::get(ty, apValue));
250 }
251
252 mlir::Value VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *e) {
253 return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
254 }
255
256 mlir::Value VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *e) {
257 if (e->getType()->isVoidType())
258 return {};
259
260 return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
261 }
262
263 mlir::Value VisitGNUNullExpr(const GNUNullExpr *e) {
264 return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
265 }
266
267 mlir::Value VisitOffsetOfExpr(OffsetOfExpr *e);
268
269 mlir::Value VisitSizeOfPackExpr(SizeOfPackExpr *e) {
270 return builder.getConstInt(cgf.getLoc(e->getExprLoc()),
271 convertType(e->getType()), e->getPackLength());
272 }
273 mlir::Value VisitPseudoObjectExpr(PseudoObjectExpr *e) {
274 return cgf.emitPseudoObjectRValue(e).getValue();
275 }
276 mlir::Value VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *e);
277 mlir::Value VisitEmbedExpr(EmbedExpr *e) {
278 assert(e->getDataElementCount() == 1);
279 auto it = e->begin();
280 llvm::APInt value = (*it)->getValue();
281 return builder.getConstInt(cgf.getLoc(e->getExprLoc()), value,
283 }
284 mlir::Value VisitOpaqueValueExpr(OpaqueValueExpr *e) {
285 if (e->isGLValue())
286 return emitLoadOfLValue(cgf.getOrCreateOpaqueLValueMapping(e),
287 e->getExprLoc());
288
289 // Otherwise, assume the mapping is the scalar directly.
290 return cgf.getOrCreateOpaqueRValueMapping(e).getValue();
291 }
292
293 mlir::Value VisitObjCSelectorExpr(ObjCSelectorExpr *e) {
294 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc selector");
295 return {};
296 }
297 mlir::Value VisitObjCProtocolExpr(ObjCProtocolExpr *e) {
298 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc protocol");
299 return {};
300 }
301 mlir::Value VisitObjCIVarRefExpr(ObjCIvarRefExpr *e) {
302 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc ivar ref");
303 return {};
304 }
305 mlir::Value VisitObjCMessageExpr(ObjCMessageExpr *e) {
306 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc message");
307 return {};
308 }
309 mlir::Value VisitObjCIsaExpr(ObjCIsaExpr *e) {
310 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc isa");
311 return {};
312 }
313 mlir::Value VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *e) {
314 cgf.cgm.errorNYI(e->getSourceRange(),
315 "ScalarExprEmitter: objc availability check");
316 return {};
317 }
318
319 mlir::Value VisitMatrixSubscriptExpr(MatrixSubscriptExpr *e) {
320 mlir::Value rowIdx = cgf.emitScalarExpr(e->getRowIdx());
321 mlir::Value columnIdx = cgf.emitScalarExpr(e->getColumnIdx());
322 mlir::Value matrix = Visit(e->getBase());
323 mlir::Location loc = cgf.getLoc(e->getSourceRange());
325 return builder.createMatrixExtract(loc, matrix, rowIdx, columnIdx);
326 }
327
328 mlir::Value VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *e) {
329 mlir::Value rowIdx = cgf.emitScalarExpr(e->getRowIdx());
331 mlir::Value matrix = Visit(e->getBase());
332 mlir::Location loc = cgf.getLoc(e->getSourceRange());
333 return builder.createMatrixExtractRow(loc, matrix, rowIdx);
334 }
335
336 mlir::Value VisitCastExpr(CastExpr *e);
337 mlir::Value VisitCallExpr(const CallExpr *e);
338
339 mlir::Value VisitStmtExpr(StmtExpr *e) {
340 CIRGenFunction::StmtExprEvaluation eval(cgf);
341 if (e->getType()->isVoidType()) {
342 (void)cgf.emitCompoundStmt(*e->getSubStmt());
343 return {};
344 }
345
346 Address retAlloca =
347 cgf.createMemTemp(e->getType(), cgf.getLoc(e->getSourceRange()));
348 (void)cgf.emitCompoundStmt(*e->getSubStmt(), &retAlloca);
349
350 return cgf.emitLoadOfScalar(cgf.makeAddrLValue(retAlloca, e->getType()),
351 e->getExprLoc());
352 }
353
354 mlir::Value VisitArraySubscriptExpr(ArraySubscriptExpr *e) {
355 ignoreResultAssign = false;
356
357 if (e->getBase()->getType()->isVectorType()) {
359
360 const mlir::Location loc = cgf.getLoc(e->getSourceRange());
361 const mlir::Value vecValue = Visit(e->getBase());
362 const mlir::Value indexValue = Visit(e->getIdx());
363 return cir::VecExtractOp::create(cgf.getBuilder(), loc, vecValue,
364 indexValue);
365 }
366 // Just load the lvalue formed by the subscript expression.
367 return emitLoadOfLValue(e);
368 }
369
370 mlir::Value VisitShuffleVectorExpr(ShuffleVectorExpr *e) {
371 if (e->getNumSubExprs() == 2) {
372 // The undocumented form of __builtin_shufflevector.
373 mlir::Value inputVec = Visit(e->getExpr(0));
374 mlir::Value indexVec = Visit(e->getExpr(1));
375 return cir::VecShuffleDynamicOp::create(cgf.getBuilder(),
376 cgf.getLoc(e->getSourceRange()),
377 inputVec, indexVec);
378 }
379
380 mlir::Value vec1 = Visit(e->getExpr(0));
381 mlir::Value vec2 = Visit(e->getExpr(1));
382
383 // The documented form of __builtin_shufflevector, where the indices are
384 // a variable number of integer constants. The constants will be stored
385 // in an ArrayAttr.
386 SmallVector<mlir::Attribute, 8> indices;
387 for (unsigned i = 2; i < e->getNumSubExprs(); ++i) {
388 indices.push_back(
389 cir::IntAttr::get(cgf.getBuilder().getSInt64Ty(),
390 e->getExpr(i)
391 ->EvaluateKnownConstInt(cgf.getContext())
392 .getSExtValue()));
393 }
394
395 return cir::VecShuffleOp::create(cgf.getBuilder(),
396 cgf.getLoc(e->getSourceRange()),
397 cgf.convertType(e->getType()), vec1, vec2,
398 cgf.getBuilder().getArrayAttr(indices));
399 }
400
401 mlir::Value VisitConvertVectorExpr(ConvertVectorExpr *e) {
402 // __builtin_convertvector is an element-wise cast, and is implemented as a
403 // regular cast. The back end handles casts of vectors correctly.
404 return emitScalarConversion(Visit(e->getSrcExpr()),
405 e->getSrcExpr()->getType(), e->getType(),
406 e->getSourceRange().getBegin());
407 }
408
409 mlir::Value VisitExtVectorElementExpr(Expr *e) { return emitLoadOfLValue(e); }
410
411 mlir::Value VisitMatrixElementExpr(Expr *e) { return emitLoadOfLValue(e); }
412
413 mlir::Value VisitMemberExpr(MemberExpr *e);
414
415 mlir::Value VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
416 return emitLoadOfLValue(e);
417 }
418
419 mlir::Value VisitInitListExpr(InitListExpr *e);
420 mlir::Value emitVectorInitWithSubvectors(mlir::Location loc,
421 cir::VectorType vectorType,
422 ArrayRef<mlir::Value> inits);
423
424 mlir::Value VisitArrayInitIndexExpr(ArrayInitIndexExpr *e) {
425 assert(cgf.getArrayInitIndex() &&
426 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
427 return cgf.getArrayInitIndex();
428 }
429
430 mlir::Value VisitImplicitValueInitExpr(const ImplicitValueInitExpr *e) {
431 return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
432 }
433
434 mlir::Value VisitExplicitCastExpr(ExplicitCastExpr *e) {
435 return VisitCastExpr(e);
436 }
437
438 mlir::Value VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *e) {
439 return cgf.cgm.emitNullConstant(e->getType(),
440 cgf.getLoc(e->getSourceRange()));
441 }
442
443 /// Perform a pointer to boolean conversion.
444 mlir::Value emitPointerToBoolConversion(mlir::Value v, QualType qt) {
445 // TODO(cir): comparing the ptr to null is done when lowering CIR to LLVM.
446 // We might want to have a separate pass for these types of conversions.
447 return cgf.getBuilder().createPtrToBoolCast(v);
448 }
449
450 mlir::Value emitFloatToBoolConversion(mlir::Value src, mlir::Location loc) {
451 cir::BoolType boolTy = builder.getBoolTy();
452 return cir::CastOp::create(builder, loc, boolTy,
453 cir::CastKind::float_to_bool, src);
454 }
455
456 mlir::Value emitIntToBoolConversion(mlir::Value srcVal, mlir::Location loc) {
457 // The enumerator of an enum with an integral underlying type is lowered to
458 // that type, which can be bool. In that case the operand is already a
459 // !cir.bool, so return it -- int_to_bool requires a !cir.int source.
460 if (mlir::isa<cir::BoolType>(srcVal.getType()))
461 return srcVal;
462
463 // Because of the type rules of C, we often end up computing a
464 // logical value, then zero extending it to int, then wanting it
465 // as a logical value again.
466 // TODO: optimize this common case here or leave it for later
467 // CIR passes?
468 cir::BoolType boolTy = builder.getBoolTy();
469 return cir::CastOp::create(builder, loc, boolTy, cir::CastKind::int_to_bool,
470 srcVal);
471 }
472
473 /// Convert the specified expression value to a boolean (!cir.bool) truth
474 /// value. This is equivalent to "Val != 0".
475 mlir::Value emitConversionToBool(mlir::Value src, QualType srcType,
476 mlir::Location loc) {
477 assert(srcType.isCanonical() && "EmitScalarConversion strips typedefs");
478
479 if (srcType->isRealFloatingType())
480 return emitFloatToBoolConversion(src, loc);
481
482 if (llvm::isa<MemberPointerType>(srcType)) {
483 cgf.getCIRGenModule().errorNYI(loc, "member pointer to bool conversion");
484 return builder.getFalse(loc);
485 }
486
487 if (srcType->isIntegerType())
488 return emitIntToBoolConversion(src, loc);
489
490 assert(::mlir::isa<cir::PointerType>(src.getType()));
491 return emitPointerToBoolConversion(src, srcType);
492 }
493
494 // Emit a conversion from the specified type to the specified destination
495 // type, both of which are CIR scalar types.
496 struct ScalarConversionOpts {
497 bool treatBooleanAsSigned;
498 bool emitImplicitIntegerTruncationChecks;
499 bool emitImplicitIntegerSignChangeChecks;
500
501 ScalarConversionOpts()
502 : treatBooleanAsSigned(false),
503 emitImplicitIntegerTruncationChecks(false),
504 emitImplicitIntegerSignChangeChecks(false) {}
505
506 ScalarConversionOpts(clang::SanitizerSet sanOpts)
507 : treatBooleanAsSigned(false),
508 emitImplicitIntegerTruncationChecks(
509 sanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
510 emitImplicitIntegerSignChangeChecks(
511 sanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
512 };
513
514 // Conversion from bool, integral, or floating-point to integral or
515 // floating-point. Conversions involving other types are handled elsewhere.
516 // Conversion to bool is handled elsewhere because that's a comparison against
517 // zero, not a simple cast. This handles both individual scalars and vectors.
518 mlir::Value emitScalarCast(mlir::Value src, QualType srcType,
519 QualType dstType, mlir::Type srcTy,
520 mlir::Type dstTy, ScalarConversionOpts opts) {
521 assert(!(mlir::isa<mlir::IntegerType>(srcTy) ||
522 mlir::isa<mlir::IntegerType>(dstTy)) &&
523 "Obsolete code. Don't use mlir::IntegerType with CIR.");
524
525 mlir::Type fullDstTy = dstTy;
526 if (mlir::isa<cir::MatrixType>(srcTy) &&
527 mlir::isa<cir::MatrixType>(dstTy)) {
528 // Use the element types of the matrices to figure out the CastKind.
529 srcTy = mlir::dyn_cast<cir::MatrixType>(srcTy).getElementType();
530 dstTy = mlir::dyn_cast<cir::MatrixType>(dstTy).getElementType();
531 } else if (mlir::isa<cir::VectorType>(srcTy) &&
532 mlir::isa<cir::VectorType>(dstTy)) {
533 // Use the element types of the vectors to figure out the CastKind.
534 srcTy = mlir::dyn_cast<cir::VectorType>(srcTy).getElementType();
535 dstTy = mlir::dyn_cast<cir::VectorType>(dstTy).getElementType();
536 }
537
538 std::optional<cir::CastKind> castKind;
539
540 // Start with a null fenv attr. If this is a floating point cast, we will
541 // get the attribute from the builder.
542 cir::FenvAttr fenvAttr;
543
544 if (mlir::isa<cir::BoolType>(srcTy)) {
545 if (opts.treatBooleanAsSigned)
546 cgf.getCIRGenModule().errorNYI("signed bool");
547 if (cgf.getBuilder().isInt(dstTy)) {
548 castKind = cir::CastKind::bool_to_int;
549 } else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
550 fenvAttr = cgf.getBuilder().getConstrainedFPAttr();
551 castKind = cir::CastKind::bool_to_float;
552 } else {
553 llvm_unreachable("Internal error: Cast to unexpected type");
554 }
555 } else if (cgf.getBuilder().isInt(srcTy)) {
556 if (cgf.getBuilder().isInt(dstTy)) {
557 castKind = cir::CastKind::integral;
558 } else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
559 fenvAttr = cgf.getBuilder().getConstrainedFPAttr();
560 castKind = cir::CastKind::int_to_float;
561 } else if (mlir::isa<cir::BoolType>(dstTy)) {
562 castKind = cir::CastKind::int_to_bool;
563 } else {
564 llvm_unreachable("Internal error: Cast to unexpected type");
565 }
566 } else if (mlir::isa<cir::FPTypeInterface>(srcTy)) {
567 fenvAttr = cgf.getBuilder().getConstrainedFPAttr();
568 if (cgf.getBuilder().isInt(dstTy)) {
569 // If we can't recognize overflow as undefined behavior, assume that
570 // overflow saturates. This protects against normal optimizations if we
571 // are compiling with non-standard FP semantics.
572 if (!cgf.cgm.getCodeGenOpts().StrictFloatCastOverflow)
573 cgf.getCIRGenModule().errorNYI("strict float cast overflow");
574 castKind = cir::CastKind::float_to_int;
575 } else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
576 // TODO: split this to createFPExt/createFPTrunc
577 return builder.createFloatingCast(src, fullDstTy);
578 } else if (mlir::isa<cir::BoolType>(dstTy)) {
579 castKind = cir::CastKind::float_to_bool;
580 } else {
581 llvm_unreachable("Internal error: Cast to unexpected type");
582 }
583 } else {
584 llvm_unreachable("Internal error: Cast from unexpected type");
585 }
586
587 assert(castKind.has_value() && "Internal error: CastKind not set.");
588 return builder.createOrFold<cir::CastOp>(src.getLoc(), fullDstTy, *castKind,
589 src, fenvAttr);
590 }
591
592 mlir::Value
593 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e) {
594 return Visit(e->getReplacement());
595 }
596
597 mlir::Value VisitVAArgExpr(VAArgExpr *ve) {
598 QualType ty = ve->getType();
599
600 if (ty->isVariablyModifiedType()) {
601 cgf.cgm.errorNYI(ve->getSourceRange(),
602 "variably modified types in varargs");
603 }
604
605 return cgf.emitVAArg(ve);
606 }
607
608 mlir::Value VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *e) {
609 return Visit(e->getSemanticForm());
610 }
611
612 mlir::Value VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *e);
613 mlir::Value
614 VisitAbstractConditionalOperator(const AbstractConditionalOperator *e);
615
616 // Unary Operators.
617 mlir::Value VisitUnaryPrePostIncDec(const UnaryOperator *e) {
618 LValue lv = cgf.emitLValue(e->getSubExpr());
619 return emitScalarPrePostIncDec(e, lv);
620 }
621 mlir::Value VisitUnaryPostDec(const UnaryOperator *e) {
622 return VisitUnaryPrePostIncDec(e);
623 }
624 mlir::Value VisitUnaryPostInc(const UnaryOperator *e) {
625 return VisitUnaryPrePostIncDec(e);
626 }
627 mlir::Value VisitUnaryPreDec(const UnaryOperator *e) {
628 return VisitUnaryPrePostIncDec(e);
629 }
630 mlir::Value VisitUnaryPreInc(const UnaryOperator *e) {
631 return VisitUnaryPrePostIncDec(e);
632 }
633
634 mlir::Value emitFixedPointIncDec(const UnaryOperator *e, mlir::Value value,
635 QualType type);
636 mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv) {
638
639 QualType type = e->getSubExpr()->getType();
640
641 mlir::Value value;
642 mlir::Value input;
643
644 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
645 QualType valType = atomicTy->getValueType();
646 mlir::Location loc = cgf.getLoc(e->getSourceRange());
647 bool isInc = e->isIncrementOp();
648 bool isPre = e->isPrefix();
649
650 // Bools are always set-to-true, as decrement isn't legal on bools.
651 if (valType->isBooleanType()) {
652 assert(isInc);
653 // Atomic operations require an integer type; reinterpret the bool
654 // pointer as a pointer to its underlying storage integer type.
655 cir::IntType intTy = builder.getBoolMemoryTy();
656 mlir::Value one = builder.getConstInt(loc, intTy, 1);
657 Address intAddr = lv.getAddress().withElementType(builder, intTy);
658
659 if (isPre) {
660 // Pre-increment: atomically store true, return true.
661 cir::StoreOp store = builder.createStore(loc, one, intAddr);
662 store.setMemOrder(cir::MemOrder::SequentiallyConsistent);
663 if (lv.isVolatileQualified())
664 store.setIsVolatile(true);
665 return builder.getTrue(loc);
666 }
667 // Post-increment: atomically exchange with true, return old value.
668 auto xchg = cir::AtomicXchgOp::create(
669 builder, loc, intAddr.getPointer(), one,
670 cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
671 builder.getI64IntegerAttr(intAddr.getAlignment().getQuantity()),
672 lv.isVolatileQualified());
673 return builder.createCast(cir::CastKind::int_to_bool, xchg.getResult(),
674 builder.getBoolTy());
675 }
676
677 // Special case for atomic increment / decrement on integers, emit
678 // atomicrmw instructions. We skip this if we want to be doing overflow
679 // checking, and fall into the slow path with the atomic cmpxchg loop.
680 if (valType->isIntegerType() &&
681 !(valType->isUnsignedIntegerType() &&
682 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
683 cgf.getLangOpts().getSignedOverflowBehavior() !=
684 LangOptions::SOB_Trapping) {
685 mlir::Type intTy = cgf.convertType(valType);
686 mlir::Value one = builder.getConstInt(loc, intTy, 1);
687 cir::AtomicFetchKind kind =
688 isInc ? cir::AtomicFetchKind::Add : cir::AtomicFetchKind::Sub;
689 auto rmw = cir::AtomicFetchOp::create(
690 builder, loc, lv.getPointer(), one, kind,
691 cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
692 builder.getI64IntegerAttr(lv.getAlignment().getQuantity()),
693 lv.isVolatileQualified(), /*fetch_first=*/true);
694 mlir::Value oldVal = rmw->getResult(0);
695 // Prefix returns new value; postfix returns old value.
696 return isPre ? emitIntIncOrDec(e, oldVal) : oldVal;
697 }
698
699 // Special case for atomic increment/decrement on floats.
700 // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80).
701 if (valType->isFloatingType()) {
702 mlir::Type fpTy = cgf.convertType(valType);
703 auto fpType = mlir::cast<cir::FPTypeInterface>(fpTy);
704 // Bail on non-power-of-2 types (e.g., x86_fp80 is 80 bits).
705 if (llvm::has_single_bit(fpType.getWidth())) {
706 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
707 mlir::Value amt = builder.getConstFP(
708 loc, fpTy, llvm::APFloat(fpType.getFloatSemantics(), 1));
709 cir::AtomicFetchKind kind =
710 isInc ? cir::AtomicFetchKind::Add : cir::AtomicFetchKind::Sub;
711 auto rmw = cir::AtomicFetchOp::create(
712 builder, loc, lv.getPointer(), amt, kind,
713 cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
714 builder.getI64IntegerAttr(lv.getAlignment().getQuantity()),
715 lv.isVolatileQualified(), /*fetch_first=*/true);
716 mlir::Value oldVal = rmw->getResult(0);
717 if (isPre)
718 return isInc ? builder.createFAdd(loc, oldVal, amt)
719 : builder.createFSub(loc, oldVal, amt);
720 return oldVal;
721 } else {
722 cgf.cgm.errorNYI(e->getSourceRange(),
723 "Atomic inc/dec of non-power-of-2 float");
724 }
725 }
726
727 // Otherwise we need a loop on compare-exchange.
728 cgf.cgm.errorNYI(e->getSourceRange(), "Atomic inc/dec");
729 value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
730 input = value;
731 } else {
732 value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
733 input = value;
734 }
735
736 // NOTE: When possible, more frequent cases are handled first.
737
738 // Special case of integer increment that we have to check first: bool++.
739 // Due to promotion rules, we get:
740 // bool++ -> bool = bool + 1
741 // -> bool = (int)bool + 1
742 // -> bool = ((int)bool + 1 != 0)
743 // An interesting aspect of this is that increment is always true.
744 // Decrement does not have this property.
745 if (e->isIncrementOp() && type->isBooleanType()) {
746 value = builder.getTrue(cgf.getLoc(e->getExprLoc()));
747 } else if (type->isIntegerType()) {
748 QualType promotedType;
749 [[maybe_unused]] bool canPerformLossyDemotionCheck = false;
750 if (cgf.getContext().isPromotableIntegerType(type)) {
751 promotedType = cgf.getContext().getPromotedIntegerType(type);
752 assert(promotedType != type && "Shouldn't promote to the same type.");
753 canPerformLossyDemotionCheck = true;
754 canPerformLossyDemotionCheck &=
755 cgf.getContext().getCanonicalType(type) !=
756 cgf.getContext().getCanonicalType(promotedType);
757 canPerformLossyDemotionCheck &=
758 type->isIntegerType() && promotedType->isIntegerType();
759
760 // TODO(cir): Currently, we store bitwidths in CIR types only for
761 // integers. This might also be required for other types.
762
763 assert(
764 (!canPerformLossyDemotionCheck ||
765 type->isSignedIntegerOrEnumerationType() ||
766 promotedType->isSignedIntegerOrEnumerationType() ||
767 mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth() ==
768 mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth()) &&
769 "The following check expects that if we do promotion to different "
770 "underlying canonical type, at least one of the types (either "
771 "base or promoted) will be signed, or the bitwidths will match.");
772 }
773
775 if (e->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
776 value = emitIncDecConsiderOverflowBehavior(e, value);
777 } else {
778 // NOTE(CIR): clang calls CreateAdd but folds this to a unary op
779 value = emitIntIncOrDec(e, input, /*nsw=*/false);
780 }
781 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
782 QualType type = ptr->getPointeeType();
783 if (const VariableArrayType *vla =
784 cgf.getContext().getAsVariableArrayType(type)) {
785 mlir::Location loc = cgf.getLoc(e->getSourceRange());
786 mlir::Value numElts = cgf.getVLASize(vla).numElts;
787 if (!e->isIncrementOp())
788 numElts = cgf.getBuilder().createNeg(loc, numElts, /*nsw=*/true);
790 value = cgf.getBuilder().createPtrStride(loc, value, numElts);
791 } else {
792 // For everything else, we can just do a simple increment.
793 mlir::Location loc = cgf.getLoc(e->getSourceRange());
794 int amount = e->isIncrementOp() ? 1 : -1;
795 mlir::Value amt = builder.getSInt32(amount, loc);
797 value = builder.createPtrStride(loc, value, amt);
798 }
799 } else if (type->isVectorType()) {
800 if (type->hasIntegerRepresentation()) {
801 value = emitIntIncOrDec(e, input, /*nsw=*/false);
802 } else {
803 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
804 value = emitFloatIncOrDec(e, input);
805 }
806 } else if (type->isRealFloatingType()) {
807 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
808 value = emitFloatIncOrDec(e, input);
809 } else if (type->isFixedPointType()) {
810 value = emitFixedPointIncDec(e, value, type);
811 } else {
812 assert(type->castAs<ObjCObjectPointerType>());
813 cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec ObjectiveC pointer");
814 return {};
815 }
816
817 CIRGenFunction::SourceLocRAIIObject sourceloc{cgf, e->getSourceRange()};
818
819 // Store the updated result through the lvalue
820 if (lv.isBitField())
821 value = cgf.emitStoreThroughBitfieldLValue(RValue::get(value), lv);
822 else
823 cgf.emitStoreThroughLValue(RValue::get(value), lv);
824
825 // If this is a postinc, return the value read from memory, otherwise use
826 // the updated value.
827 return e->isPrefix() ? value : input;
828 }
829
830 mlir::Value emitIncDecConsiderOverflowBehavior(const UnaryOperator *e,
831 mlir::Value inVal) {
832 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
833 case LangOptions::SOB_Defined:
834 return emitIntIncOrDec(e, inVal, /*nsw=*/false);
835 case LangOptions::SOB_Undefined:
837 return emitIntIncOrDec(e, inVal, /*nsw=*/true);
838 case LangOptions::SOB_Trapping:
839 if (!e->canOverflow())
840 return emitIntIncOrDec(e, inVal, /*nsw=*/true);
841 cgf.cgm.errorNYI(e->getSourceRange(), "inc/def overflow SOB_Trapping");
842 return {};
843 }
844 llvm_unreachable("Unexpected signed overflow behavior kind");
845 }
846
847 mlir::Value VisitUnaryAddrOf(const UnaryOperator *e) {
848 if (llvm::isa<MemberPointerType>(e->getType()))
849 return cgf.cgm.emitMemberPointerConstant(e);
850
851 return cgf.emitLValue(e->getSubExpr()).getPointer();
852 }
853
854 mlir::Value VisitUnaryDeref(const UnaryOperator *e) {
855 if (e->getType()->isVoidType())
856 return Visit(e->getSubExpr()); // the actual value should be unused
857 return emitLoadOfLValue(e);
858 }
859
860 mlir::Value VisitUnaryPlus(const UnaryOperator *e) {
861 QualType promotionType = getPromotionType(e->getSubExpr()->getType());
862 mlir::Value result = VisitUnaryPlus(e, promotionType);
863 if (result && !promotionType.isNull())
864 return emitUnPromotedValue(result, e->getType());
865 return result;
866 }
867
868 mlir::Value VisitUnaryPlus(const UnaryOperator *e, QualType promotionType) {
869 ignoreResultAssign = false;
870 if (!promotionType.isNull())
871 return cgf.emitPromotedScalarExpr(e->getSubExpr(), promotionType);
872 return Visit(e->getSubExpr());
873 }
874
875 mlir::Value VisitUnaryMinus(const UnaryOperator *e) {
876 QualType promotionType = getPromotionType(e->getSubExpr()->getType());
877 mlir::Value result = VisitUnaryMinus(e, promotionType);
878 if (result && !promotionType.isNull())
879 return emitUnPromotedValue(result, e->getType());
880 return result;
881 }
882
883 mlir::Value VisitUnaryMinus(const UnaryOperator *e, QualType promotionType) {
884 ignoreResultAssign = false;
885 mlir::Value operand;
886 if (!promotionType.isNull())
887 operand = cgf.emitPromotedScalarExpr(e->getSubExpr(), promotionType);
888 else
889 operand = Visit(e->getSubExpr());
890
891 mlir::Location loc = cgf.getLoc(e->getSourceRange().getBegin());
892
893 if (cir::isFPOrVectorOfFPType(operand.getType())) {
894 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
895 return builder.createOrFold<cir::FNegOp>(loc, operand,
896 builder.getFastMathFlagsAttr());
897 }
898
899 // Saturated negation must saturate (-min for signed, any nonzero value for
900 // unsigned), as in classic codegen.
902 CIRGenFixedPointBuilder fpBuilder(builder, loc);
903 return fpBuilder.createNeg(
904 operand, cgf.getContext().getFixedPointSemantics(e->getType()));
905 }
906
907 // TODO(cir): We might have to change this to support overflow trapping.
908 // Classic codegen routes unary minus through emitSub to ensure
909 // that the overflow behavior is handled correctly.
910 bool nsw = e->getType()->isSignedIntegerType() &&
911 cgf.getLangOpts().getSignedOverflowBehavior() !=
912 LangOptions::SOB_Defined;
913
914 return builder.createOrFold<cir::MinusOp>(loc, operand, nsw);
915 }
916
917 mlir::Value emitIntIncOrDec(const UnaryOperator *e, mlir::Value input,
918 bool nsw = false) {
919 mlir::Location loc = cgf.getLoc(e->getSourceRange().getBegin());
920 return e->isIncrementOp()
921 ? builder.createOrFold<cir::IncOp>(loc, input, nsw)
922 : builder.createOrFold<cir::DecOp>(loc, input, nsw);
923 }
924
925 mlir::Value emitFloatIncOrDec(const UnaryOperator *e, mlir::Value input) {
926 assert(cir::isFPOrVectorOfFPType(input.getType()) &&
927 "Expect floating-point operand");
928 mlir::Location loc = cgf.getLoc(e->getSourceRange().getBegin());
929
930 if (auto vecType = mlir::dyn_cast<cir::VectorType>(input.getType())) {
931 mlir::Type fpScalarType = vecType.getElementType();
932 auto fpInterface = mlir::cast<cir::FPTypeInterface>(fpScalarType);
933 auto amount = llvm::APFloat::getOne(fpInterface.getFloatSemantics(),
934 /*Negative=*/e->isDecrementOp());
935 mlir::Value amtValue = builder.getConstFP(loc, fpScalarType, amount);
936 amtValue = cir::VecSplatOp::create(builder, loc, vecType, amtValue);
937 return builder.createFAdd(loc, input, amtValue);
938 }
939
940 QualType type = e->getSubExpr()->getType();
941 // Another special case: half FP increment should be done via float.
942 if (type->isHalfType() && !cgf.getContext().getLangOpts().NativeHalfType)
943 input = builder.createFloatingCast(input, builder.getSingleTy());
944
945 auto fpInterface = mlir::cast<cir::FPTypeInterface>(input.getType());
946 auto amount = llvm::APFloat::getOne(fpInterface.getFloatSemantics(),
947 /*Negative=*/e->isDecrementOp());
948 mlir::Value amtValue = builder.getConstFP(loc, input.getType(), amount);
949 mlir::Value output = builder.createFAdd(loc, input, amtValue);
950
951 if (type->isHalfType() && !cgf.getContext().getLangOpts().NativeHalfType)
952 output = builder.createFloatingCast(output, builder.getFp16Ty());
953
954 return output;
955 }
956
957 mlir::Value VisitUnaryNot(const UnaryOperator *e) {
958 ignoreResultAssign = false;
959 mlir::Value op = Visit(e->getSubExpr());
960 return builder.createOrFold<cir::NotOp>(
961 cgf.getLoc(e->getSourceRange().getBegin()), op);
962 }
963
964 mlir::Value VisitUnaryLNot(const UnaryOperator *e);
965
966 mlir::Value VisitUnaryReal(const UnaryOperator *e);
967 mlir::Value VisitUnaryImag(const UnaryOperator *e);
968 mlir::Value VisitRealImag(const UnaryOperator *e,
969 QualType promotionType = QualType());
970
971 mlir::Value VisitUnaryExtension(const UnaryOperator *e) {
972 return Visit(e->getSubExpr());
973 }
974
975 // C++
976 mlir::Value VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e) {
977 return emitLoadOfLValue(e);
978 }
979 mlir::Value VisitSourceLocExpr(SourceLocExpr *e) {
980 ASTContext &ctx = cgf.getContext();
981 APValue evaluated =
982 e->EvaluateInContext(ctx, cgf.curSourceLocExprScope.getDefaultExpr());
983 mlir::Attribute attribute = ConstantEmitter(cgf).emitAbstract(
984 e->getLocation(), evaluated, e->getType());
985 mlir::TypedAttr typedAttr = mlir::cast<mlir::TypedAttr>(attribute);
986 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
987 typedAttr);
988 }
989 mlir::Value VisitCXXDefaultArgExpr(CXXDefaultArgExpr *dae) {
990 CIRGenFunction::CXXDefaultArgExprScope scope(cgf, dae);
991 return Visit(dae->getExpr());
992 }
993 mlir::Value VisitCXXDefaultInitExpr(CXXDefaultInitExpr *die) {
994 CIRGenFunction::CXXDefaultInitExprScope scope(cgf, die);
995 return Visit(die->getExpr());
996 }
997
998 mlir::Value VisitCXXThisExpr(CXXThisExpr *te) { return cgf.loadCXXThis(); }
999
1000 mlir::Value VisitExprWithCleanups(ExprWithCleanups *e);
1001 mlir::Value VisitCXXNewExpr(const CXXNewExpr *e) {
1002 return cgf.emitCXXNewExpr(e);
1003 }
1004 mlir::Value VisitCXXDeleteExpr(const CXXDeleteExpr *e) {
1005 cgf.emitCXXDeleteExpr(e);
1006 return {};
1007 }
1008 mlir::Value VisitTypeTraitExpr(const TypeTraitExpr *e) {
1009 // We diverge slightly from classic codegen here because CIR has stricter
1010 // typing. In LLVM IR, constant folding covers up some potential type
1011 // mismatches such as bool-to-int conversions that would fail the verifier
1012 // in CIR. To make things work, we need to be sure we only emit a bool value
1013 // if the expression type is bool.
1014 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1015 if (e->isStoredAsBoolean()) {
1016 if (e->getType()->isBooleanType())
1017 return builder.getBool(e->getBoolValue(), loc);
1018 assert(e->getType()->isIntegerType() &&
1019 "Expected int type for TypeTraitExpr");
1020 return builder.getConstInt(loc, cgf.convertType(e->getType()),
1021 (uint64_t)e->getBoolValue());
1022 }
1023 assert(e->getType()->isIntegerType() && "not a scalar type trait");
1024 return builder.getConstInt(loc, e->getAPValue().getInt());
1025 }
1026 mlir::Value
1027 VisitConceptSpecializationExpr(const ConceptSpecializationExpr *e) {
1028 return builder.getBool(e->isSatisfied(), cgf.getLoc(e->getExprLoc()));
1029 }
1030 mlir::Value VisitRequiresExpr(const RequiresExpr *e) {
1031 return builder.getBool(e->isSatisfied(), cgf.getLoc(e->getExprLoc()));
1032 }
1033 mlir::Value VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *e) {
1034 mlir::Type type = cgf.convertType(e->getType());
1035 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1036 return builder.getConstInt(loc, type, e->getValue());
1037 }
1038 mlir::Value VisitExpressionTraitExpr(const ExpressionTraitExpr *e) {
1039 return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
1040 }
1041 mlir::Value VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *e) {
1042 cgf.cgm.errorNYI(e->getSourceRange(),
1043 "ScalarExprEmitter: cxx pseudo destructor");
1044 return {};
1045 }
1046 mlir::Value VisitCXXThrowExpr(const CXXThrowExpr *e) {
1047 cgf.emitCXXThrowExpr(e);
1048 return {};
1049 }
1050
1051 mlir::Value VisitCXXNoexceptExpr(CXXNoexceptExpr *e) {
1052 return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
1053 }
1054
1055 mlir::Value emitFixedPointConversion(mlir::Value src, QualType srcTy,
1056 QualType dstTy, mlir::Location loc);
1057
1058 /// Emit a conversion from the specified type to the specified destination
1059 /// type, both of which are CIR scalar types.
1060 /// TODO: do we need ScalarConversionOpts here? Should be done in another
1061 /// pass.
1062 mlir::Value
1063 emitScalarConversion(mlir::Value src, QualType srcType, QualType dstType,
1064 SourceLocation loc,
1065 ScalarConversionOpts opts = ScalarConversionOpts()) {
1066 // All conversions involving fixed point types should be handled by the
1067 // emitFixedPoint family functions. This is done to prevent bloating up
1068 // this function more, and although fixed point numbers are represented by
1069 // integers, we do not want to follow any logic that assumes they should be
1070 // treated as integers.
1071 if (srcType->isFixedPointType()) {
1072 if (dstType->isBooleanType()) {
1073 cir::BoolType boolTy = builder.getBoolTy();
1074 return cir::CastOp::create(builder, cgf.getLoc(loc), boolTy,
1075 cir::CastKind::int_to_bool, src);
1076 }
1077
1078 if (dstType->isFixedPointType() || dstType->isIntegerType() ||
1079 dstType->isRealFloatingType())
1080 return emitFixedPointConversion(src, srcType, dstType, cgf.getLoc(loc));
1081
1082 llvm_unreachable("Unhandled scalar conversion from a fixed point type to "
1083 "another type.");
1084 } else if (dstType->isFixedPointType()) {
1085 if (srcType->isIntegerType() || srcType->isRealFloatingType()) {
1086 // This also includes converting booleans and enums to fixed point
1087 // types.
1088 return emitFixedPointConversion(src, srcType, dstType, cgf.getLoc(loc));
1089 }
1090
1091 llvm_unreachable("Unhandled scalar conversion to a fixed point type from "
1092 "another type.");
1093 }
1094
1095 srcType = srcType.getCanonicalType();
1096 dstType = dstType.getCanonicalType();
1097 if (srcType == dstType) {
1098 if (opts.emitImplicitIntegerSignChangeChecks)
1099 cgf.getCIRGenModule().errorNYI(loc,
1100 "implicit integer sign change checks");
1101 return src;
1102 }
1103
1104 if (dstType->isVoidType())
1105 return {};
1106
1107 mlir::Type mlirSrcType = src.getType();
1108
1109 // Handle conversions to bool first, they are special: comparisons against
1110 // 0.
1111 if (dstType->isBooleanType())
1112 return emitConversionToBool(src, srcType, cgf.getLoc(loc));
1113
1114 mlir::Type mlirDstType = cgf.convertType(dstType);
1115
1116 if (srcType->isHalfType() &&
1117 !cgf.getContext().getLangOpts().NativeHalfType) {
1118 // Cast to FP using the intrinsic if the half type itself isn't supported.
1119 if (!mlir::isa<cir::FPTypeInterface>(mlirDstType)) {
1120 // Cast to other types through float, using FPExt, depending on whether
1121 // the half type itself is supported (as opposed to operations on half,
1122 // available with NativeHalfType).
1123 src = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, src,
1124 cgf.floatTy);
1125 srcType = cgf.getContext().FloatTy;
1126 mlirSrcType = cgf.floatTy;
1127 }
1128 }
1129
1130 // TODO(cir): LLVM codegen ignore conversions like int -> uint,
1131 // is there anything to be done for CIR here?
1132 if (mlirSrcType == mlirDstType) {
1133 if (opts.emitImplicitIntegerSignChangeChecks)
1134 cgf.getCIRGenModule().errorNYI(loc,
1135 "implicit integer sign change checks");
1136 return src;
1137 }
1138
1139 // Handle pointer conversions next: pointers can only be converted to/from
1140 // other pointers and integers. Check for pointer types in terms of LLVM, as
1141 // some native types (like Obj-C id) may map to a pointer type.
1142 if (auto dstPT = dyn_cast<cir::PointerType>(mlirDstType)) {
1143 cgf.getCIRGenModule().errorNYI(loc, "pointer casts");
1144 return builder.getNullPtr(dstPT, src.getLoc());
1145 }
1146
1147 if (isa<cir::PointerType>(mlirSrcType)) {
1148 // Must be an ptr to int cast.
1149 assert(isa<cir::IntType>(mlirDstType) && "not ptr->int?");
1150 return builder.createPtrToInt(src, mlirDstType);
1151 }
1152
1153 // A scalar can be splatted to an extended vector of the same element type
1154 if (dstType->isExtVectorType() && !srcType->isVectorType()) {
1155 // Sema should add casts to make sure that the source expression's type
1156 // is the same as the vector's element type (sans qualifiers)
1157 assert(dstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1158 srcType.getTypePtr() &&
1159 "Splatted expr doesn't match with vector element type?");
1160
1161 cgf.getCIRGenModule().errorNYI(loc, "vector splatting");
1162 return {};
1163 }
1164
1165 if (srcType->isMatrixType() && dstType->isMatrixType()) {
1166 return emitScalarCast(src, srcType, dstType, mlirSrcType, mlirDstType,
1167 opts);
1168 }
1169 assert(!srcType->isMatrixType() && !dstType->isMatrixType() &&
1170 "Internal error: conversion between matrix type and scalar type");
1171
1172 // Finally, we have the arithmetic types or vectors of arithmetic types.
1173 mlir::Value res = nullptr;
1174 mlir::Type resTy = mlirDstType;
1175
1176 res = emitScalarCast(src, srcType, dstType, mlirSrcType, mlirDstType, opts);
1177
1178 if (mlirDstType != resTy) {
1179 res = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, res,
1180 resTy);
1181 }
1182
1183 if (opts.emitImplicitIntegerTruncationChecks)
1184 cgf.getCIRGenModule().errorNYI(loc, "implicit integer truncation checks");
1185
1186 if (opts.emitImplicitIntegerSignChangeChecks)
1187 cgf.getCIRGenModule().errorNYI(loc,
1188 "implicit integer sign change checks");
1189
1190 return res;
1191 }
1192
1193 BinOpInfo emitBinOps(const BinaryOperator *e,
1194 QualType promotionType = QualType()) {
1195 ignoreResultAssign = false;
1196 BinOpInfo result;
1197 result.lhs = cgf.emitPromotedScalarExpr(e->getLHS(), promotionType);
1198 result.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionType);
1199 if (!promotionType.isNull())
1200 result.fullType = promotionType;
1201 else
1202 result.fullType = e->getType();
1203 result.compType = result.fullType;
1204 if (const auto *vecType = result.fullType->getAs<VectorType>())
1205 result.compType = vecType->getElementType();
1206 result.opcode = e->getOpcode();
1207 result.loc = e->getSourceRange();
1208 result.fpFeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
1209 result.e = e;
1210 return result;
1211 }
1212
1213 mlir::Value emitMul(const BinOpInfo &ops);
1214 mlir::Value emitDiv(const BinOpInfo &ops);
1215 mlir::Value emitRem(const BinOpInfo &ops);
1216 mlir::Value emitAdd(const BinOpInfo &ops);
1217 mlir::Value emitSub(const BinOpInfo &ops);
1218 mlir::Value emitShl(const BinOpInfo &ops);
1219 mlir::Value emitShr(const BinOpInfo &ops);
1220 mlir::Value emitAnd(const BinOpInfo &ops);
1221 mlir::Value emitXor(const BinOpInfo &ops);
1222 mlir::Value emitOr(const BinOpInfo &ops);
1223
1224 mlir::Value emitFixedPointBinOp(const BinOpInfo &ops);
1225
1226 LValue emitCompoundAssignLValue(
1227 const CompoundAssignOperator *e,
1228 mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &),
1229 mlir::Value &result);
1230 mlir::Value
1231 emitCompoundAssign(const CompoundAssignOperator *e,
1232 mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &));
1233
1234 // TODO(cir): Candidate to be in a common AST helper between CIR and LLVM
1235 // codegen.
1236 QualType getPromotionType(QualType ty) {
1237 const clang::ASTContext &ctx = cgf.getContext();
1238 if (auto *complexTy = ty->getAs<ComplexType>()) {
1239 QualType elementTy = complexTy->getElementType();
1240 if (elementTy.UseExcessPrecision(ctx))
1241 return ctx.getComplexType(ctx.FloatTy);
1242 }
1243
1244 if (ty.UseExcessPrecision(cgf.getContext())) {
1245 if (auto *vt = ty->getAs<VectorType>()) {
1246 unsigned numElements = vt->getNumElements();
1247 return ctx.getVectorType(ctx.FloatTy, numElements, vt->getVectorKind());
1248 }
1249 return cgf.getContext().FloatTy;
1250 }
1251
1252 return QualType();
1253 }
1254
1255// Binary operators and binary compound assignment operators.
1256#define HANDLEBINOP(OP) \
1257 mlir::Value VisitBin##OP(const BinaryOperator *e) { \
1258 QualType promotionTy = getPromotionType(e->getType()); \
1259 auto result = emit##OP(emitBinOps(e, promotionTy)); \
1260 if (result && !promotionTy.isNull()) \
1261 result = emitUnPromotedValue(result, e->getType()); \
1262 return result; \
1263 } \
1264 mlir::Value VisitBin##OP##Assign(const CompoundAssignOperator *e) { \
1265 return emitCompoundAssign(e, &ScalarExprEmitter::emit##OP); \
1266 }
1267
1268 HANDLEBINOP(Mul)
1269 HANDLEBINOP(Div)
1270 HANDLEBINOP(Rem)
1271 HANDLEBINOP(Add)
1272 HANDLEBINOP(Sub)
1273 HANDLEBINOP(Shl)
1274 HANDLEBINOP(Shr)
1276 HANDLEBINOP(Xor)
1278#undef HANDLEBINOP
1279
1280 cir::CmpOpKind clangCmpToCIRCmp(clang::BinaryOperatorKind clangCmp) {
1281 switch (clangCmp) {
1282 case BO_LT:
1283 return cir::CmpOpKind::lt;
1284 case BO_GT:
1285 return cir::CmpOpKind::gt;
1286 case BO_LE:
1287 return cir::CmpOpKind::le;
1288 case BO_GE:
1289 return cir::CmpOpKind::ge;
1290 case BO_EQ:
1291 return cir::CmpOpKind::eq;
1292 case BO_NE:
1293 return cir::CmpOpKind::ne;
1294 default:
1295 llvm_unreachable("unsupported comparison kind for cir.cmp");
1296 }
1297 }
1298 /// Returns <Signaling, Kind>.
1299 std::pair<bool, cir::FCmpOpKind>
1300 clangCmpToCIRFCmp(clang::BinaryOperatorKind clangCmp) {
1301 switch (clangCmp) {
1302 case BO_LT:
1303 return std::make_pair(/*Signaling=*/true, cir::FCmpOpKind::olt);
1304 case BO_GT:
1305 return std::make_pair(/*Signaling=*/true, cir::FCmpOpKind::ogt);
1306 case BO_LE:
1307 return std::make_pair(/*Signaling=*/true, cir::FCmpOpKind::ole);
1308 case BO_GE:
1309 return std::make_pair(/*Signaling=*/true, cir::FCmpOpKind::oge);
1310 case BO_EQ:
1311 return std::make_pair(/*Signaling=*/false, cir::FCmpOpKind::oeq);
1312 case BO_NE:
1313 return std::make_pair(/*Signaling=*/false, cir::FCmpOpKind::une);
1314 default:
1315 llvm_unreachable("unsupported comparison kind");
1316 }
1317 }
1318
1319 mlir::Value emitCmp(const BinaryOperator *e) {
1320 ignoreResultAssign = false;
1321 const mlir::Location loc = cgf.getLoc(e->getExprLoc());
1322 mlir::Value result;
1323 QualType lhsTy = e->getLHS()->getType();
1324 QualType rhsTy = e->getRHS()->getType();
1325
1326 cir::CmpOpKind kind = clangCmpToCIRCmp(e->getOpcode());
1327 if (lhsTy->getAs<MemberPointerType>()) {
1329 assert(e->getOpcode() == BO_EQ || e->getOpcode() == BO_NE);
1330 mlir::Value lhs = cgf.emitScalarExpr(e->getLHS());
1331 mlir::Value rhs = cgf.emitScalarExpr(e->getRHS());
1332 result = builder.createCompare(loc, kind, lhs, rhs);
1333 } else if (!lhsTy->isAnyComplexType() && !rhsTy->isAnyComplexType()) {
1334 BinOpInfo boInfo = emitBinOps(e);
1335 mlir::Value lhs = boInfo.lhs;
1336 mlir::Value rhs = boInfo.rhs;
1337
1338 if (lhsTy->isVectorType()) {
1339 if (!e->getType()->isVectorType()) {
1340 // If AltiVec, the comparison results in a numeric type, so we use
1341 // intrinsics comparing vectors and giving 0 or 1 as a result
1342 cgf.cgm.errorNYI(loc, "AltiVec comparison");
1343 } else {
1344 // Other kinds of vectors. Element-wise comparison returning
1345 // a vector.
1346 auto resultTy =
1347 mlir::cast<cir::VectorType>(cgf.convertType(boInfo.fullType));
1348 if (cir::isFPOrVectorOfFPType(lhs.getType())) {
1349 std::pair<bool, cir::FCmpOpKind> fpInfo =
1350 clangCmpToCIRFCmp(e->getOpcode());
1351 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
1352 result = builder.createVecFCompare(cgf.getLoc(boInfo.loc), resultTy,
1353 fpInfo.second, lhs, rhs,
1354 fpInfo.first);
1355 } else {
1356 result = builder.createVecCompare(cgf.getLoc(boInfo.loc), resultTy,
1357 kind, lhs, rhs);
1358 }
1359 }
1360 } else if (boInfo.isFixedPointOp()) {
1361 result = emitFixedPointBinOp(boInfo);
1362 } else {
1363 // integers and pointers
1364 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers &&
1365 mlir::isa<cir::PointerType>(lhs.getType()) &&
1366 mlir::isa<cir::PointerType>(rhs.getType())) {
1367 cgf.cgm.errorNYI(loc, "strict vtable pointer comparisons");
1368 }
1369 result = builder.createCompare(loc, kind, lhs, rhs);
1370 }
1371 } else {
1372 assert((e->getOpcode() == BO_EQ || e->getOpcode() == BO_NE) &&
1373 "Complex Comparison: can only be an equality comparison");
1374
1375 mlir::Value lhs;
1376 if (lhsTy->isAnyComplexType()) {
1377 lhs = cgf.emitComplexExpr(e->getLHS());
1378 } else {
1379 mlir::Value lhsReal = Visit(e->getLHS());
1380 mlir::Value lhsImag = builder.getNullValue(convertType(lhsTy), loc);
1381 lhs = builder.createComplexCreate(loc, lhsReal, lhsImag);
1382 }
1383
1384 mlir::Value rhs;
1385 if (rhsTy->isAnyComplexType()) {
1386 rhs = cgf.emitComplexExpr(e->getRHS());
1387 } else {
1388 mlir::Value rhsReal = Visit(e->getRHS());
1389 mlir::Value rhsImag = builder.getNullValue(convertType(rhsTy), loc);
1390 rhs = builder.createComplexCreate(loc, rhsReal, rhsImag);
1391 }
1392
1393 result = builder.createCompare(loc, kind, lhs, rhs);
1394 }
1395
1396 return emitScalarConversion(result, cgf.getContext().BoolTy, e->getType(),
1397 e->getExprLoc());
1398 }
1399
1400// Comparisons.
1401#define VISITCOMP(CODE) \
1402 mlir::Value VisitBin##CODE(const BinaryOperator *E) { return emitCmp(E); }
1403 VISITCOMP(LT)
1404 VISITCOMP(GT)
1405 VISITCOMP(LE)
1406 VISITCOMP(GE)
1407 VISITCOMP(EQ)
1408 VISITCOMP(NE)
1409#undef VISITCOMP
1410
1411 mlir::Value VisitBinAssign(const BinaryOperator *e) {
1412 const bool ignore = std::exchange(ignoreResultAssign, false);
1413
1414 mlir::Value rhs;
1415 LValue lhs;
1416
1417 switch (e->getLHS()->getType().getObjCLifetime()) {
1423 break;
1425 // __block variables need to have the rhs evaluated first, plus this
1426 // should improve codegen just a little.
1427 rhs = Visit(e->getRHS());
1429 // TODO(cir): This needs to be emitCheckedLValue() once we support
1430 // sanitizers
1431 lhs = cgf.emitLValue(e->getLHS());
1432
1433 // Store the value into the LHS. Bit-fields are handled specially because
1434 // the result is altered by the store, i.e., [C99 6.5.16p1]
1435 // 'An assignment expression has the value of the left operand after the
1436 // assignment...'.
1437 if (lhs.isBitField()) {
1439 rhs = cgf.emitStoreThroughBitfieldLValue(RValue::get(rhs), lhs);
1440 } else {
1441 cgf.emitNullabilityCheck(lhs, rhs, e->getExprLoc());
1443 cgf.emitStoreThroughLValue(RValue::get(rhs), lhs);
1444 }
1445 }
1446
1447 // If the result is clearly ignored, return now.
1448 if (ignore)
1449 return nullptr;
1450
1451 // The result of an assignment in C is the assigned r-value.
1452 if (!cgf.getLangOpts().CPlusPlus)
1453 return rhs;
1454
1455 // If the lvalue is non-volatile, return the computed value of the
1456 // assignment.
1457 if (!lhs.isVolatile())
1458 return rhs;
1459
1460 // Otherwise, reload the value.
1461 return emitLoadOfLValue(lhs, e->getExprLoc());
1462 }
1463
1464 mlir::Value VisitBinComma(const BinaryOperator *e) {
1465 cgf.emitIgnoredExpr(e->getLHS());
1466 // NOTE: We don't need to EnsureInsertPoint() like LLVM codegen.
1467 return Visit(e->getRHS());
1468 }
1469
1470 mlir::Value VisitBinLAnd(const clang::BinaryOperator *e) {
1471 if (e->getType()->isVectorType()) {
1472 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1473 mlir::Type lhsTy = cgf.convertType(e->getLHS()->getType());
1474 mlir::Value zeroVec = builder.getNullValue(lhsTy, loc);
1475
1476 mlir::Value lhs = Visit(e->getLHS());
1477 mlir::Value rhs = Visit(e->getRHS());
1478
1479 auto resultTy =
1480 mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
1481 if (cir::isFPOrVectorOfFPType(lhs.getType())) {
1482 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
1483 auto cmpOpKind = cir::FCmpOpKind::une;
1484 lhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1485 rhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1486 } else {
1487 auto cmpOpKind = cir::CmpOpKind::ne;
1488 lhs = builder.createVecCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1489 rhs = builder.createVecCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1490 }
1491 return builder.createAnd(loc, lhs, rhs);
1492 }
1493
1495 mlir::Type resTy = cgf.convertType(e->getType());
1496 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1497
1498 mlir::Value lhsCondV = cgf.evaluateExprAsBool(e->getLHS());
1499
1500 CIRGenFunction::ConditionalEvaluation eval(cgf, loc);
1501
1502 auto resOp = cir::TernaryOp::create(
1503 builder, loc, lhsCondV, /*trueBuilder=*/
1504 [&](mlir::OpBuilder &b, mlir::Location loc) {
1505 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1506 b.getInsertionBlock()};
1507 cgf.curLexScope->setAsTernary();
1508 eval.beginEvaluation();
1509 mlir::Value res = cgf.evaluateExprAsBool(e->getRHS());
1510 eval.endEvaluation();
1511 lexScope.forceCleanup({&res});
1512 cir::YieldOp::create(b, loc, res);
1513 },
1514 /*falseBuilder*/
1515 [&](mlir::OpBuilder &b, mlir::Location loc) {
1516 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1517 b.getInsertionBlock()};
1518 cgf.curLexScope->setAsTernary();
1519 auto res = cir::ConstantOp::create(b, loc, builder.getFalseAttr());
1520 cir::YieldOp::create(b, loc, res.getRes());
1521 });
1522 return maybePromoteBoolResult(resOp.getResult(), resTy);
1523 }
1524
1525 mlir::Value VisitBinLOr(const clang::BinaryOperator *e) {
1526 if (e->getType()->isVectorType()) {
1527 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1528 mlir::Type lhsTy = cgf.convertType(e->getLHS()->getType());
1529 mlir::Value zeroVec = builder.getNullValue(lhsTy, loc);
1530
1531 mlir::Value lhs = Visit(e->getLHS());
1532 mlir::Value rhs = Visit(e->getRHS());
1533
1534 auto resultTy =
1535 mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
1536 if (cir::isFPOrVectorOfFPType(lhs.getType())) {
1537 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
1538 auto cmpOpKind = cir::FCmpOpKind::une;
1539 lhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1540 rhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1541 } else {
1542 auto cmpOpKind = cir::CmpOpKind::ne;
1543 lhs = builder.createVecCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1544 rhs = builder.createVecCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1545 }
1546 return builder.createOr(loc, lhs, rhs);
1547 }
1548
1550 mlir::Type resTy = cgf.convertType(e->getType());
1551 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1552
1553 mlir::Value lhsCondV = cgf.evaluateExprAsBool(e->getLHS());
1554
1555 CIRGenFunction::ConditionalEvaluation eval(cgf, loc);
1556
1557 auto resOp = cir::TernaryOp::create(
1558 builder, loc, lhsCondV, /*trueBuilder=*/
1559 [&](mlir::OpBuilder &b, mlir::Location loc) {
1560 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1561 b.getInsertionBlock()};
1562 cgf.curLexScope->setAsTernary();
1563 auto res = cir::ConstantOp::create(b, loc, builder.getTrueAttr());
1564 cir::YieldOp::create(b, loc, res.getRes());
1565 },
1566 /*falseBuilder*/
1567 [&](mlir::OpBuilder &b, mlir::Location loc) {
1568 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1569 b.getInsertionBlock()};
1570 cgf.curLexScope->setAsTernary();
1571 eval.beginEvaluation();
1572 mlir::Value res = cgf.evaluateExprAsBool(e->getRHS());
1573 eval.endEvaluation();
1574 lexScope.forceCleanup({&res});
1575 cir::YieldOp::create(b, loc, res);
1576 });
1577
1578 return maybePromoteBoolResult(resOp.getResult(), resTy);
1579 }
1580
1581 mlir::Value VisitBinPtrMemD(const BinaryOperator *e) {
1582 return emitLoadOfLValue(e);
1583 }
1584
1585 mlir::Value VisitBinPtrMemI(const BinaryOperator *e) {
1586 return emitLoadOfLValue(e);
1587 }
1588
1589 // Other Operators.
1590 mlir::Value VisitBlockExpr(const BlockExpr *e) {
1591 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: block");
1592 return {};
1593 }
1594
1595 mlir::Value VisitChooseExpr(ChooseExpr *e) {
1596 return Visit(e->getChosenSubExpr());
1597 }
1598
1599 mlir::Value VisitObjCStringLiteral(const ObjCStringLiteral *e) {
1600 cgf.cgm.errorNYI(e->getSourceRange(),
1601 "ScalarExprEmitter: objc string literal");
1602 return {};
1603 }
1604 mlir::Value VisitObjCBoxedExpr(ObjCBoxedExpr *e) {
1605 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc boxed");
1606 return {};
1607 }
1608 mlir::Value VisitObjCArrayLiteral(ObjCArrayLiteral *e) {
1609 cgf.cgm.errorNYI(e->getSourceRange(),
1610 "ScalarExprEmitter: objc array literal");
1611 return {};
1612 }
1613 mlir::Value VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *e) {
1614 cgf.cgm.errorNYI(e->getSourceRange(),
1615 "ScalarExprEmitter: objc dictionary literal");
1616 return {};
1617 }
1618
1619 mlir::Value convertVec3AndVec4(CIRGenBuilderTy &builder, mlir::Location loc,
1620 mlir::Value src, unsigned numElementsDst) {
1621 static constexpr int64_t mask[] = {0, 1, 2, -1};
1622 return builder.createVecShuffle(
1623 loc, src, llvm::ArrayRef<int64_t>(mask, numElementsDst));
1624 }
1625
1626 // Create cast instructions for converting MLIR value \p Src to MLIR type \p
1627 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
1628 // but could be scalar or vectors of different lengths, and either can be
1629 // pointer.
1630 //
1631 // There are 4 cases:
1632 // 1. non-pointer -> non-pointer : needs 1 bitcast
1633 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
1634 // 3. pointer -> non-pointer
1635 // a) pointer -> intptr_t : needs 1 ptrtoint
1636 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
1637 // 4. non-pointer -> pointer
1638 // a) intptr_t -> pointer : needs 1 inttoptr
1639 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
1640 //
1641 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
1642 // allow casting directly between pointer types and non-integer non-pointer
1643 // types.
1644 mlir::Value createCastsForTypeOfSameSize(mlir::Value src, mlir::Type dstTy) {
1645 mlir::Type srcTy = src.getType();
1646
1647 // Case 1.
1648 if (!isa<cir::PointerType>(srcTy) && !isa<cir::PointerType>(dstTy))
1649 return builder.createBitcast(src, dstTy);
1650
1651 // Case 2.
1652 if (isa<cir::PointerType>(srcTy) && isa<cir::PointerType>(dstTy)) {
1653 cgf.cgm.errorNYI(
1654 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 2");
1655 return {};
1656 }
1657
1658 // Case 3.
1659 if (isa<cir::PointerType>(srcTy) && !isa<cir::PointerType>(dstTy)) {
1660 if (!isa<cir::IntType>(dstTy)) {
1661 cgf.cgm.errorNYI(
1662 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 3a");
1663 }
1664
1665 cgf.cgm.errorNYI(
1666 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 3a and 3b");
1667 return {};
1668 }
1669
1670 // Case 4b.
1671 if (!isa<cir::IntType>(srcTy)) {
1672 cgf.cgm.errorNYI(
1673 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 4a");
1674 return {};
1675 }
1676 // Cases 4a and 4b.
1677 return builder.createIntToPtr(src, dstTy);
1678 }
1679
1680 mlir::Value VisitAsTypeExpr(AsTypeExpr *e) {
1681 mlir::Value src = cgf.emitScalarExpr(e->getSrcExpr());
1682 mlir::Type srcTy = src.getType();
1683 mlir::Type dstTy = cgf.convertType(e->getType());
1684
1685 unsigned numElementsSrc = isa<cir::VectorType>(srcTy)
1686 ? cast<cir::VectorType>(srcTy).getFixedSize()
1687 : 0;
1688 unsigned numElementsDst = isa<cir::VectorType>(dstTy)
1689 ? cast<cir::VectorType>(dstTy).getFixedSize()
1690 : 0;
1691
1692 // Use bit vector expansion for ext_vector_type boolean vectors.
1693 if (e->getType()->isExtVectorBoolType()) {
1694 cgf.cgm.errorNYI(e->getSourceRange(),
1695 "ScalarExprEmitter: VisitAsTypeExpr ExtVectorBoolType");
1696 return {};
1697 }
1698
1699 // Going from vec3 to non-vec3 is a special case and requires a shuffle
1700 // vector to get a vec4, then a bitcast if the target type is different.
1701 if (numElementsSrc == 3 && numElementsDst != 3) {
1702 cgf.cgm.errorNYI(e->getSourceRange(),
1703 "ScalarExprEmitter: VisitAsTypeExpr numElemsSrc = 3, "
1704 "numElemsDst != 3");
1705 return {};
1706 }
1707
1708 // Going from non-vec3 to vec3 is a special case and requires a bitcast
1709 // to vec4 if the original type is not vec4, then a shuffle vector to
1710 // get a vec3.
1711 if (numElementsSrc != 3 && numElementsDst == 3) {
1712 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1713 auto dstElemTy = cast<cir::VectorType>(dstTy).getElementType();
1714 auto dstVec4Ty = cir::VectorType::getFixed(dstElemTy, 4);
1715 src = createCastsForTypeOfSameSize(src, dstVec4Ty);
1716 src = convertVec3AndVec4(builder, loc, src, 3);
1717 return src;
1718 }
1719
1720 return createCastsForTypeOfSameSize(src, dstTy);
1721 }
1722
1723 mlir::Value VisitAtomicExpr(AtomicExpr *e) {
1724 return cgf.emitAtomicExpr(e).getValue();
1725 }
1726};
1727
1728LValue ScalarExprEmitter::emitCompoundAssignLValue(
1729 const CompoundAssignOperator *e,
1730 mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &),
1731 mlir::Value &result) {
1733 return cgf.emitScalarCompoundAssignWithComplex(e, result);
1734
1735 QualType lhsTy = e->getLHS()->getType();
1736 BinOpInfo opInfo;
1737
1738 // Emit the RHS first. __block variables need to have the rhs evaluated
1739 // first, plus this should improve codegen a little.
1740
1741 QualType promotionTypeCR = getPromotionType(e->getComputationResultType());
1742 if (promotionTypeCR.isNull())
1743 promotionTypeCR = e->getComputationResultType();
1744
1745 QualType promotionTypeLHS = getPromotionType(e->getComputationLHSType());
1746 QualType promotionTypeRHS = getPromotionType(e->getRHS()->getType());
1747
1748 if (!promotionTypeRHS.isNull())
1749 opInfo.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionTypeRHS);
1750 else
1751 opInfo.rhs = Visit(e->getRHS());
1752
1753 opInfo.fullType = promotionTypeCR;
1754 opInfo.compType = opInfo.fullType;
1755 if (const auto *vecType = opInfo.fullType->getAs<VectorType>())
1756 opInfo.compType = vecType->getElementType();
1757 opInfo.opcode = e->getOpcode();
1758 opInfo.fpFeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
1759 opInfo.e = e;
1760 opInfo.loc = e->getSourceRange();
1761
1762 // Load/convert the LHS
1763 LValue lhsLV = cgf.emitLValue(e->getLHS());
1764
1765 if (lhsTy->getAs<AtomicType>()) {
1766 cgf.cgm.errorNYI(result.getLoc(), "atomic lvalue assign");
1767 return LValue();
1768 }
1769
1770 opInfo.lhs = emitLoadOfLValue(lhsLV, e->getExprLoc());
1771
1772 CIRGenFunction::SourceLocRAIIObject sourceloc{cgf, e->getSourceRange()};
1773 SourceLocation loc = e->getExprLoc();
1774 if (!promotionTypeLHS.isNull())
1775 opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS, loc);
1776 else
1777 opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy,
1778 e->getComputationLHSType(), loc);
1779
1780 // Expand the binary operator.
1781 result = (this->*func)(opInfo);
1782
1783 // Convert the result back to the LHS type,
1784 // potentially with Implicit Conversion sanitizer check.
1785 result = emitScalarConversion(result, promotionTypeCR, lhsTy, loc,
1786 ScalarConversionOpts(cgf.sanOpts));
1787
1788 // Store the result value into the LHS lvalue. Bit-fields are handled
1789 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1790 // 'An assignment expression has the value of the left operand after the
1791 // assignment...'.
1792 if (lhsLV.isBitField())
1793 result = cgf.emitStoreThroughBitfieldLValue(RValue::get(result), lhsLV);
1794 else
1795 cgf.emitStoreThroughLValue(RValue::get(result), lhsLV);
1796
1798
1799 return lhsLV;
1800}
1801
1802mlir::Value ScalarExprEmitter::emitComplexToScalarConversion(mlir::Location lov,
1803 mlir::Value value,
1804 CastKind kind,
1805 QualType destTy) {
1806 cir::CastKind castOpKind;
1807 switch (kind) {
1808 case CK_FloatingComplexToReal:
1809 castOpKind = cir::CastKind::float_complex_to_real;
1810 break;
1811 case CK_IntegralComplexToReal:
1812 castOpKind = cir::CastKind::int_complex_to_real;
1813 break;
1814 case CK_FloatingComplexToBoolean:
1815 castOpKind = cir::CastKind::float_complex_to_bool;
1816 break;
1817 case CK_IntegralComplexToBoolean:
1818 castOpKind = cir::CastKind::int_complex_to_bool;
1819 break;
1820 default:
1821 llvm_unreachable("invalid complex-to-scalar cast kind");
1822 }
1823
1824 return builder.createCast(lov, castOpKind, value, cgf.convertType(destTy));
1825}
1826
1827mlir::Value ScalarExprEmitter::emitPromoted(const Expr *e,
1828 QualType promotionType) {
1829 e = e->IgnoreParens();
1830 if (const auto *bo = dyn_cast<BinaryOperator>(e)) {
1831 switch (bo->getOpcode()) {
1832#define HANDLE_BINOP(OP) \
1833 case BO_##OP: \
1834 return emit##OP(emitBinOps(bo, promotionType));
1835 HANDLE_BINOP(Add)
1836 HANDLE_BINOP(Sub)
1837 HANDLE_BINOP(Mul)
1838 HANDLE_BINOP(Div)
1839#undef HANDLE_BINOP
1840 default:
1841 break;
1842 }
1843 } else if (const auto *uo = dyn_cast<UnaryOperator>(e)) {
1844 switch (uo->getOpcode()) {
1845 case UO_Imag:
1846 case UO_Real:
1847 return VisitRealImag(uo, promotionType);
1848 case UO_Minus:
1849 return VisitUnaryMinus(uo, promotionType);
1850 case UO_Plus:
1851 return VisitUnaryPlus(uo, promotionType);
1852 default:
1853 break;
1854 }
1855 }
1856 mlir::Value result = Visit(const_cast<Expr *>(e));
1857 if (result) {
1858 if (!promotionType.isNull())
1859 return emitPromotedValue(result, promotionType);
1860 return emitUnPromotedValue(result, e->getType());
1861 }
1862 return result;
1863}
1864
1865mlir::Value ScalarExprEmitter::emitCompoundAssign(
1866 const CompoundAssignOperator *e,
1867 mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &)) {
1868
1869 bool ignore = std::exchange(ignoreResultAssign, false);
1870 mlir::Value rhs;
1871 LValue lhs = emitCompoundAssignLValue(e, func, rhs);
1872
1873 // If the result is clearly ignored, return now.
1874 if (ignore)
1875 return {};
1876
1877 // The result of an assignment in C is the assigned r-value.
1878 if (!cgf.getLangOpts().CPlusPlus)
1879 return rhs;
1880
1881 // If the lvalue is non-volatile, return the computed value of the assignment.
1882 if (!lhs.isVolatile())
1883 return rhs;
1884
1885 // Otherwise, reload the value.
1886 return emitLoadOfLValue(lhs, e->getExprLoc());
1887}
1888
1889mlir::Value
1890ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *e) {
1891 ASTContext &context = cgf.getContext();
1892 mlir::Location loc = cgf.getLoc(e->getSourceRange());
1893 cir::GlobalOp globalConstStr =
1894 cgf.cgm.createGlobalString(loc, e->ComputeName(context), "__usn_str");
1895
1896 // Unlike LLVM IR, CIR pointers are typed, so the bitcast and the address
1897 // space cast are emitted as separate operations when both are needed.
1898 mlir::Value addr = builder.createGetGlobal(loc, globalConstStr);
1899 auto exprTy = mlir::cast<cir::PointerType>(convertType(e->getType()));
1900 auto addrTy = mlir::cast<cir::PointerType>(addr.getType());
1901 if (addrTy.getAddrSpace() != exprTy.getAddrSpace())
1902 addr = cgf.performAddrSpaceCast(
1903 addr, builder.getPointerTo(addrTy.getPointee(), exprTy.getAddrSpace()));
1904 return builder.createBitcast(loc, addr, exprTy);
1905}
1906
1907mlir::Value ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *e) {
1908 CIRGenFunction::FullExprCleanupScope scope(cgf, e->getSubExpr());
1909 mlir::Value v = Visit(e->getSubExpr());
1910 // Defend against dominance problems caused by jumps out of expression
1911 // evaluation through the shared cleanup block.
1912 scope.exit({&v});
1913 return v;
1914}
1915
1916} // namespace
1917
1918LValue
1920 ScalarExprEmitter emitter(*this, builder);
1921 mlir::Value result;
1922 switch (e->getOpcode()) {
1923#define COMPOUND_OP(Op) \
1924 case BO_##Op##Assign: \
1925 return emitter.emitCompoundAssignLValue(e, &ScalarExprEmitter::emit##Op, \
1926 result)
1927 COMPOUND_OP(Mul);
1928 COMPOUND_OP(Div);
1929 COMPOUND_OP(Rem);
1930 COMPOUND_OP(Add);
1931 COMPOUND_OP(Sub);
1932 COMPOUND_OP(Shl);
1933 COMPOUND_OP(Shr);
1935 COMPOUND_OP(Xor);
1936 COMPOUND_OP(Or);
1937#undef COMPOUND_OP
1938
1939 case BO_PtrMemD:
1940 case BO_PtrMemI:
1941 case BO_Mul:
1942 case BO_Div:
1943 case BO_Rem:
1944 case BO_Add:
1945 case BO_Sub:
1946 case BO_Shl:
1947 case BO_Shr:
1948 case BO_LT:
1949 case BO_GT:
1950 case BO_LE:
1951 case BO_GE:
1952 case BO_EQ:
1953 case BO_NE:
1954 case BO_Cmp:
1955 case BO_And:
1956 case BO_Xor:
1957 case BO_Or:
1958 case BO_LAnd:
1959 case BO_LOr:
1960 case BO_Assign:
1961 case BO_Comma:
1962 llvm_unreachable("Not valid compound assignment operators");
1963 }
1964 llvm_unreachable("Unhandled compound assignment operator");
1965}
1966
1967/// Emit the computation of the specified expression of scalar type.
1969 bool ignoreResultAssign) {
1970 assert(e && hasScalarEvaluationKind(e->getType()) &&
1971 "Invalid scalar expression to emit");
1972
1973 return ScalarExprEmitter(*this, builder, ignoreResultAssign)
1974 .Visit(const_cast<Expr *>(e));
1975}
1976
1978 QualType promotionType) {
1979 if (!promotionType.isNull())
1980 return ScalarExprEmitter(*this, builder).emitPromoted(e, promotionType);
1981 return ScalarExprEmitter(*this, builder).Visit(const_cast<Expr *>(e));
1982}
1983
1984[[maybe_unused]] static bool mustVisitNullValue(const Expr *e) {
1985 // If a null pointer expression's type is the C++0x nullptr_t and
1986 // the expression is not a simple literal, it must be evaluated
1987 // for its potential side effects.
1989 return false;
1990 return e->getType()->isNullPtrType();
1991}
1992
1993/// If \p e is a widened promoted integer, get its base (unpromoted) type.
1994static std::optional<QualType>
1995getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
1996 const Expr *base = e->IgnoreImpCasts();
1997 if (e == base)
1998 return std::nullopt;
1999
2000 QualType baseTy = base->getType();
2001 if (!astContext.isPromotableIntegerType(baseTy) ||
2002 astContext.getTypeSize(baseTy) >= astContext.getTypeSize(e->getType()))
2003 return std::nullopt;
2004
2005 return baseTy;
2006}
2007
2008/// Check if \p e is a widened promoted integer.
2009[[maybe_unused]] static bool isWidenedIntegerOp(const ASTContext &astContext,
2010 const Expr *e) {
2011 return getUnwidenedIntegerType(astContext, e).has_value();
2012}
2013
2014/// Check if we can skip the overflow check for \p Op.
2015[[maybe_unused]] static bool canElideOverflowCheck(const ASTContext &astContext,
2016 const BinOpInfo &op) {
2017 assert((isa<UnaryOperator>(op.e) || isa<BinaryOperator>(op.e)) &&
2018 "Expected a unary or binary operator");
2019
2020 // If the binop has constant inputs and we can prove there is no overflow,
2021 // we can elide the overflow check.
2022 if (!op.mayHaveIntegerOverflow())
2023 return true;
2024
2025 // If a unary op has a widened operand, the op cannot overflow.
2026 if (const auto *uo = dyn_cast<UnaryOperator>(op.e))
2027 return !uo->canOverflow();
2028
2029 // We usually don't need overflow checks for binops with widened operands.
2030 // Multiplication with promoted unsigned operands is a special case.
2031 const auto *bo = cast<BinaryOperator>(op.e);
2032 std::optional<QualType> optionalLHSTy =
2033 getUnwidenedIntegerType(astContext, bo->getLHS());
2034 if (!optionalLHSTy)
2035 return false;
2036
2037 std::optional<QualType> optionalRHSTy =
2038 getUnwidenedIntegerType(astContext, bo->getRHS());
2039 if (!optionalRHSTy)
2040 return false;
2041
2042 QualType lhsTy = *optionalLHSTy;
2043 QualType rhsTy = *optionalRHSTy;
2044
2045 // This is the simple case: binops without unsigned multiplication, and with
2046 // widened operands. No overflow check is needed here.
2047 if ((op.opcode != BO_Mul && op.opcode != BO_MulAssign) ||
2048 !lhsTy->isUnsignedIntegerType() || !rhsTy->isUnsignedIntegerType())
2049 return true;
2050
2051 // For unsigned multiplication the overflow check can be elided if either one
2052 // of the unpromoted types are less than half the size of the promoted type.
2053 unsigned promotedSize = astContext.getTypeSize(op.e->getType());
2054 return (2 * astContext.getTypeSize(lhsTy)) < promotedSize ||
2055 (2 * astContext.getTypeSize(rhsTy)) < promotedSize;
2056}
2057
2058/// Emit pointer + index arithmetic.
2060 const BinOpInfo &op,
2061 bool isSubtraction) {
2062 // Must have binary (not unary) expr here. Unary pointer
2063 // increment/decrement doesn't use this path.
2065
2066 mlir::Value pointer = op.lhs;
2067 Expr *pointerOperand = expr->getLHS();
2068 mlir::Value index = op.rhs;
2069 Expr *indexOperand = expr->getRHS();
2070
2071 // In the case of subtraction, the FE has ensured that the LHS is always the
2072 // pointer. However, addition can have the pointer on either side. We will
2073 // always have a pointer operand and an integer operand, so if the LHS wasn't
2074 // a pointer, we need to swap our values.
2075 if (!isSubtraction && !mlir::isa<cir::PointerType>(pointer.getType())) {
2076 std::swap(pointer, index);
2077 std::swap(pointerOperand, indexOperand);
2078 }
2079 assert(mlir::isa<cir::PointerType>(pointer.getType()) &&
2080 "Need a pointer operand");
2081 assert(mlir::isa<cir::IntType>(index.getType()) && "Need an integer operand");
2082
2083 // Some versions of glibc and gcc use idioms (particularly in their malloc
2084 // routines) that add a pointer-sized integer (known to be a pointer value)
2085 // to a null pointer in order to cast the value back to an integer or as
2086 // part of a pointer alignment algorithm. This is undefined behavior, but
2087 // we'd like to be able to compile programs that use it.
2088 //
2089 // Normally, we'd generate a GEP with a null-pointer base here in response
2090 // to that code, but it's also UB to dereference a pointer created that
2091 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
2092 // generate a direct cast of the integer value to a pointer.
2093 //
2094 // The idiom (p = nullptr + N) is not met if any of the following are true:
2095 //
2096 // The operation is subtraction.
2097 // The index is not pointer-sized.
2098 // The pointer type is not byte-sized.
2099 //
2101 cgf.getContext(), op.opcode, expr->getLHS(), expr->getRHS()))
2102 return cgf.getBuilder().createIntToPtr(index, pointer.getType());
2103
2104 // Differently from LLVM codegen, ABI bits for index sizes is handled during
2105 // LLVM lowering.
2106
2107 // If this is subtraction, negate the index.
2108 if (isSubtraction)
2109 index = cgf.getBuilder().createNeg(cgf.getLoc(op.e->getExprLoc()), index);
2110
2112
2113 const PointerType *pointerType =
2114 pointerOperand->getType()->getAs<PointerType>();
2115 if (!pointerType) {
2116 cgf.cgm.errorNYI("Objective-C:pointer arithmetic with non-pointer type");
2117 return nullptr;
2118 }
2119
2120 QualType elementType = pointerType->getPointeeType();
2121 if (const VariableArrayType *vla =
2122 cgf.getContext().getAsVariableArrayType(elementType)) {
2123 mlir::Value numElements = cgf.getVLASize(vla).numElts;
2124 mlir::Location loc = cgf.getLoc(op.e->getExprLoc());
2125 index = cgf.getBuilder().createCast(cir::CastKind::integral, index,
2126 numElements.getType());
2127 // GEP indexes are signed, and scaling an index isn't permitted to
2128 // signed-overflow, so we use the same semantics for our explicit
2129 // multiply. We suppress this if overflow is not undefined behavior.
2130 cir::OverflowFlags overflowFlags = cgf.getLangOpts().PointerOverflowDefined
2131 ? cir::OverflowFlags::None
2132 : cir::OverflowFlags::NoSignedWrap;
2133 index = cgf.getBuilder().createMul(loc, index, numElements, overflowFlags);
2135 return cir::PtrStrideOp::create(cgf.getBuilder(), loc, pointer.getType(),
2136 pointer, index);
2137 }
2138
2140 return cir::PtrStrideOp::create(cgf.getBuilder(),
2141 cgf.getLoc(op.e->getExprLoc()),
2142 pointer.getType(), pointer, index);
2143}
2144
2145static bool isIntegerVectorBinOp(mlir::Type ty) {
2146 auto vecTy = mlir::dyn_cast<cir::VectorType>(ty);
2147 return vecTy && mlir::isa<cir::IntType>(vecTy.getElementType());
2148}
2149
2150// Construct a cir.fmuladd op to represent a fused mul-add of `mulOp` and
2151// `addend`. Use negMul and negAdd to negate the first operand of the mul or
2152// the addend respectively. This allows fmuladd to represent a*b-c, or c-a*b.
2153// Patterns in LLVM should catch the negated forms and translate them to
2154// efficient operations.
2155static mlir::Value buildFMulAdd(mlir::Location addLoc, cir::FMulOp mulOp,
2156 mlir::Value addend, CIRGenBuilderTy &builder,
2157 bool negMul, bool negAdd) {
2158 mlir::Location loc = builder.getFusedLoc({mulOp.getLoc(), addLoc});
2159 mlir::Value mulOp0 = mulOp.getLhs();
2160 mlir::Value mulOp1 = mulOp.getRhs();
2161 if (negMul)
2162 mulOp0 = builder.createFNeg(loc, mulOp0);
2163 if (negAdd)
2164 addend = builder.createFNeg(loc, addend);
2165
2166 // Carry the mul's fenv attribute so a constrained fmul yields a constrained
2167 // fmuladd; the builder is under the add's FP options, not the mul's.
2168 mlir::Value fmuladd = cir::FMulAddOp::create(
2169 builder, loc, addend.getType(), mulOp0, mulOp1, addend,
2170 mulOp.getFenvAttr(), builder.getFastMathFlagsAttr());
2171 mulOp.erase();
2172 return fmuladd;
2173}
2174
2175// Check whether it would be legal to emit a cir.fmuladd op to represent op
2176// and if so, build it.
2177//
2178// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2179// Does NOT check the type of the operation - it's assumed that this function
2180// will be called from contexts where it's known that the type is contractable.
2181static mlir::Value tryEmitFMulAdd(mlir::Location loc, const BinOpInfo &op,
2182 CIRGenBuilderTy &builder,
2183 bool isSub = false) {
2184 assert((op.opcode == BO_Add || op.opcode == BO_AddAssign ||
2185 op.opcode == BO_Sub || op.opcode == BO_SubAssign) &&
2186 "Only fadd/fsub can be the root of an fmuladd.");
2187
2188 // Check whether this op is fusable, i.e. -ffp-contract=on. -ffp-contract=fast
2189 // is represented by the `contract` flag on the fmul/fadd instead.
2190 if (!op.fpFeatures.allowFPContractWithinStatement())
2191 return nullptr;
2192
2193 mlir::Value lhs = op.lhs;
2194 mlir::Value rhs = op.rhs;
2195
2196 // Peek through fneg to look for fmul. Make sure the fneg has no other users,
2197 // and that it is the only use of its operand.
2198 bool negLHS = false;
2199 if (auto lhsNeg = lhs.getDefiningOp<cir::FNegOp>()) {
2200 if (lhsNeg.getResult().use_empty() && lhsNeg.getInput().hasOneUse()) {
2201 lhs = lhsNeg.getInput();
2202 negLHS = true;
2203 }
2204 }
2205
2206 bool negRHS = false;
2207 if (auto rhsNeg = rhs.getDefiningOp<cir::FNegOp>()) {
2208 if (rhsNeg.getResult().use_empty() && rhsNeg.getInput().hasOneUse()) {
2209 rhs = rhsNeg.getInput();
2210 negRHS = true;
2211 }
2212 }
2213
2214 // We have a potentially fusable op. Look for a mul on one of the operands.
2215 // Also make sure that the mul result isn't used directly. In that case,
2216 // there's no point creating a muladd operation.
2217 if (auto lhsMul = lhs.getDefiningOp<cir::FMulOp>()) {
2218 if (lhsMul.getResult().use_empty() || negLHS) {
2219 // If we looked through fneg, erase it.
2220 if (negLHS)
2221 op.lhs.getDefiningOp<cir::FNegOp>().erase();
2222 return buildFMulAdd(loc, lhsMul, op.rhs, builder, negLHS, isSub);
2223 }
2224 }
2225 if (auto rhsMul = rhs.getDefiningOp<cir::FMulOp>()) {
2226 if (rhsMul.getResult().use_empty() || negRHS) {
2227 // If we looked through fneg, erase it.
2228 if (negRHS)
2229 op.rhs.getDefiningOp<cir::FNegOp>().erase();
2230 return buildFMulAdd(loc, rhsMul, op.lhs, builder, isSub ^ negRHS, false);
2231 }
2232 }
2233
2234 return nullptr;
2235}
2236
2237mlir::Value ScalarExprEmitter::emitFixedPointIncDec(const UnaryOperator *e,
2238 mlir::Value value,
2239 QualType type) {
2240 // Fixed-point types are tricky. In some cases, it isn't possible to
2241 // represent a 1 or a -1 in the type at all. Piggyback off of
2242 // EmitFixedPointBinOp to avoid having to reimplement saturation.
2243 BinOpInfo info;
2244 info.loc = e->getSourceRange();
2245 info.fpFeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
2246 info.e = e;
2247 info.compType = info.fullType = e->getType();
2248 info.opcode = e->isIncrementOp() ? BO_Add : BO_Sub;
2249 info.lhs = value;
2250 info.rhs = builder.getConstInt(cgf.getLoc(info.loc), value.getType(), 1);
2251 // If the type is signed, it's better to represent this as +(-1) or -(-1),
2252 // since -1 is guaranteed to be representable.
2253 // FIXME(cir): This is a carry-over from Classic codegen, we should probably
2254 // figure out if ++ -> -(-1) and -- -> +(-1) is REALLY what we want? For now
2255 // we are just doing what classic does here.
2256 if (type->isSignedFixedPointType()) {
2257 info.opcode = e->isIncrementOp() ? BO_Sub : BO_Add;
2258 info.rhs = builder.createNeg(cgf.getLoc(info.loc), info.rhs);
2259 }
2260 // Now, convert from our invented integer literal to the type of the unary
2261 // op. This will upscale and saturate if necessary. This value can become
2262 // undef in some cases.
2263 CIRGenFixedPointBuilder fpbuilder(builder, cgf.getLoc(info.loc));
2264 auto dstSema = cgf.getContext().getFixedPointSemantics(info.fullType);
2265 info.rhs =
2266 fpbuilder.createIntegerToFixed(info.rhs, /*srcIsSigned=*/true, dstSema);
2267 return emitFixedPointBinOp(info);
2268}
2269
2270mlir::Value ScalarExprEmitter::emitFixedPointConversion(mlir::Value src,
2271 QualType srcTy,
2272 QualType dstTy,
2273 mlir::Location loc) {
2274 assert(srcTy->isFixedPointType() || dstTy->isFixedPointType());
2275
2276 CIRGenFixedPointBuilder fpBuilder(builder, loc);
2277 mlir::Value result;
2278 if (srcTy->isRealFloatingType()) {
2279 assert(dstTy->isFixedPointType());
2280 result = fpBuilder.createFloatingToFixed(
2281 src, cgf.getContext().getFixedPointSemantics(dstTy));
2282 } else if (dstTy->isRealFloatingType()) {
2283 assert(srcTy->isFixedPointType());
2284 result = fpBuilder.createFixedToFloating(
2285 src, cgf.getContext().getFixedPointSemantics(srcTy),
2286 cgf.convertType(dstTy));
2287 } else {
2288 llvm::FixedPointSemantics srcFPSema =
2290 llvm::FixedPointSemantics dstFPSema =
2292
2293 if (dstTy->isIntegerType())
2294 result = fpBuilder.createFixedToInteger(
2295 src, srcFPSema, dstFPSema.getWidth(), dstFPSema.isSigned());
2296 else if (srcTy->isIntegerType())
2297 result =
2298 fpBuilder.createIntegerToFixed(src, srcFPSema.isSigned(), dstFPSema);
2299 else {
2300 assert(srcTy->isFixedPointType() && dstTy->isFixedPointType());
2301 result = fpBuilder.createFixedToFixed(src, srcFPSema, dstFPSema);
2302 }
2303 }
2304 return result;
2305}
2306
2307mlir::Value ScalarExprEmitter::emitMul(const BinOpInfo &ops) {
2308 const mlir::Location loc = cgf.getLoc(ops.loc);
2309 if (!isIntegerVectorBinOp(ops.lhs.getType()) &&
2310 ops.compType->isSignedIntegerOrEnumerationType()) {
2311 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
2312 case LangOptions::SOB_Defined:
2313 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2314 return builder.createMul(loc, ops.lhs, ops.rhs);
2315 [[fallthrough]];
2316 case LangOptions::SOB_Undefined:
2317 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2318 return builder.createNSWMul(loc, ops.lhs, ops.rhs);
2319 [[fallthrough]];
2320 case LangOptions::SOB_Trapping:
2321 if (canElideOverflowCheck(cgf.getContext(), ops))
2322 return builder.createNSWMul(loc, ops.lhs, ops.rhs);
2323 cgf.cgm.errorNYI("sanitizers");
2324 }
2325 }
2326
2327 if (ops.fullType->isConstantMatrixType()) {
2328 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2329
2330 if (isa<cir::MatrixType>(ops.lhs.getType()) &&
2331 isa<cir::MatrixType>(ops.rhs.getType()))
2332 return builder.createMatrixMultiply(loc, ops.lhs, ops.rhs);
2333
2334 auto [lhs, rhs] =
2335 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2336 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2337 return builder.createFMul(loc, lhs, rhs);
2338 return builder.createMul(loc, lhs, rhs);
2339 }
2340
2341 if (ops.compType->isUnsignedIntegerType() &&
2342 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2343 !canElideOverflowCheck(cgf.getContext(), ops))
2344 cgf.cgm.errorNYI("unsigned int overflow sanitizer");
2345
2346 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2347 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2348 return builder.createFMul(loc, ops.lhs, ops.rhs);
2349 }
2350
2351 if (ops.isFixedPointOp())
2352 return emitFixedPointBinOp(ops);
2353
2354 return cir::MulOp::create(builder, cgf.getLoc(ops.loc),
2355 cgf.convertType(ops.fullType), ops.lhs, ops.rhs);
2356}
2357mlir::Value ScalarExprEmitter::emitDiv(const BinOpInfo &ops) {
2358 const mlir::Location loc = cgf.getLoc(ops.loc);
2359 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2360 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2361 return builder.createFDiv(loc, ops.lhs, ops.rhs);
2362 }
2363
2364 if (ops.fullType->isConstantMatrixType()) {
2365 assert(mlir::isa<cir::MatrixType>(ops.lhs.getType()) &&
2366 "first operand must be a matrix");
2367 assert(cir::isAnyIntegerOrFloatingPointType(ops.rhs.getType()) &&
2368 "second operand must be an arithmetic type");
2369
2370 auto [lhs, rhs] =
2371 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2372
2373 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2374 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2375 return builder.createFDiv(loc, lhs, rhs);
2376 return builder.createDiv(loc, lhs, rhs);
2377 }
2378
2379 if (ops.isFixedPointOp())
2380 return emitFixedPointBinOp(ops);
2381
2382 return cir::DivOp::create(builder, loc, cgf.convertType(ops.fullType),
2383 ops.lhs, ops.rhs);
2384}
2385mlir::Value ScalarExprEmitter::emitRem(const BinOpInfo &ops) {
2386 const mlir::Location loc = cgf.getLoc(ops.loc);
2387 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2388 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2389 return builder.createFRem(loc, ops.lhs, ops.rhs);
2390 }
2391 return cir::RemOp::create(builder, loc, cgf.convertType(ops.fullType),
2392 ops.lhs, ops.rhs);
2393}
2394
2395mlir::Value ScalarExprEmitter::emitFixedPointBinOp(const BinOpInfo &ops) {
2396 // This is either a binary operation where at least one of the operands is
2397 // a fixed-point type, or a unary operation where the operand is a fixed-point
2398 // type. The result type of a binary operation is determined by
2399 // Sema::handleFixedPointConversions().
2400 QualType resultTy = ops.compType;
2401 QualType lhsTy, rhsTy;
2402 if (const auto *binOp = dyn_cast<BinaryOperator>(ops.e)) {
2403 rhsTy = binOp->getRHS()->getType();
2404 if (const auto *cao = dyn_cast<CompoundAssignOperator>(binOp)) {
2405 // For compound assignment, the effective type of the LHS at this point
2406 // is the computation LHS type, not the actual LHS type, and the final
2407 // result type is not the type of the expression but rather the
2408 // computation result type.
2409 lhsTy = cao->getComputationLHSType();
2410 resultTy = cao->getComputationResultType();
2411 } else {
2412 lhsTy = binOp->getLHS()->getType();
2413 }
2414 } else if (const auto *unOp = dyn_cast<UnaryOperator>(ops.e)) {
2415 lhsTy = unOp->getSubExpr()->getType();
2416 rhsTy = unOp->getSubExpr()->getType();
2417 }
2418 ASTContext &ctx = cgf.getContext();
2419 mlir::Value lhs = ops.lhs;
2420 mlir::Value rhs = ops.rhs;
2421
2422 auto lhsFixedSema = ctx.getFixedPointSemantics(lhsTy);
2423 auto rhsFixedSema = ctx.getFixedPointSemantics(rhsTy);
2424 auto resultFixedSema = ctx.getFixedPointSemantics(resultTy);
2425 auto commonFixedSema = lhsFixedSema.getCommonSemantics(rhsFixedSema);
2426
2427 // Perform the actual operation.
2428 mlir::Value result;
2429 CIRGenFixedPointBuilder fpbuilder(builder, cgf.getLoc(ops.loc));
2430 switch (ops.opcode) {
2431 case BO_AddAssign:
2432 case BO_Add:
2433 result = fpbuilder.createAdd(lhs, lhsFixedSema, rhs, rhsFixedSema);
2434 break;
2435 case BO_SubAssign:
2436 case BO_Sub:
2437 result = fpbuilder.createSub(lhs, lhsFixedSema, rhs, rhsFixedSema);
2438 break;
2439 case BO_MulAssign:
2440 case BO_Mul:
2441 result = fpbuilder.createMul(lhs, lhsFixedSema, rhs, rhsFixedSema);
2442 break;
2443 case BO_DivAssign:
2444 case BO_Div:
2445 result = fpbuilder.createDiv(lhs, lhsFixedSema, rhs, rhsFixedSema);
2446 break;
2447 case BO_ShlAssign:
2448 case BO_Shl:
2449 result = fpbuilder.createShl(lhs, lhsFixedSema, rhs);
2450 break;
2451 case BO_ShrAssign:
2452 case BO_Shr:
2453 result = fpbuilder.createShr(lhs, rhs);
2454 break;
2455 case BO_LT:
2456 case BO_GT:
2457 case BO_LE:
2458 case BO_GE:
2459 case BO_EQ:
2460 case BO_NE:
2461 return fpbuilder.createCmp(lhs, lhsFixedSema, rhs, rhsFixedSema,
2462 clangCmpToCIRCmp(ops.opcode));
2463 case BO_Cmp:
2464 case BO_LAnd:
2465 case BO_LOr:
2466 llvm_unreachable("Found unimplemented fixed point binary operation");
2467 case BO_PtrMemD:
2468 case BO_PtrMemI:
2469 case BO_Rem:
2470 case BO_Xor:
2471 case BO_And:
2472 case BO_Or:
2473 case BO_Assign:
2474 case BO_RemAssign:
2475 case BO_AndAssign:
2476 case BO_XorAssign:
2477 case BO_OrAssign:
2478 case BO_Comma:
2479 llvm_unreachable(
2480 "Found unsupported binary operation for fixed point types.");
2481 }
2482
2483 bool isShift = BinaryOperator::isShiftOp(ops.opcode) ||
2485 // Convert to the result type.
2486 return fpbuilder.createFixedToFixed(
2487 result, isShift ? lhsFixedSema : commonFixedSema, resultFixedSema);
2488}
2489
2490mlir::Value ScalarExprEmitter::emitAdd(const BinOpInfo &ops) {
2491 if (mlir::isa<cir::PointerType>(ops.lhs.getType()) ||
2492 mlir::isa<cir::PointerType>(ops.rhs.getType()))
2493 return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/
2494 false);
2495
2496 const mlir::Location loc = cgf.getLoc(ops.loc);
2497 if (!isIntegerVectorBinOp(ops.lhs.getType()) &&
2498 ops.compType->isSignedIntegerOrEnumerationType()) {
2499 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
2500 case LangOptions::SOB_Defined:
2501 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2502 return builder.createAdd(loc, ops.lhs, ops.rhs);
2503 [[fallthrough]];
2504 case LangOptions::SOB_Undefined:
2505 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2506 return builder.createNSWAdd(loc, ops.lhs, ops.rhs);
2507 [[fallthrough]];
2508 case LangOptions::SOB_Trapping:
2509 if (canElideOverflowCheck(cgf.getContext(), ops))
2510 return builder.createNSWAdd(loc, ops.lhs, ops.rhs);
2511 cgf.cgm.errorNYI("sanitizers");
2512 }
2513 }
2514 if (ops.fullType->isConstantMatrixType()) {
2515 // Like llvm::MatrixBuilder::CreateAdd, splat a scalar operand to the matrix
2516 // type before adding.
2517 auto [lhs, rhs] =
2518 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2519
2520 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2521 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2522 return builder.createFAdd(loc, lhs, rhs);
2523 return builder.createAdd(loc, lhs, rhs);
2524 }
2525
2526 if (ops.compType->isUnsignedIntegerType() &&
2527 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2528 !canElideOverflowCheck(cgf.getContext(), ops))
2529 cgf.cgm.errorNYI("unsigned int overflow sanitizer");
2530
2531 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2532 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2533 // Try to form an fmuladd.
2534 if (mlir::Value fmuladd = tryEmitFMulAdd(loc, ops, builder))
2535 return fmuladd;
2536 return builder.createFAdd(loc, ops.lhs, ops.rhs);
2537 }
2538
2539 if (ops.isFixedPointOp())
2540 return emitFixedPointBinOp(ops);
2541
2542 return builder.createAdd(loc, ops.lhs, ops.rhs);
2543}
2544
2545mlir::Value ScalarExprEmitter::emitSub(const BinOpInfo &ops) {
2546 const mlir::Location loc = cgf.getLoc(ops.loc);
2547 // The LHS is always a pointer if either side is.
2548 if (!mlir::isa<cir::PointerType>(ops.lhs.getType())) {
2549 if (!isIntegerVectorBinOp(ops.lhs.getType()) &&
2550 ops.compType->isSignedIntegerOrEnumerationType()) {
2551 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
2552 case LangOptions::SOB_Defined: {
2553 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2554 return builder.createSub(loc, ops.lhs, ops.rhs);
2555 [[fallthrough]];
2556 }
2557 case LangOptions::SOB_Undefined:
2558 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2559 return builder.createNSWSub(loc, ops.lhs, ops.rhs);
2560 [[fallthrough]];
2561 case LangOptions::SOB_Trapping:
2562 if (canElideOverflowCheck(cgf.getContext(), ops))
2563 return builder.createNSWSub(loc, ops.lhs, ops.rhs);
2564 cgf.cgm.errorNYI("sanitizers");
2565 }
2566 }
2567
2568 if (ops.fullType->isConstantMatrixType()) {
2569 // Like llvm::MatrixBuilder::CreateSub, splat a scalar operand to the
2570 // matrix type before adding.
2571 auto [lhs, rhs] =
2572 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2573
2574 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2575 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2576 return builder.createFSub(loc, lhs, rhs);
2577 return builder.createSub(loc, lhs, rhs);
2578 }
2579
2580 if (ops.compType->isUnsignedIntegerType() &&
2581 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2582 !canElideOverflowCheck(cgf.getContext(), ops))
2583 cgf.cgm.errorNYI("unsigned int overflow sanitizer");
2584
2585 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2586 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2587 // Try to form an fmuladd.
2588 if (mlir::Value fmuladd =
2589 tryEmitFMulAdd(loc, ops, builder, /*isSub=*/true))
2590 return fmuladd;
2591 return builder.createFSub(loc, ops.lhs, ops.rhs);
2592 }
2593
2594 if (ops.isFixedPointOp())
2595 return emitFixedPointBinOp(ops);
2596
2597 return builder.createSub(loc, ops.lhs, ops.rhs);
2598 }
2599
2600 // If the RHS is not a pointer, then we have normal pointer
2601 // arithmetic.
2602 if (!mlir::isa<cir::PointerType>(ops.rhs.getType()))
2603 return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/true);
2604
2605 // Otherwise, this is a pointer subtraction
2606
2607 // Do the raw subtraction part.
2608 //
2609 // TODO(cir): note for LLVM lowering out of this; when expanding this into
2610 // LLVM we shall take VLA's, division by element size, etc.
2611 //
2612 // See more in `EmitSub` in CGExprScalar.cpp.
2614 return cir::PtrDiffOp::create(builder, cgf.getLoc(ops.loc), cgf.ptrDiffTy,
2615 ops.lhs, ops.rhs);
2616}
2617
2618mlir::Value ScalarExprEmitter::emitShl(const BinOpInfo &ops) {
2619 // TODO: This misses out on the sanitizer check below.
2620 if (ops.isFixedPointOp())
2621 return emitFixedPointBinOp(ops);
2622
2623 // CIR accepts shift between different types, meaning nothing special
2624 // to be done here. OTOH, LLVM requires the LHS and RHS to be the same type:
2625 // promote or truncate the RHS to the same size as the LHS.
2626
2627 bool sanitizeSignedBase = cgf.sanOpts.has(SanitizerKind::ShiftBase) &&
2628 ops.compType->hasSignedIntegerRepresentation() &&
2630 !cgf.getLangOpts().CPlusPlus20;
2631 bool sanitizeUnsignedBase =
2632 cgf.sanOpts.has(SanitizerKind::UnsignedShiftBase) &&
2633 ops.compType->hasUnsignedIntegerRepresentation();
2634 bool sanitizeBase = sanitizeSignedBase || sanitizeUnsignedBase;
2635 bool sanitizeExponent = cgf.sanOpts.has(SanitizerKind::ShiftExponent);
2636
2637 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2638 if (cgf.getLangOpts().OpenCL)
2639 cgf.cgm.errorNYI("opencl");
2640 else if ((sanitizeBase || sanitizeExponent) &&
2641 mlir::isa<cir::IntType>(ops.lhs.getType()))
2642 cgf.cgm.errorNYI("sanitizers");
2643
2644 return builder.createShiftLeft(cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2645}
2646
2647mlir::Value ScalarExprEmitter::emitShr(const BinOpInfo &ops) {
2648 // TODO: This misses out on the sanitizer check below.
2649 if (ops.isFixedPointOp())
2650 return emitFixedPointBinOp(ops);
2651
2652 // CIR accepts shift between different types, meaning nothing special
2653 // to be done here. OTOH, LLVM requires the LHS and RHS to be the same type:
2654 // promote or truncate the RHS to the same size as the LHS.
2655
2656 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2657 if (cgf.getLangOpts().OpenCL)
2658 cgf.cgm.errorNYI("opencl");
2659 else if (cgf.sanOpts.has(SanitizerKind::ShiftExponent) &&
2660 mlir::isa<cir::IntType>(ops.lhs.getType()))
2661 cgf.cgm.errorNYI("sanitizers");
2662
2663 // Note that we don't need to distinguish unsigned treatment at this
2664 // point since it will be handled later by LLVM lowering.
2665 return builder.createShiftRight(cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2666}
2667
2668mlir::Value ScalarExprEmitter::emitAnd(const BinOpInfo &ops) {
2669 return cir::AndOp::create(builder, cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2670}
2671mlir::Value ScalarExprEmitter::emitXor(const BinOpInfo &ops) {
2672 return cir::XorOp::create(builder, cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2673}
2674mlir::Value ScalarExprEmitter::emitOr(const BinOpInfo &ops) {
2675 return cir::OrOp::create(builder, cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2676}
2677
2678// Emit code for an explicit or implicit cast. Implicit
2679// casts have to handle a more broad range of conversions than explicit
2680// casts, as they handle things like function to ptr-to-function decay
2681// etc.
2682mlir::Value ScalarExprEmitter::VisitCastExpr(CastExpr *ce) {
2683 Expr *subExpr = ce->getSubExpr();
2684 QualType destTy = ce->getType();
2685 CastKind kind = ce->getCastKind();
2686 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ce);
2687
2688 // These cases are generally not written to ignore the result of evaluating
2689 // their sub-expressions, so we clear this now.
2690 ignoreResultAssign = false;
2691
2692 switch (kind) {
2693 case clang::CK_Dependent:
2694 llvm_unreachable("dependent cast kind in CIR gen!");
2695 case clang::CK_BuiltinFnToFnPtr:
2696 llvm_unreachable("builtin functions are handled elsewhere");
2697 case CK_LValueBitCast:
2698 case CK_LValueToRValueBitCast: {
2699 LValue sourceLVal = cgf.emitLValue(subExpr);
2700 Address sourceAddr = sourceLVal.getAddress();
2701
2702 mlir::Type destElemTy = cgf.convertTypeForMem(destTy);
2703 Address destAddr = sourceAddr.withElementType(cgf.getBuilder(), destElemTy);
2704 LValue destLVal = cgf.makeAddrLValue(destAddr, destTy);
2706 return emitLoadOfLValue(destLVal, ce->getExprLoc());
2707 }
2708
2709 case CK_CPointerToObjCPointerCast:
2710 case CK_BlockPointerToObjCPointerCast:
2711 case CK_AnyPointerToBlockPointerCast:
2712 case CK_BitCast: {
2713 mlir::Value src = Visit(const_cast<Expr *>(subExpr));
2714 mlir::Type dstTy = cgf.convertType(destTy);
2715
2716 // Function and object pointers may differ in address space.
2717 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(src.getType());
2718 auto dstPtrTy = mlir::dyn_cast<cir::PointerType>(dstTy);
2719 if (srcPtrTy && dstPtrTy &&
2720 srcPtrTy.getAddrSpace() != dstPtrTy.getAddrSpace())
2721 src = cgf.performAddrSpaceCast(
2722 src,
2723 builder.getPointerTo(srcPtrTy.getPointee(), dstPtrTy.getAddrSpace()));
2724
2725 if (cgf.sanOpts.has(SanitizerKind::CFIUnrelatedCast))
2726 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
2727 "sanitizer support");
2728
2729 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers)
2730 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
2731 "strict vtable pointers");
2732
2733 // Update heapallocsite metadata when there is an explicit pointer cast.
2735
2736 // If Src is a fixed vector and Dst is a scalable vector, and both have the
2737 // same element type, use the llvm.vector.insert intrinsic to perform the
2738 // bitcast.
2740
2741 // If Src is a scalable vector and Dst is a fixed vector, and both have the
2742 // same element type, use the llvm.vector.extract intrinsic to perform the
2743 // bitcast.
2745
2746 // Perform VLAT <-> VLST bitcast through memory.
2747 // TODO: since the llvm.experimental.vector.{insert,extract} intrinsics
2748 // require the element types of the vectors to be the same, we
2749 // need to keep this around for bitcasts between VLAT <-> VLST where
2750 // the element types of the vectors are not the same, until we figure
2751 // out a better way of doing these casts.
2753
2754 return cgf.getBuilder().createBitcast(cgf.getLoc(subExpr->getSourceRange()),
2755 src, dstTy);
2756 }
2757 case CK_AddressSpaceConversion: {
2758 Expr::EvalResult result;
2759 if (subExpr->EvaluateAsRValue(result, cgf.getContext()) &&
2760 result.Val.isNullPointer()) {
2761 // If e has side effect, it is emitted even if its final result is a
2762 // null pointer. In that case, a DCE pass should be able to
2763 // eliminate the useless instructions emitted during translating E.
2764 if (result.HasSideEffects)
2765 Visit(subExpr);
2766 return cgf.cgm.getNullPointer(
2767 mlir::cast<cir::PointerType>(convertType(destTy)), destTy,
2768 cgf.getLoc(subExpr->getExprLoc()));
2769 }
2770 return cgf.performAddrSpaceCast(Visit(subExpr), convertType(destTy));
2771 }
2772
2773 case CK_AtomicToNonAtomic:
2774 case CK_NonAtomicToAtomic:
2775 case CK_UserDefinedConversion:
2776 return Visit(const_cast<Expr *>(subExpr));
2777 case CK_NoOp:
2778 return ce->changesVolatileQualification() ? emitLoadOfLValue(ce)
2779 : Visit(subExpr);
2780 case CK_IntegralToPointer: {
2781 mlir::Type destCIRTy = cgf.convertType(destTy);
2782 mlir::Value src = Visit(const_cast<Expr *>(subExpr));
2783
2784 // Properly resize by casting to an int of the same size as the pointer.
2785 // Clang's IntegralToPointer includes 'bool' as the source, but in CIR
2786 // 'bool' is not an integral type. So check the source type to get the
2787 // correct CIR conversion.
2788 mlir::Type middleTy = cgf.cgm.getDataLayout().getIntPtrType(destCIRTy);
2789 mlir::Value middleVal = builder.createCast(
2790 subExpr->getType()->isBooleanType() ? cir::CastKind::bool_to_int
2791 : cir::CastKind::integral,
2792 src, middleTy);
2793
2794 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers) {
2795 cgf.cgm.errorNYI(subExpr->getSourceRange(),
2796 "IntegralToPointer: strict vtable pointers");
2797 return {};
2798 }
2799
2800 return builder.createIntToPtr(middleVal, destCIRTy);
2801 }
2802
2803 case CK_BaseToDerived: {
2804 const CXXRecordDecl *derivedClassDecl = destTy->getPointeeCXXRecordDecl();
2805 assert(derivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2806 Address base = cgf.emitPointerWithAlignment(subExpr);
2807 Address derived = cgf.getAddressOfDerivedClass(
2808 cgf.getLoc(ce->getSourceRange()), base, derivedClassDecl, ce->path(),
2810
2811 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2812 // performed and the object is not of the derived type.
2814
2815 return cgf.getAsNaturalPointerTo(derived, ce->getType()->getPointeeType());
2816 }
2817 case CK_UncheckedDerivedToBase:
2818 case CK_DerivedToBase: {
2819 // The EmitPointerWithAlignment path does this fine; just discard
2820 // the alignment.
2822 ce->getType()->getPointeeType());
2823 }
2824 case CK_Dynamic: {
2825 Address v = cgf.emitPointerWithAlignment(subExpr);
2826 const auto *dce = cast<CXXDynamicCastExpr>(ce);
2827 return cgf.emitDynamicCast(v, dce);
2828 }
2829 case CK_ArrayToPointerDecay:
2830 return cgf.emitArrayToPointerDecay(subExpr).getPointer();
2831
2832 case CK_NullToPointer: {
2833 if (mustVisitNullValue(subExpr))
2834 cgf.emitIgnoredExpr(subExpr);
2835
2836 // Note that DestTy is used as the MLIR type instead of a custom
2837 // nullptr type.
2838 auto ty = mlir::cast<cir::PointerType>(cgf.convertType(destTy));
2839 return cgf.cgm.getNullPointer(ty, destTy,
2840 cgf.getLoc(subExpr->getExprLoc()));
2841 }
2842
2843 case CK_NullToMemberPointer: {
2844 if (mustVisitNullValue(subExpr))
2845 cgf.emitIgnoredExpr(subExpr);
2846
2848
2849 const MemberPointerType *mpt = ce->getType()->getAs<MemberPointerType>();
2850 mlir::Location loc = cgf.getLoc(subExpr->getExprLoc());
2851 return cgf.getBuilder().getConstant(
2852 loc, cgf.cgm.emitNullMemberAttr(destTy, mpt));
2853 }
2854
2855 case CK_ReinterpretMemberPointer: {
2856 mlir::Value src = Visit(subExpr);
2857 return builder.createBitcast(cgf.getLoc(subExpr->getExprLoc()), src,
2858 cgf.convertType(destTy));
2859 }
2860 case CK_BaseToDerivedMemberPointer:
2861 case CK_DerivedToBaseMemberPointer: {
2862 mlir::Value src = Visit(subExpr);
2863
2865
2866 QualType derivedTy =
2867 kind == CK_DerivedToBaseMemberPointer ? subExpr->getType() : destTy;
2868 const auto *mpType = derivedTy->castAs<MemberPointerType>();
2869 NestedNameSpecifier qualifier = mpType->getQualifier();
2870 assert(qualifier && "member pointer without class qualifier");
2871 const Type *qualifierType = qualifier.getAsType();
2872 assert(qualifierType && "member pointer qualifier is not a type");
2873 const CXXRecordDecl *derivedClass = qualifierType->getAsCXXRecordDecl();
2874 CharUnits offset =
2875 cgf.cgm.computeNonVirtualBaseClassOffset(derivedClass, ce->path());
2876
2877 mlir::Location loc = cgf.getLoc(subExpr->getExprLoc());
2878 mlir::Type resultTy = cgf.convertType(destTy);
2879 mlir::IntegerAttr offsetAttr = builder.getIndexAttr(offset.getQuantity());
2880
2881 if (subExpr->getType()->isMemberFunctionPointerType()) {
2882 if (kind == CK_BaseToDerivedMemberPointer)
2883 return cir::DerivedMethodOp::create(builder, loc, resultTy, src,
2884 offsetAttr);
2885 return cir::BaseMethodOp::create(builder, loc, resultTy, src, offsetAttr);
2886 }
2887
2888 if (kind == CK_BaseToDerivedMemberPointer)
2889 return cir::DerivedDataMemberOp::create(builder, loc, resultTy, src,
2890 offsetAttr);
2891 return cir::BaseDataMemberOp::create(builder, loc, resultTy, src,
2892 offsetAttr);
2893 }
2894
2895 case CK_LValueToRValue:
2896 assert(cgf.getContext().hasSameUnqualifiedType(subExpr->getType(), destTy));
2897 assert(subExpr->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2898 return Visit(const_cast<Expr *>(subExpr));
2899
2900 case CK_IntegralCast: {
2901 ScalarConversionOpts opts;
2902 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce)) {
2903 if (!ice->isPartOfExplicitCast())
2904 opts = ScalarConversionOpts(cgf.sanOpts);
2905 }
2906 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2907 ce->getExprLoc(), opts);
2908 }
2909
2910 case CK_FloatingComplexToReal:
2911 case CK_IntegralComplexToReal:
2912 case CK_FloatingComplexToBoolean:
2913 case CK_IntegralComplexToBoolean: {
2914 mlir::Value value = cgf.emitComplexExpr(subExpr);
2915 return emitComplexToScalarConversion(cgf.getLoc(ce->getExprLoc()), value,
2916 kind, destTy);
2917 }
2918
2919 case CK_FloatingRealToComplex:
2920 case CK_FloatingComplexCast:
2921 case CK_IntegralRealToComplex:
2922 case CK_IntegralComplexCast:
2923 case CK_IntegralComplexToFloatingComplex:
2924 case CK_FloatingComplexToIntegralComplex:
2925 llvm_unreachable("scalar cast to non-scalar value");
2926
2927 case CK_PointerToIntegral: {
2928 assert(!destTy->isBooleanType() && "bool should use PointerToBool");
2929 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers)
2930 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
2931 "strict vtable pointers");
2932 return builder.createPtrToInt(Visit(subExpr), cgf.convertType(destTy));
2933 }
2934 case CK_ToVoid:
2935 cgf.emitIgnoredExpr(subExpr);
2936 return {};
2937
2938 case CK_FixedPointCast:
2939 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2940 ce->getExprLoc());
2941
2942 case CK_FixedPointToBoolean:
2943 assert(subExpr->getType()->isFixedPointType() &&
2944 "Expected src type to be fixed point type");
2945 assert(destTy->isBooleanType() && "Expected dest type to be boolean type");
2946 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2947 ce->getExprLoc());
2948
2949 case CK_FixedPointToIntegral:
2950 assert(subExpr->getType()->isFixedPointType() &&
2951 "Expected src type to be fixed point type");
2952 assert(destTy->isIntegerType() && "Expected dest type to be an integer");
2953 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2954 ce->getExprLoc());
2955
2956 case CK_IntegralToFixedPoint:
2957 assert(subExpr->getType()->isIntegerType() &&
2958 "Expected src type to be an integer");
2959 assert(destTy->isFixedPointType() &&
2960 "Expected dest type to be fixed point type");
2961 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2962 ce->getExprLoc());
2963
2964 case CK_IntegralToFloating:
2965 case CK_FloatingToIntegral:
2966 case CK_FloatingCast:
2967 case CK_FixedPointToFloating:
2968 case CK_FloatingToFixedPoint: {
2969 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ce);
2970 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2971 ce->getExprLoc());
2972 }
2973
2974 case CK_IntegralToBoolean:
2975 return emitIntToBoolConversion(Visit(subExpr),
2976 cgf.getLoc(ce->getSourceRange()));
2977
2978 case CK_PointerToBoolean:
2979 return emitPointerToBoolConversion(Visit(subExpr), subExpr->getType());
2980 case CK_FloatingToBoolean:
2981 return emitFloatToBoolConversion(Visit(subExpr),
2982 cgf.getLoc(subExpr->getExprLoc()));
2983 case CK_MemberPointerToBoolean: {
2984 mlir::Value memPtr = Visit(subExpr);
2985 return builder.createCast(cgf.getLoc(ce->getSourceRange()),
2986 cir::CastKind::member_ptr_to_bool, memPtr,
2987 cgf.convertType(destTy));
2988 }
2989
2990 case CK_HLSLAggregateSplatCast:
2991 case CK_VectorSplat: {
2992 // Splat the element across to all elements
2993 mlir::Type destCIRTy = cgf.convertType(destTy);
2994 return cir::VecSplatOp::create(builder,
2995 cgf.getLoc(subExpr->getSourceRange()),
2996 destCIRTy, Visit(subExpr));
2997 }
2998 case CK_FunctionToPointerDecay:
2999 return cgf.emitLValue(subExpr).getPointer();
3000
3001 case CK_HLSLVectorTruncation: {
3002 assert((destTy->isVectorType() || destTy->isBuiltinType()) &&
3003 "Destination type must be a vector or builtin type.");
3004 mlir::Value vec = Visit(subExpr);
3005 mlir::Location loc = cgf.getLoc(subExpr->getSourceRange());
3006 if (auto *vecTy = destTy->getAs<VectorType>()) {
3007 unsigned numElts = vecTy->getNumElements();
3008 llvm::SmallVector<int64_t, 4> mask(numElts);
3009 std::iota(mask.begin(), mask.end(), 0);
3010 return builder.createVecShuffle(loc, vec, mask);
3011 }
3012 mlir::Value idx = builder.getConstInt(loc, cgf.sizeTy, 0);
3013 return cir::VecExtractOp::create(builder, loc, vec, idx);
3014 }
3015
3016 case CK_HLSLMatrixTruncation: {
3017 assert((destTy->isMatrixType() || destTy->isBuiltinType()) &&
3018 "Destination type must be a matrix or builtin type.");
3019 mlir::Value matrix = Visit(subExpr);
3020 mlir::Location loc = cgf.getLoc(subExpr->getSourceRange());
3021 if (const auto *matTy = destTy->getAs<ConstantMatrixType>()) {
3022 llvm::SmallVector<int64_t> mask(matTy->getNumElementsFlattened());
3023 unsigned numCols = matTy->getNumColumns();
3024 unsigned numRows = matTy->getNumRows();
3025
3026 auto *srcMatTy = subExpr->getType()->getAs<ConstantMatrixType>();
3027 assert(srcMatTy && "Source type must be a matrix type.");
3028 assert(numRows <= srcMatTy->getNumRows());
3029 assert(numCols <= srcMatTy->getNumColumns());
3030
3031 for (unsigned row = 0; row < numRows; row++)
3032 for (unsigned column = 0; column < numCols; column++)
3033 mask[matTy->getColumnMajorFlattenedIndex(row, column)] =
3034 srcMatTy->getColumnMajorFlattenedIndex(row, column);
3035
3036 auto elementTy =
3037 mlir::cast<cir::MatrixType>(matrix.getType()).getElementType();
3038 auto resultTy = cir::MatrixType::get(builder.getContext(), elementTy,
3039 numRows, numCols);
3040 return builder.createVecShuffle(loc, matrix, resultTy, mask);
3041 }
3042
3043 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
3044 "ScalarExprEmitter::VisitCastExpr: HLSL "
3045 "Matrix truncation with non-matrix dest");
3046 return {};
3047 }
3048 default:
3049 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
3050 "CastExpr: ", ce->getCastKindName());
3051 }
3052 return {};
3053}
3054
3055mlir::Value ScalarExprEmitter::VisitCallExpr(const CallExpr *e) {
3057 return emitLoadOfLValue(e);
3058
3059 auto v = cgf.emitCallExpr(e).getValue();
3061 return v;
3062}
3063
3064mlir::Value ScalarExprEmitter::VisitMemberExpr(MemberExpr *e) {
3065 if (CIRGenFunction::ConstantEmission constant = cgf.tryEmitAsConstant(e)) {
3066 cgf.emitIgnoredExpr(e->getBase());
3067 return cgf.emitScalarConstant(constant, e);
3068 } else {
3069 Expr::EvalResult result;
3070 if (e->EvaluateAsInt(result, cgf.getContext(), Expr::SE_AllowSideEffects)) {
3071 llvm::APSInt value = result.Val.getInt();
3072 cgf.emitIgnoredExpr(e->getBase());
3073 mlir::Location loc = cgf.getLoc(e->getExprLoc());
3074 // The constant is folded from an APSInt with the source-type's bit width
3075 // (1 for bool), but the AST's expression type is what later consumers of
3076 // this value see. For a bool member we have to emit a !cir.bool constant
3077 // -- otherwise downstream ops (cir.call into a bool parameter, cir.if /
3078 // cir.ternary on the value, ...) would all reject the !cir.int<u, 1> the
3079 // raw APSInt would produce.
3080 if (e->getType()->isBooleanType())
3081 return builder.getBool(value.getBoolValue(), loc);
3082 return builder.getConstInt(loc, value);
3083 }
3084 }
3085
3086 return emitLoadOfLValue(e);
3087}
3088
3089mlir::Value
3090ScalarExprEmitter::emitVectorInitWithSubvectors(mlir::Location loc,
3091 cir::VectorType vectorType,
3092 ArrayRef<mlir::Value> inits) {
3093 const unsigned resElts = vectorType.getFixedSize();
3094 mlir::Value result =
3095 builder.getConstant(loc, cir::PoisonAttr::get(vectorType));
3096 unsigned curIdx = 0;
3097 for (mlir::Value init : inits) {
3098 auto initType = mlir::dyn_cast<cir::VectorType>(init.getType());
3099 if (!initType) {
3100 result = builder.createInsertElement(loc, result, init, curIdx++);
3101 continue;
3102 }
3103
3104 const unsigned initElts = initType.getFixedSize();
3105 assert(curIdx + initElts <= resElts &&
3106 "Sema should reject excess elements");
3107 SmallVector<int64_t, 16> mask(resElts, -1);
3108 std::iota(mask.begin(), mask.begin() + initElts, 0);
3109 mlir::Value ext = builder.createVecShuffle(loc, init, mask);
3110
3111 // Poison stays on the RHS of the first shuffle, matching classic codegen.
3112 const unsigned offset = curIdx == 0 ? 0 : resElts;
3113 std::iota(mask.begin(), mask.begin() + curIdx, 0);
3114 std::iota(mask.begin() + curIdx, mask.begin() + curIdx + initElts, offset);
3115 if (curIdx == 0)
3116 std::swap(result, ext);
3117 result = builder.createVecShuffle(loc, result, ext, mask);
3118 curIdx += initElts;
3119 }
3120
3121 if (curIdx < resElts) {
3122 const mlir::Value zeroValue =
3123 builder.getNullValue(vectorType.getElementType(), loc);
3124 for (; curIdx < resElts; ++curIdx)
3125 result = builder.createInsertElement(loc, result, zeroValue, curIdx);
3126 }
3127 return result;
3128}
3129
3130mlir::Value ScalarExprEmitter::VisitInitListExpr(InitListExpr *e) {
3131 const unsigned numInitElements = e->getNumInits();
3132
3133 [[maybe_unused]] const bool ignore = std::exchange(ignoreResultAssign, false);
3134 assert((ignore == false ||
3135 (numInitElements == 0 && e->getType()->isVoidType())) &&
3136 "init list ignored");
3137
3138 if (e->hadArrayRangeDesignator()) {
3139 cgf.cgm.errorNYI(e->getSourceRange(), "ArrayRangeDesignator");
3140 return {};
3141 }
3142
3143 if (e->getType()->isVectorType()) {
3144 const auto vectorType =
3145 mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
3146
3147 SmallVector<mlir::Value, 16> elements;
3148 bool hasVectorInit = false;
3149 for (Expr *init : e->inits()) {
3150 elements.push_back(Visit(init));
3151 hasVectorInit |= mlir::isa<cir::VectorType>(elements.back().getType());
3152 }
3153
3154 if (hasVectorInit)
3155 return emitVectorInitWithSubvectors(cgf.getLoc(e->getSourceRange()),
3156 vectorType, elements);
3157
3158 // Zero-initialize any remaining values.
3159 const uint64_t vectorSize = vectorType.getFixedSize();
3160 if (numInitElements < vectorSize) {
3161 const mlir::Value zeroValue = cgf.getBuilder().getNullValue(
3162 vectorType.getElementType(), cgf.getLoc(e->getSourceRange()));
3163 std::fill_n(std::back_inserter(elements), vectorSize - numInitElements,
3164 zeroValue);
3165 }
3166
3167 return cir::VecCreateOp::create(cgf.getBuilder(),
3168 cgf.getLoc(e->getSourceRange()), vectorType,
3169 elements);
3170 }
3171
3173
3174 if (e->getType()->isVoidType())
3175 return {};
3176
3177 // C++11 value-initialization for the scalar.
3178 if (numInitElements == 0)
3179 return emitNullValue(e->getType(), cgf.getLoc(e->getExprLoc()));
3180
3181 return Visit(e->getInit(0));
3182}
3183
3184mlir::Value CIRGenFunction::emitScalarConversion(mlir::Value src,
3185 QualType srcTy, QualType dstTy,
3186 SourceLocation loc) {
3189 "Invalid scalar expression to emit");
3190 return ScalarExprEmitter(*this, builder)
3191 .emitScalarConversion(src, srcTy, dstTy, loc);
3192}
3193
3195 QualType srcTy,
3196 QualType dstTy,
3197 SourceLocation loc) {
3198 assert(srcTy->isAnyComplexType() && hasScalarEvaluationKind(dstTy) &&
3199 "Invalid complex -> scalar conversion");
3200
3201 QualType complexElemTy = srcTy->castAs<ComplexType>()->getElementType();
3202 if (dstTy->isBooleanType()) {
3203 auto kind = complexElemTy->isFloatingType()
3204 ? cir::CastKind::float_complex_to_bool
3205 : cir::CastKind::int_complex_to_bool;
3206 return builder.createCast(getLoc(loc), kind, src, convertType(dstTy));
3207 }
3208
3209 auto kind = complexElemTy->isFloatingType()
3210 ? cir::CastKind::float_complex_to_real
3211 : cir::CastKind::int_complex_to_real;
3212 mlir::Value real =
3213 builder.createCast(getLoc(loc), kind, src, convertType(complexElemTy));
3214 return emitScalarConversion(real, complexElemTy, dstTy, loc);
3215}
3216
3217mlir::Value ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *e) {
3218 // Perform vector logical not on comparison with zero vector.
3219 if (e->getType()->isVectorType() &&
3220 e->getType()->castAs<VectorType>()->getVectorKind() ==
3222 mlir::Value oper = Visit(e->getSubExpr());
3223 mlir::Location loc = cgf.getLoc(e->getExprLoc());
3224 auto operVecTy = mlir::cast<cir::VectorType>(oper.getType());
3225 mlir::Value zeroVec = builder.getNullValue(operVecTy, loc);
3226 auto resultTy = mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
3227 if (cir::isFPOrVectorOfFPType(operVecTy.getElementType())) {
3228 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
3229 return builder.createVecFCompare(loc, resultTy, cir::FCmpOpKind::oeq,
3230 oper, zeroVec);
3231 }
3232
3233 return builder.createVecCompare(loc, resultTy, cir::CmpOpKind::eq, oper,
3234 zeroVec);
3235 }
3236
3237 // Compare operand to zero.
3238 mlir::Value boolVal = cgf.evaluateExprAsBool(e->getSubExpr());
3239
3240 // Invert value.
3241 boolVal = builder.createNot(boolVal);
3242
3243 // ZExt result to the expr type.
3244 return maybePromoteBoolResult(boolVal, cgf.convertType(e->getType()));
3245}
3246
3247mlir::Value ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *e) {
3248 // Try folding the offsetof to a constant.
3249 Expr::EvalResult evalResult;
3250 if (e->EvaluateAsInt(evalResult, cgf.getContext())) {
3251 mlir::Type type = cgf.convertType(e->getType());
3252 llvm::APSInt value = evalResult.Val.getInt();
3253 return builder.getConstAPInt(cgf.getLoc(e->getExprLoc()), type, value);
3254 }
3255
3257 e->getSourceRange(),
3258 "ScalarExprEmitter::VisitOffsetOfExpr Can't eval expr as int");
3259 return {};
3260}
3261
3262mlir::Value ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *e) {
3263 QualType promotionTy = getPromotionType(e->getSubExpr()->getType());
3264 mlir::Value result = VisitRealImag(e, promotionTy);
3265 if (result && !promotionTy.isNull())
3266 result = emitUnPromotedValue(result, e->getType());
3267 return result;
3268}
3269
3270mlir::Value ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *e) {
3271 QualType promotionTy = getPromotionType(e->getSubExpr()->getType());
3272 mlir::Value result = VisitRealImag(e, promotionTy);
3273 if (result && !promotionTy.isNull())
3274 result = emitUnPromotedValue(result, e->getType());
3275 return result;
3276}
3277
3278mlir::Value ScalarExprEmitter::VisitRealImag(const UnaryOperator *e,
3279 QualType promotionTy) {
3280 assert(
3281 (e->getOpcode() == clang::UO_Real || e->getOpcode() == clang::UO_Imag) &&
3282 "Invalid UnaryOp kind for ComplexType Real or Imag");
3283
3284 Expr *op = e->getSubExpr();
3285 mlir::Location loc = cgf.getLoc(e->getExprLoc());
3286 if (op->getType()->isAnyComplexType()) {
3287 // If it's an l-value, load through the appropriate subobject l-value.
3288 // Note that we have to ask `e` because `op` might be an l-value that
3289 // this won't work for, e.g. an Obj-C property
3290 mlir::Value complex = cgf.emitComplexExpr(op);
3291 if (e->isGLValue() && !promotionTy.isNull()) {
3292 promotionTy = promotionTy->isAnyComplexType()
3293 ? promotionTy
3294 : cgf.getContext().getComplexType(promotionTy);
3295 complex = cgf.emitPromotedValue(complex, promotionTy);
3296 }
3297
3298 return e->getOpcode() == clang::UO_Real
3299 ? builder.createComplexReal(loc, complex)
3300 : builder.createComplexImag(loc, complex);
3301 }
3302
3303 if (e->getOpcode() == UO_Real) {
3304 mlir::Value operand = promotionTy.isNull()
3305 ? Visit(op)
3306 : cgf.emitPromotedScalarExpr(op, promotionTy);
3307 return builder.createComplexReal(loc, operand);
3308 }
3309
3310 // __imag on a scalar returns zero. Emit the subexpr to ensure side
3311 // effects are evaluated, but not the actual value.
3312 mlir::Value operand;
3313 if (op->isGLValue()) {
3314 operand = cgf.emitLValue(op).getPointer();
3315 operand = cir::LoadOp::create(builder, loc, operand);
3316 } else if (!promotionTy.isNull()) {
3317 operand = cgf.emitPromotedScalarExpr(op, promotionTy);
3318 } else {
3319 operand = cgf.emitScalarExpr(op);
3320 }
3321 return builder.createComplexImag(loc, operand);
3322}
3323
3324/// Return the size or alignment of the type of argument of the sizeof
3325/// expression as an integer.
3326mlir::Value ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3327 const UnaryExprOrTypeTraitExpr *e) {
3328 const QualType typeToSize = e->getTypeOfArgument();
3329 const mlir::Location loc = cgf.getLoc(e->getSourceRange());
3330 if (auto kind = e->getKind();
3331 kind == UETT_SizeOf || kind == UETT_DataSizeOf || kind == UETT_CountOf) {
3332 if (const VariableArrayType *vat =
3333 cgf.getContext().getAsVariableArrayType(typeToSize)) {
3334 // For _Countof, we only want to evaluate if the extent is actually
3335 // variable as opposed to a multi-dimensional array whose extent is
3336 // constant but whose element type is variable.
3337 bool evaluateExtent = true;
3338 if (kind == UETT_CountOf && vat->getElementType()->isArrayType()) {
3339 evaluateExtent =
3340 !vat->getSizeExpr()->isIntegerConstantExpr(cgf.getContext());
3341 }
3342
3343 if (evaluateExtent) {
3344 if (e->isArgumentType()) {
3345 // sizeof(type) - make sure to emit the VLA size.
3346 cgf.emitVariablyModifiedType(typeToSize);
3347 } else {
3348 // C99 6.5.3.4p2: If the argument is an expression of type
3349 // VLA, it is evaluated.
3351 }
3352
3353 // For _Countof, we just want to return the size of a single dimension.
3354 if (kind == UETT_CountOf)
3355 return cgf.getVLAElements1D(vat).numElts;
3356
3357 // For sizeof and __datasizeof, we need to scale the number of elements
3358 // by the size of the array element type.
3359 CIRGenFunction::VlaSizePair vlaSize = cgf.getVLASize(vat);
3360 mlir::Value numElts = vlaSize.numElts;
3361
3362 // Scale the number of non-VLA elements by the non-VLA element size.
3363 CharUnits eltSize = cgf.getContext().getTypeSizeInChars(vlaSize.type);
3364 if (!eltSize.isOne()) {
3365 mlir::Location loc = cgf.getLoc(e->getSourceRange());
3366 mlir::Value eltSizeValue =
3367 builder.getConstAPInt(numElts.getLoc(), numElts.getType(),
3368 cgf.cgm.getSize(eltSize).getValue());
3369 return builder.createMul(loc, eltSizeValue, numElts,
3370 cir::OverflowFlags::NoUnsignedWrap);
3371 }
3372
3373 return numElts;
3374 }
3375 }
3376 } else if (e->getKind() == UETT_OpenMPRequiredSimdAlign) {
3378 cgf.getContext()
3381 .getQuantity();
3382 return builder.getConstantInt(loc, cgf.cgm.sizeTy, alignment);
3383 } else if (e->getKind() == UETT_VectorElements) {
3384 auto vecTy = cast<cir::VectorType>(convertType(e->getTypeOfArgument()));
3385 if (vecTy.isScalable()) {
3387 e->getSourceRange(),
3388 "VisitUnaryExprOrTypeTraitExpr: sizeOf scalable vector");
3389 return builder.getConstant(
3390 loc, cir::IntAttr::get(cgf.cgm.sizeTy,
3392 }
3393
3394 return builder.getConstant(
3395 loc, cir::IntAttr::get(cgf.cgm.sizeTy, vecTy.getFixedSize()));
3396 }
3397
3398 // The result type is size_t (target-dependent width); use it so the IntAttr
3399 // width matches the APInt from EvaluateKnownConstInt.
3400 return builder.getConstant(
3401 loc, cir::IntAttr::get(cgf.cgm.sizeTy,
3403}
3404
3405mlir::Value ScalarExprEmitter::VisitAbstractConditionalOperator(
3406 const AbstractConditionalOperator *e) {
3407 CIRGenBuilderTy &builder = cgf.getBuilder();
3408 mlir::Location loc = cgf.getLoc(e->getSourceRange());
3409 ignoreResultAssign = false;
3410
3411 // Bind the common expression if necessary.
3412 CIRGenFunction::OpaqueValueMapping binding(cgf, e);
3413
3414 Expr *condExpr = e->getCond();
3415 Expr *lhsExpr = e->getTrueExpr();
3416 Expr *rhsExpr = e->getFalseExpr();
3417
3418 // If the condition constant folds and can be elided, try to avoid emitting
3419 // the condition and the dead arm.
3420 bool condExprBool;
3421 if (cgf.constantFoldsToBool(condExpr, condExprBool)) {
3422 Expr *live = lhsExpr, *dead = rhsExpr;
3423 if (!condExprBool)
3424 std::swap(live, dead);
3425
3426 // If the dead side doesn't have labels we need, just emit the Live part.
3427 if (!cgf.containsLabel(dead)) {
3428 if (condExprBool)
3430 mlir::Value result = Visit(live);
3431
3432 // If the live part is a throw expression, it acts like it has a void
3433 // type, so evaluating it returns a null Value. However, a conditional
3434 // with non-void type must return a non-null Value.
3435 if (!result && !e->getType()->isVoidType()) {
3436 result = builder.getConstant(
3437 loc, cir::PoisonAttr::get(builder.getContext(),
3438 cgf.convertType(e->getType())));
3439 }
3440
3441 return result;
3442 }
3443 }
3444
3445 QualType condType = condExpr->getType();
3446
3447 // OpenCL: If the condition is a vector, we can treat this condition like
3448 // the select function.
3449 if (cgf.getLangOpts().OpenCL &&
3450 (condType->isVectorType() || condType->isExtVectorType())) {
3452
3453 mlir::Value condValue = cgf.emitScalarExpr(condExpr);
3454 mlir::Value lhsValue = Visit(lhsExpr);
3455 mlir::Value rhsValue = Visit(rhsExpr);
3456
3457 // Test the MSB with a signed compare, as classic codegen does.
3458 mlir::Type vecTy =
3459 convertType(cgf.getContext().getCorrespondingSignedType(condType));
3460 condValue = builder.createBitcast(condValue, vecTy);
3461 mlir::Value zeroVec = builder.getNullValue(vecTy, loc);
3462 auto testMSB = cir::VecCmpOp::create(
3463 builder, loc, vecTy, cir::CmpOpKind::lt, condValue, zeroVec);
3464 mlir::Value tmp = builder.createIntCast(testMSB, vecTy);
3465 mlir::Value tmp2 = builder.createNot(tmp);
3466
3467 // Bitcast float or differently signed operands to the condition type.
3468 mlir::Value rhsTmp = rhsValue;
3469 mlir::Value lhsTmp = lhsValue;
3470 bool wasCast = false;
3471 if (rhsValue.getType() != vecTy) {
3472 rhsTmp = builder.createBitcast(rhsValue, tmp2.getType());
3473 lhsTmp = builder.createBitcast(lhsValue, tmp.getType());
3474 wasCast = true;
3475 }
3476
3477 mlir::Value tmp3 = builder.createAnd(loc, rhsTmp, tmp2);
3478 mlir::Value tmp4 = builder.createAnd(loc, lhsTmp, tmp);
3479 mlir::Value tmp5 = builder.createOr(loc, tmp3, tmp4);
3480 if (wasCast)
3481 tmp5 = builder.createBitcast(tmp5, rhsValue.getType());
3482 return tmp5;
3483 }
3484
3485 if (condType->isVectorType() || condType->isSveVLSBuiltinType()) {
3486 if (!condType->isVectorType()) {
3488 cgf.cgm.errorNYI(loc, "TernaryOp for SVE vector");
3489 return {};
3490 }
3491
3492 mlir::Value condValue = Visit(condExpr);
3493 mlir::Value lhsValue = Visit(lhsExpr);
3494 mlir::Value rhsValue = Visit(rhsExpr);
3495 return cir::VecTernaryOp::create(builder, loc, condValue, lhsValue,
3496 rhsValue);
3497 }
3498
3499 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3500 // select instead of as control flow. We can only do this if it is cheap
3501 // and safe to evaluate the LHS and RHS unconditionally.
3503 cgf.getContext()) &&
3505 cgf.getContext())) {
3506 mlir::Value condV = cgf.evaluateExprAsBool(condExpr);
3508
3509 mlir::Value lhs = Visit(lhsExpr);
3510 mlir::Value rhs = Visit(rhsExpr);
3511 if (!lhs) {
3512 // If the conditional has void type, make sure we return a null Value.
3513 assert(!rhs && "lhs and rhs types must match");
3514 return {};
3515 }
3516
3517 return builder.createSelect(loc, condV, lhs, rhs);
3518 }
3519
3520 mlir::Value condV = cgf.emitOpOnBoolExpr(loc, condExpr);
3521 CIRGenFunction::ConditionalEvaluation eval(cgf, loc);
3522
3523 auto emitBranch = [&](mlir::OpBuilder &b, mlir::Location loc, Expr *expr) {
3524 CIRGenFunction::LexicalScope lexScope{cgf, loc, b.getInsertionBlock()};
3526
3527 mlir::Value branch;
3528 {
3529 // Emit any cleanups that were needed on this branch so we can spill
3530 // and reload the return value.
3531 CIRGenFunction::RunCleanupsScope branchCleanups(cgf);
3533 eval.beginEvaluation();
3534 branch = Visit(expr);
3535 eval.endEvaluation();
3536 branchCleanups.forceCleanup({&branch});
3537 }
3538
3539 if (branch)
3540 cir::YieldOp::create(b, loc, branch);
3541 };
3542
3543 cir::TernaryOp ternary = cir::TernaryOp::create(
3544 builder, loc, condV,
3545 /*trueBuilder=*/
3546 [&](mlir::OpBuilder &b, mlir::Location loc) {
3547 emitBranch(b, loc, lhsExpr);
3548 },
3549 /*falseBuilder=*/
3550 [&](mlir::OpBuilder &b, mlir::Location loc) {
3551 emitBranch(b, loc, rhsExpr);
3552 });
3553
3554 // Only a void arm can be left unterminated (a noreturn arm already ends
3555 // in cir.unreachable); close it with an empty cir.yield.
3556 for (mlir::Region *region :
3557 {&ternary.getTrueRegion(), &ternary.getFalseRegion()}) {
3558 mlir::Block &lastBlock = region->back();
3559 if (lastBlock.empty() ||
3560 !lastBlock.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
3561 mlir::OpBuilder::InsertionGuard guard(builder);
3562 builder.setInsertionPointToEnd(&lastBlock);
3563 cir::YieldOp::create(builder, loc);
3564 }
3565 }
3566
3567 return ternary.getResult();
3568}
3569
3571 LValue lv) {
3572 return ScalarExprEmitter(*this, builder).emitScalarPrePostIncDec(e, lv);
3573}
static Value * createCastsForTypeOfSameSize(CGBuilderTy &Builder, const llvm::DataLayout &DL, Value *Src, llvm::Type *DstTy, StringRef Name="")
#define HANDLE_BINOP(OP)
static bool mustVisitNullValue(const Expr *e)
#define COMPOUND_OP(Op)
#define HANDLEBINOP(OP)
static bool isWidenedIntegerOp(const ASTContext &astContext, const Expr *e)
Check if e is a widened promoted integer.
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static mlir::Value tryEmitFMulAdd(mlir::Location loc, const BinOpInfo &op, CIRGenBuilderTy &builder, bool isSub=false)
static mlir::Value buildFMulAdd(mlir::Location addLoc, cir::FMulOp mulOp, mlir::Value addend, CIRGenBuilderTy &builder, bool negMul, bool negAdd)
static bool canElideOverflowCheck(const ASTContext &astContext, const BinOpInfo &op)
Check if we can skip the overflow check for Op.
static std::optional< QualType > getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e)
If e is a widened promoted integer, get its base (unpromoted) type.
#define VISITCOMP(CODE)
static bool isIntegerVectorBinOp(mlir::Type ty)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
mlir::Value createNSWSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::ConstantOp getBool(bool state, mlir::Location loc)
mlir::Value createDiv(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
mlir::Value getConstAPInt(mlir::Location loc, mlir::Type typ, const llvm::APInt &val)
mlir::Value createSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
mlir::Value createNSWAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::ConstantOp getNullValue(mlir::Type ty, mlir::Location loc)
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
mlir::Value createOr(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createCast(mlir::Location loc, cir::CastKind kind, mlir::Value src, mlir::Type newTy)
mlir::Value createIntToPtr(mlir::Value src, mlir::Type newTy)
mlir::Value createPtrToInt(mlir::Value src, mlir::Type newTy)
mlir::Value createFDiv(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::PointerType getPointerTo(mlir::Type ty)
cir::VecFCmpOp createVecFCompare(mlir::Location loc, cir::FCmpOpKind kind, mlir::Value lhs, mlir::Value rhs, bool signaling=false)
Compares lhs and rhs element-wise.
mlir::Value createFNeg(mlir::Location loc, mlir::Value operand)
mlir::Value createMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
mlir::Value createFAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createComplexImag(mlir::Location loc, mlir::Value operand)
mlir::Value createNSWMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::GetGlobalOp createGetGlobal(mlir::Location loc, cir::GlobalOp global, bool threadLocal=false)
mlir::Value createShiftLeft(mlir::Location loc, mlir::Value lhs, unsigned bits)
mlir::Value createAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::VecCmpOp createVecCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
Compares lhs and rhs element-wise.
mlir::Value createIntCast(mlir::Value src, mlir::Type newTy)
mlir::Value createInsertElement(mlir::Location loc, mlir::Value vec, mlir::Value newElt, uint64_t idx)
cir::FastMathFlagsAttr getFastMathFlagsAttr()
Returns a null attribute when no fast-math flags are set.
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
mlir::Value createFMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createNot(mlir::Location loc, mlir::Value value)
mlir::Value createSelect(mlir::Location loc, mlir::Value condition, mlir::Value trueValue, mlir::Value falseValue)
cir::ConstantOp getConstantInt(mlir::Location loc, mlir::Type ty, int64_t value)
mlir::Value createFRem(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createShiftRight(mlir::Location loc, mlir::Value lhs, unsigned bits)
mlir::Value createFSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createComplexReal(mlir::Location loc, mlir::Value operand)
mlir::Type getIntPtrType(mlir::Type ty) const
llvm::APInt getValue() const
APSInt & getInt()
Definition APValue.h:577
bool isLValue() const
Definition APValue.h:554
bool isNullPointer() const
Definition APValue.cpp:1173
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CanQualType FloatTy
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
QualType getCorrespondingSignedType(QualType T) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
LabelDecl * getLabel() const
Definition Expr.h:4642
uint64_t getValue() const
Definition ExprCXX.h:3059
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:6838
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
SourceLocation getExprLoc() const
Definition Expr.h:4148
bool isShiftOp() const
Definition Expr.h:4196
Expr * getRHS() const
Definition Expr.h:4159
bool isShiftAssignOp() const
Definition Expr.h:4265
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4320
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition Expr.cpp:2242
Opcode getOpcode() const
Definition Expr.h:4152
BinaryOperatorKind Opcode
Definition Expr.h:4112
mlir::Value getPointer() const
Definition Address.h:98
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
clang::CharUnits getAlignment() const
Definition Address.h:138
std::pair< mlir::Value, mlir::Value > splatMatrixOpOperandsIfNecessary(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::VecShuffleOp createVecShuffle(mlir::Location loc, mlir::Value vec1, mlir::Value vec2, llvm::ArrayRef< mlir::Attribute > maskAttrs)
mlir::Value createNeg(mlir::Location loc, mlir::Value value, bool nsw=false)
cir::MatrixMultiplyOp createMatrixMultiply(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
Multiply an MxK matrix by a KxN matrix, producing an MxN matrix.
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
static bool hasScalarEvaluationKind(clang::QualType type)
mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy, QualType dstTy, SourceLocation loc)
Emit a conversion from the specified complex type to the specified destination type,...
mlir::Type convertType(clang::QualType t)
mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType)
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
void emitVariablyModifiedType(QualType ty)
const clang::LangOptions & getLangOpts() const
VlaSizePair getVLASize(const VariableArrayType *type)
Returns an MLIR::Value+QualType pair that corresponds to the size, in non-variably-sized elements,...
LValue emitScalarCompoundAssignWithComplex(const CompoundAssignOperator *e, mlir::Value &result)
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
RValue emitCallExpr(const clang::CallExpr *e, ReturnValueSlot returnValue=ReturnValueSlot())
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
mlir::Value evaluateExprAsBool(const clang::Expr *e)
Perform the usual unary conversions on the specified expression and compare the result against zero,...
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool, bool allowLabels=false)
If the specified expression does not fold to a constant, or if it does but contains a label,...
mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond)
TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const
mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType, clang::QualType dstType, clang::SourceLocation loc)
Emit a conversion from the specified type to the specified destination type, both of which are CIR sc...
Address getAddressOfDerivedClass(mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue)
clang::SanitizerSet sanOpts
Sanitizers enabled for this function.
mlir::Type convertTypeForMem(QualType t)
LValue emitCompoundAssignmentLValue(const clang::CompoundAssignOperator *e)
mlir::Value getAsNaturalPointerTo(Address addr, QualType pointeeType)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType)
bool shouldNullCheckClassCastValue(const CastExpr *ce)
CIRGenBuilderTy & getBuilder()
mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv)
bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts=false)
Return true if the statement contains a label in it.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr)
Try to emit a reference to the given value without producing it as an l-value.
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
Address emitArrayToPointerDecay(const Expr *e, LValueBaseInfo *baseInfo=nullptr)
mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult)
clang::ASTContext & getContext() const
mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e)
void emitNullabilityCheck(LValue lhs, mlir::Value rhs, clang::SourceLocation loc)
Given an assignment *lhs = rhs, emit a test that checks if rhs is nonnull, if 1LHS is marked _Nonnull...
void emitStoreThroughLValue(RValue src, LValue dst, bool isInit=false)
Store the specified rvalue into the specified lvalue, where both are guaranteed to the have the same ...
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce)
mlir::Value getNullPointer(cir::PointerType ptrTy, QualType qt, mlir::Location loc)
Get target specific null pointer.
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *derivedClass, llvm::iterator_range< CastExpr::path_const_iterator > path)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
mlir::IntegerAttr getSize(CharUnits size)
cir::GlobalOp createGlobalString(mlir::Location loc, llvm::StringRef str, llvm::StringRef name)
Create a private constant global holding the null-terminated string str, mirroring llvm::IRBuilder::C...
const cir::CIRDataLayout & getDataLayout() const
const clang::CodeGenOptions & getCodeGenOpts() const
mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt)
Returns a null attribute to represent either a null method or null data member, depending on the type...
mlir::Value getPointer() const
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool getValue() const
Definition ExprCXX.h:745
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
bool getValue() const
Definition ExprCXX.h:4386
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:309
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
CastKind getCastKind() const
Definition Expr.h:3789
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3832
bool changesVolatileQualification() const
Return.
Definition Expr.h:3879
static const char * getCastKindName(CastKind CK)
Definition Expr.cpp:1987
Expr * getSubExpr()
Definition Expr.h:3795
int64_t QuantityType
Definition CharUnits.h:40
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
unsigned getValue() const
Definition Expr.h:1674
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4369
QualType getComputationLHSType() const
Definition Expr.h:4403
QualType getComputationResultType() const
Definition Expr.h:4406
SourceLocation getExprLoc() const LLVM_READONLY
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1202
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4878
ChildElementIter< false > begin()
Definition Expr.h:5310
size_t getDataElementCount() const
Definition Expr.h:5226
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition Expr.h:289
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
bool allowFPContractWithinStatement() const
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1620
llvm::APFloat getValue() const
Definition Expr.h:1711
const Expr * getSubExpr() const
Definition Expr.h:1107
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6554
unsigned getNumInits() const
Definition Expr.h:5410
bool hadArrayRangeDesignator() const
Definition Expr.h:5569
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
bool isSignedOverflowDefined() const
Expr * getBase() const
Definition Expr.h:3510
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3628
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:247
SourceRange getSourceRange() const
Definition ExprObjC.h:1754
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:189
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:414
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:1253
Expr * getSelectedExpr() const
Definition ExprCXX.h:4693
const Expr * getSubExpr() const
Definition Expr.h:2268
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8630
bool UseExcessPrecision(const ASTContext &Ctx)
Definition Type.cpp:1775
bool isCanonical() const
Definition TypeBase.h:8635
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool isSatisfied() const
Whether or not the requires clause is satisfied.
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:597
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4745
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4751
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4569
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2319
SourceLocation getLocation() const
Definition Expr.h:5139
Encodes a location in the source.
SourceLocation getBegin() const
CompoundStmt * getSubStmt()
Definition Expr.h:4681
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
const char * getStmtClassName() const
Definition Stmt.cpp:86
bool getBoolValue() const
Definition ExprCXX.h:2962
const APValue & getAPValue() const
Definition ExprCXX.h:2967
bool isStoredAsBoolean() const
Definition ExprCXX.h:2954
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2417
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2394
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:2080
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2836
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2506
bool isExtVectorType() const
Definition TypeBase.h:8958
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
bool isHalfType() const
Definition TypeBase.h:9208
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9280
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2438
bool isMatrixType() const
Definition TypeBase.h:8978
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8900
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2535
bool isFloatingType() const
Definition Type.cpp:2519
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2462
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2763
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2726
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
SourceLocation getExprLoc() const
Definition Expr.h:2437
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2395
static bool isDecrementOp(Opcode Op)
Definition Expr.h:2402
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:2469
static bool isPrefix(Opcode Op)
isPrefix - Return true if this is a prefix operation, like –x.
Definition Expr.h:2388
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2367
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4398
VectorKind getVectorKind() const
Definition TypeBase.h:4418
bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, const ASTContext &Ctx)
Check whether E is cheap enough and side-effect-free enough to evaluate unconditionally instead of co...
Definition ExprUtils.cpp:87
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
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
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CastKind
CastKind - The kind of operation required for a conversion.
inits_range inits()
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
U cast(CodeGen::Address addr)
Definition Address.h:327
__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
#define false
Definition stdbool.h:26
static bool instrumentation()
static bool dataMemberType()
static bool objCLifetime()
static bool vecTernaryOp()
static bool addHeapAllocSiteMetadata()
static bool mayHaveIntegerOverflow()
static bool emitMatrixIndexAssumption()
static bool openMPLastprivateConditional()
static bool llvmLoweringPtrDiffConsidersPointee()
static bool scalableVectors()
static bool memberFuncPtrAuthInfo()
static bool emitLValueAlignmentAssumption()
static bool incrementProfileCounter()
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174