clang 24.0.0git
CGExprAgg.cpp
Go to the documentation of this file.
1//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Aggregate Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGDebugInfo.h"
15#include "CGHLSLRuntime.h"
16#include "CGObjCRuntime.h"
17#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "ConstantEmitter.h"
21#include "EHScopeStack.h"
22#include "TargetInfo.h"
24#include "clang/AST/Attr.h"
25#include "clang/AST/DeclCXX.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Intrinsics.h"
35using namespace clang;
36using namespace CodeGen;
37
38//===----------------------------------------------------------------------===//
39// Aggregate Expression Emitter
40//===----------------------------------------------------------------------===//
41
42namespace {
43class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
44 CodeGenFunction &CGF;
45 CGBuilderTy &Builder;
46 AggValueSlot Dest;
47 bool IsResultUnused;
48
49 AggValueSlot EnsureSlot(QualType T) {
50 if (!Dest.isIgnored())
51 return Dest;
52 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
53 }
54 void EnsureDest(QualType T) {
55 if (!Dest.isIgnored())
56 return;
57 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
58 }
59
60 // Calls `Fn` with a valid return value slot, potentially creating a temporary
61 // to do so. If a temporary is created, an appropriate copy into `Dest` will
62 // be emitted, as will lifetime markers.
63 //
64 // The given function should take a ReturnValueSlot, and return an RValue that
65 // points to said slot.
66 void withReturnValueSlot(const Expr *E,
67 llvm::function_ref<RValue(ReturnValueSlot)> Fn);
68
69 void DoZeroInitPadding(uint64_t &PaddingStart, uint64_t PaddingEnd,
70 const FieldDecl *NextField);
71
72public:
73 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
74 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
75 IsResultUnused(IsResultUnused) {}
76
77 //===--------------------------------------------------------------------===//
78 // Utilities
79 //===--------------------------------------------------------------------===//
80
81 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
82 /// represents a value lvalue, this method emits the address of the lvalue,
83 /// then loads the result into DestPtr.
84 void EmitAggLoadOfLValue(const Expr *E);
85
86 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
87 /// SrcIsRValue is true if source comes from an RValue.
88 void EmitFinalDestCopy(QualType type, const LValue &src,
91 void EmitFinalDestCopy(QualType type, RValue src);
92 void EmitCopy(QualType type, const AggValueSlot &dest,
93 const AggValueSlot &src);
94
95 void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, QualType ArrayQTy,
96 Expr *ExprToVisit, ArrayRef<Expr *> Args,
97 Expr *ArrayFiller);
98
99 void EmitComparisonResult(const Expr *E,
100 const ComparisonCategoryInfo &CmpInfo,
101 llvm::Value *ResultValue);
102
103 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
104 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
107 }
108
109 bool TypeRequiresGCollection(QualType T);
110
111 //===--------------------------------------------------------------------===//
112 // Visitor Methods
113 //===--------------------------------------------------------------------===//
114
115 void Visit(Expr *E) {
116 ApplyDebugLocation DL(CGF, E);
117 StmtVisitor<AggExprEmitter>::Visit(E);
118 }
119
120 void VisitStmt(Stmt *S) { CGF.ErrorUnsupported(S, "aggregate expression"); }
121 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
122 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
123 Visit(GE->getResultExpr());
124 }
125 void VisitCoawaitExpr(CoawaitExpr *E) {
126 CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
127 }
128 void VisitCoyieldExpr(CoyieldExpr *E) {
129 CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
130 }
131 void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
132 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
133 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
134 return Visit(E->getReplacement());
135 }
136
137 void VisitConstantExpr(ConstantExpr *E) {
138 EnsureDest(E->getType());
139
140 if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
142 Result, E->getType(), Dest.getAddress(),
143 llvm::TypeSize::getFixed(
144 Dest.getPreferredSize(CGF.getContext(), E->getType())
145 .getQuantity()),
147 return;
148 }
149 return Visit(E->getSubExpr());
150 }
151
152 // l-values.
153 void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
154 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
155 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
156 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
157 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
158 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
159 EmitAggLoadOfLValue(E);
160 }
161 void VisitPredefinedExpr(const PredefinedExpr *E) { EmitAggLoadOfLValue(E); }
162
163 // Operators.
164 void VisitCastExpr(CastExpr *E);
165 void VisitCallExpr(const CallExpr *E);
166 void VisitStmtExpr(const StmtExpr *E);
167 void VisitBinaryOperator(const BinaryOperator *BO);
168 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
169 void VisitBinAssign(const BinaryOperator *E);
170 void VisitBinComma(const BinaryOperator *E);
171 void VisitBinCmp(const BinaryOperator *E);
172 void VisitTypeTraitExpr(const TypeTraitExpr *E);
173 void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
174 Visit(E->getSemanticForm());
175 }
176
177 void VisitObjCMessageExpr(ObjCMessageExpr *E);
178 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { EmitAggLoadOfLValue(E); }
179
180 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
181 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
182 void VisitChooseExpr(const ChooseExpr *CE);
183 void VisitInitListExpr(InitListExpr *E);
184 void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
185 FieldDecl *InitializedFieldInUnion,
186 Expr *ArrayFiller);
187 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
188 llvm::Value *outerBegin = nullptr);
189 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
190 void VisitNoInitExpr(NoInitExpr *E) {} // Do nothing.
191 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
192 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
193 Visit(DAE->getExpr());
194 }
195 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
196 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
197 Visit(DIE->getExpr());
198 }
199 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
200 void VisitCXXConstructExpr(const CXXConstructExpr *E);
201 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
202 void VisitLambdaExpr(LambdaExpr *E);
203 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
204 void VisitExprWithCleanups(ExprWithCleanups *E);
205 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
206 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
207 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
208 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
209
210 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
211 if (E->isGLValue()) {
212 LValue LV = CGF.EmitPseudoObjectLValue(E);
213 return EmitFinalDestCopy(E->getType(), LV);
214 }
215
216 AggValueSlot Slot = EnsureSlot(E->getType());
217 bool NeedsDestruction =
218 !Slot.isExternallyDestructed() &&
220 if (NeedsDestruction)
222 CGF.EmitPseudoObjectRValue(E, Slot);
223 if (NeedsDestruction)
225 E->getType());
226 }
227
228 void VisitVAArgExpr(VAArgExpr *E);
229 void VisitCXXParenListInitExpr(CXXParenListInitExpr *E);
230
231 void EmitInitializationToLValue(Expr *E, LValue Address);
232 void EmitNullInitializationToLValue(LValue Address);
233 // case Expr::ChooseExprClass:
234 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
235 void VisitAtomicExpr(AtomicExpr *E) {
236 RValue Res = CGF.EmitAtomicExpr(E);
237 EmitFinalDestCopy(E->getType(), Res);
238 }
239 void VisitPackIndexingExpr(PackIndexingExpr *E) {
240 Visit(E->getSelectedExpr());
241 }
242};
243} // end anonymous namespace.
244
245//===----------------------------------------------------------------------===//
246// Utilities
247//===----------------------------------------------------------------------===//
248
249/// EmitAggLoadOfLValue - Given an expression with aggregate type that
250/// represents a value lvalue, this method emits the address of the lvalue,
251/// then loads the result into DestPtr.
252void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
254
255 // If the type of the l-value is atomic, then do an atomic load.
256 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
257 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
258 return;
259 }
260
261 if (E->getType().getAddressSpace() == LangAS::hlsl_constant)
262 if (CGF.CGM.getHLSLRuntime().emitBufferCopy(CGF, E, LV, Dest))
263 return;
264
265 EmitFinalDestCopy(E->getType(), LV);
266}
267
268/// True if the given aggregate type requires special GC API calls.
269bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
270 // Only record types have members that might require garbage collection.
271 const auto *Record = T->getAsRecordDecl();
272 if (!Record)
273 return false;
274
275 // Don't mess with non-trivial C++ types.
277 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
278 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
279 return false;
280
281 // Check whether the type has an object member.
282 return Record->hasObjectMember();
283}
284
285void AggExprEmitter::withReturnValueSlot(
286 const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
287 QualType RetTy = E->getType();
288 bool RequiresDestruction =
289 !Dest.isExternallyDestructed() &&
291
292 // If it makes no observable difference, save a memcpy + temporary.
293 //
294 // We need to always provide our own temporary if destruction is required.
295 // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
296 // its lifetime before we have the chance to emit a proper destructor call.
297 //
298 // We also need a temporary if the destination is in a different address space
299 // from the sret AS. Use the target hook to get the actual sret AS for this
300 // return type.
301 const CXXRecordDecl *RD = RetTy->getAsCXXRecordDecl();
302 LangAS SRetLangAS = CGF.CGM.getTargetCodeGenInfo().getSRetAddrSpace(RD);
303 unsigned SRetAS = CGF.getContext().getTargetAddressSpace(SRetLangAS);
304 bool CanAggregateCopy =
305 RD ? (RD->hasTrivialCopyConstructor() ||
307 RD->hasTrivialMoveAssignment() || RD->hasAttr<TrivialABIAttr>() ||
308 RD->isUnion())
309 : RetTy.isTriviallyCopyableType(CGF.getContext());
310 bool DestASMismatch = !Dest.isIgnored() && CanAggregateCopy &&
311 Dest.getAddress()
313 ->stripPointerCasts()
314 ->getType()
315 ->getPointerAddressSpace() != SRetAS;
316 bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
317 (RequiresDestruction && Dest.isIgnored()) || DestASMismatch;
318
319 Address RetAddr = Address::invalid();
320
321 EHScopeStack::stable_iterator LifetimeEndBlock;
322 llvm::IntrinsicInst *LifetimeStartInst = nullptr;
323 if (!UseTemp) {
324 RetAddr = Dest.getAddress();
325 if (RetAddr.isValid() && RetAddr.getAddressSpace() != SRetAS) {
326 llvm::Type *SRetPtrTy =
327 llvm::PointerType::get(CGF.getLLVMContext(), SRetAS);
328 RetAddr = RetAddr.withPointer(
329 CGF.performAddrSpaceCast(RetAddr.getBasePointer(), SRetPtrTy),
330 RetAddr.isKnownNonNull());
331 }
332 } else {
333 RetAddr = CGF.CreateMemTempWithoutCast(RetTy, "tmp");
334 if (CGF.EmitLifetimeStart(RetAddr.getBasePointer())) {
335 LifetimeStartInst =
336 cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
337 assert(LifetimeStartInst->getIntrinsicID() ==
338 llvm::Intrinsic::lifetime_start &&
339 "Last insertion wasn't a lifetime.start?");
340
341 CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
342 NormalEHLifetimeMarker, RetAddr);
343 LifetimeEndBlock = CGF.EHStack.stable_begin();
344 }
345 }
346
347 RValue Src =
348 EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
349 Dest.isExternallyDestructed()));
350
351 if (!UseTemp)
352 return;
353
354 assert(Dest.isIgnored() || Dest.emitRawPointer(CGF) !=
355 Src.getAggregatePointer(E->getType(), CGF));
356 EmitFinalDestCopy(E->getType(), Src);
357
358 if (!RequiresDestruction && LifetimeStartInst) {
359 // If there's no dtor to run, the copy was the last use of our temporary.
360 // Since we're not guaranteed to be in an ExprWithCleanups, clean up
361 // eagerly.
362 CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
363 CGF.EmitLifetimeEnd(RetAddr.getBasePointer());
364 }
365}
366
367/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
368void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
369 assert(src.isAggregate() && "value must be aggregate value!");
370 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
371 EmitFinalDestCopy(type, srcLV, CodeGenFunction::EVK_RValue);
372}
373
374/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
375void AggExprEmitter::EmitFinalDestCopy(
376 QualType type, const LValue &src,
377 CodeGenFunction::ExprValueKind SrcValueKind) {
378 // If Dest is ignored, then we're evaluating an aggregate expression
379 // in a context that doesn't care about the result. Note that loads
380 // from volatile l-values force the existence of a non-ignored
381 // destination.
382 if (Dest.isIgnored())
383 return;
384
385 // Copy non-trivial C structs here.
386 LValue DstLV = CGF.MakeAddrLValue(
387 Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
388
389 if (SrcValueKind == CodeGenFunction::EVK_RValue) {
390 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
391 if (Dest.isPotentiallyAliased())
392 CGF.callCStructMoveAssignmentOperator(DstLV, src);
393 else
394 CGF.callCStructMoveConstructor(DstLV, src);
395 return;
396 }
397 } else {
398 if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
399 if (Dest.isPotentiallyAliased())
400 CGF.callCStructCopyAssignmentOperator(DstLV, src);
401 else
402 CGF.callCStructCopyConstructor(DstLV, src);
403 return;
404 }
405 }
406
407 AggValueSlot srcAgg = AggValueSlot::forLValue(
410 EmitCopy(type, Dest, srcAgg);
411}
412
413/// Perform a copy from the source into the destination.
414///
415/// \param type - the type of the aggregate being copied; qualifiers are
416/// ignored
417void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
418 const AggValueSlot &src) {
419 if (dest.requiresGCollection()) {
420 CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
421 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
423 src.getAddress(), size);
424 return;
425 }
426
427 // If the result of the assignment is used, copy the LHS there also.
428 // It's volatile if either side is. Use the minimum alignment of
429 // the two sides.
430 LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
431 LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
432 CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
433 dest.isVolatile() || src.isVolatile());
434}
435
436/// Emit the initializer for a std::initializer_list initialized with a
437/// real initializer list.
438void AggExprEmitter::VisitCXXStdInitializerListExpr(
439 CXXStdInitializerListExpr *E) {
440 // Emit an array containing the elements. The array is externally destructed
441 // if the std::initializer_list object is.
442 ASTContext &Ctx = CGF.getContext();
443 LValue Array = CGF.EmitLValue(E->getSubExpr());
444 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
445 Address ArrayPtr = Array.getAddress();
446
447 const ConstantArrayType *ArrayType =
449 assert(ArrayType && "std::initializer_list constructed from non-array");
450
451 auto *Record = E->getType()->castAsRecordDecl();
452 RecordDecl::field_iterator Field = Record->field_begin();
453 assert(Field != Record->field_end() &&
454 Ctx.hasSameType(Field->getType()->getPointeeType(),
455 ArrayType->getElementType()) &&
456 "Expected std::initializer_list first field to be const E *");
457
458 // Start pointer.
459 AggValueSlot Dest = EnsureSlot(E->getType());
460 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
461 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
462 llvm::Value *ArrayStart = ArrayPtr.emitRawPointer(CGF);
463 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
464 ++Field;
465 assert(Field != Record->field_end() &&
466 "Expected std::initializer_list to have two fields");
467
468 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
469 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
470 if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
471 // Length.
472 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
473
474 } else {
475 // End pointer.
476 assert(Field->getType()->isPointerType() &&
477 Ctx.hasSameType(Field->getType()->getPointeeType(),
478 ArrayType->getElementType()) &&
479 "Expected std::initializer_list second field to be const E *");
480 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
481 llvm::Value *IdxEnd[] = {Zero, Size};
482 llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(
483 ArrayPtr.getElementType(), ArrayPtr.emitRawPointer(CGF), IdxEnd,
484 "arrayend");
485 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
486 }
487
488 assert(++Field == Record->field_end() &&
489 "Expected std::initializer_list to only have two fields");
490}
491
492// emit an elementwise cast where the RHS is a scalar or vector
493// or emit an aggregate splat cast
495 LValue DestVal,
496 llvm::Value *SrcVal,
497 QualType SrcTy,
498 SourceLocation Loc) {
499 // Flatten our destination
500 SmallVector<LValue, 16> StoreList;
501 CGF.FlattenAccessAndTypeLValue(DestVal, StoreList);
502
503 bool isVector = false;
504 if (auto *VT = SrcTy->getAs<VectorType>()) {
505 isVector = true;
506 SrcTy = VT->getElementType();
507 assert(StoreList.size() <= VT->getNumElements() &&
508 "Cannot perform HLSL flat cast when vector source \
509 object has less elements than flattened destination \
510 object.");
511 }
512
513 for (unsigned I = 0, Size = StoreList.size(); I < Size; I++) {
514 LValue DestLVal = StoreList[I];
515 llvm::Value *Load =
516 isVector ? CGF.Builder.CreateExtractElement(SrcVal, I, "vec.load")
517 : SrcVal;
518 llvm::Value *Cast =
519 CGF.EmitScalarConversion(Load, SrcTy, DestLVal.getType(), Loc);
520 CGF.EmitStoreThroughLValue(RValue::get(Cast), DestLVal);
521 }
522}
523
524// emit a flat cast where the RHS is an aggregate
525static void EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue DestVal,
526 LValue SrcVal, SourceLocation Loc) {
527 // Flatten our destination
528 SmallVector<LValue, 16> StoreList;
529 CGF.FlattenAccessAndTypeLValue(DestVal, StoreList);
530 // Flatten our src
532 CGF.FlattenAccessAndTypeLValue(SrcVal, LoadList);
533
534 assert(StoreList.size() <= LoadList.size() &&
535 "Cannot perform HLSL elementwise cast when flattened source object \
536 has less elements than flattened destination object.");
537 // apply casts to what we load from LoadList
538 // and store result in Dest
539 for (unsigned I = 0, E = StoreList.size(); I < E; I++) {
540 LValue DestLVal = StoreList[I];
541 LValue SrcLVal = LoadList[I];
542 RValue RVal = CGF.EmitLoadOfLValue(SrcLVal, Loc);
543 assert(RVal.isScalar() && "All flattened source values should be scalars");
544 llvm::Value *Val = RVal.getScalarVal();
545 llvm::Value *Cast = CGF.EmitScalarConversion(Val, SrcLVal.getType(),
546 DestLVal.getType(), Loc);
547 CGF.EmitStoreThroughLValue(RValue::get(Cast), DestLVal);
548 }
549}
550
551/// Emit initialization of an array from an initializer list. ExprToVisit must
552/// be either an InitListEpxr a CXXParenInitListExpr.
553void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
554 QualType ArrayQTy, Expr *ExprToVisit,
555 ArrayRef<Expr *> Args, Expr *ArrayFiller) {
556 uint64_t NumInitElements = Args.size();
557
558 uint64_t NumArrayElements = AType->getNumElements();
559 for (const auto *Init : Args) {
560 if (const auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
561 NumInitElements += Embed->getDataElementCount() - 1;
562 if (NumInitElements > NumArrayElements) {
563 NumInitElements = NumArrayElements;
564 break;
565 }
566 }
567 }
568
569 assert(NumInitElements <= NumArrayElements);
570
571 QualType elementType =
572 CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
573 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
574 CharUnits elementAlign =
575 DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
576 llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
577
578 // Consider initializing the array by copying from a global. For this to be
579 // more efficient than per-element initialization, the size of the elements
580 // with explicit initializers should be large enough.
581 if (NumInitElements * elementSize.getQuantity() > 16 &&
582 elementType.isTriviallyCopyableType(CGF.getContext())) {
583 CodeGen::CodeGenModule &CGM = CGF.CGM;
584 ConstantEmitter Emitter(CGF);
585 QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(
586 CGM.getContext().removeAddrSpaceQualType(ArrayQTy),
588 LangAS AS = GVArrayQTy.getAddressSpace();
589 if (llvm::Constant *C =
590 Emitter.tryEmitForInitializer(ExprToVisit, AS, GVArrayQTy)) {
591 auto GV = new llvm::GlobalVariable(
592 CGM.getModule(), C->getType(),
593 /* isConstant= */ true, llvm::GlobalValue::PrivateLinkage, C,
594 "constinit",
595 /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
597 Emitter.finalize(GV);
598 CharUnits Align = CGM.getContext().getTypeAlignInChars(GVArrayQTy);
599 GV->setAlignment(Align.getAsAlign());
600 Address GVAddr(GV, GV->getValueType(), Align);
601 EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, GVArrayQTy));
602 return;
603 }
604 }
605
606 // Exception safety requires us to destroy all the
607 // already-constructed members if an initializer throws.
608 // For that, we'll need an EH cleanup.
609 QualType::DestructionKind dtorKind = elementType.isDestructedType();
610 Address endOfInit = Address::invalid();
611 CodeGenFunction::CleanupDeactivationScope deactivation(CGF);
612
613 llvm::Value *begin = DestPtr.emitRawPointer(CGF);
614 if (dtorKind) {
615 CodeGenFunction::AllocaTrackerRAII allocaTracker(CGF);
616 // In principle we could tell the cleanup where we are more
617 // directly, but the control flow can get so varied here that it
618 // would actually be quite complex. Therefore we go through an
619 // alloca.
620 llvm::Instruction *dominatingIP =
621 Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(CGF.Int8PtrTy));
622 endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
623 "arrayinit.endOfInit");
624 Builder.CreateStore(begin, endOfInit);
625 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
626 elementAlign,
627 CGF.getDestroyer(dtorKind));
629 .AddAuxAllocas(allocaTracker.Take());
630
632 {CGF.EHStack.stable_begin(), dominatingIP});
633 }
634
635 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
636
637 auto Emit = [&](Expr *Init, uint64_t ArrayIndex) {
638 llvm::Value *element = begin;
639 if (ArrayIndex > 0) {
640 if (CGF.getLangOpts().EmitLogicalPointer)
641 element = Builder.CreateStructuredGEP(
642 AType, begin, llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex),
643 "arrayinit.element");
644 else
645 element = Builder.CreateInBoundsGEP(
646 llvmElementType, begin,
647 llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex),
648 "arrayinit.element");
649
650 // Tell the cleanup that it needs to destroy up to this
651 // element. TODO: some of these stores can be trivially
652 // observed to be unnecessary.
653 if (endOfInit.isValid())
654 Builder.CreateStore(element, endOfInit);
655 }
656
657 LValue elementLV = CGF.MakeAddrLValue(
658 Address(element, llvmElementType, elementAlign), elementType);
659 EmitInitializationToLValue(Init, elementLV);
660 return true;
661 };
662
663 unsigned ArrayIndex = 0;
664 // Emit the explicit initializers.
665 for (uint64_t i = 0; i != NumInitElements; ++i) {
666 if (ArrayIndex >= NumInitElements)
667 break;
668 if (auto *EmbedS = dyn_cast<EmbedExpr>(Args[i]->IgnoreParenImpCasts())) {
669 EmbedS->doForEachDataElement(Emit, ArrayIndex);
670 } else {
671 Emit(Args[i], ArrayIndex);
672 ArrayIndex++;
673 }
674 }
675
676 // Check whether there's a non-trivial array-fill expression.
677 bool hasTrivialFiller = CodeGenUtils::isTrivialFiller(ArrayFiller);
678
679 // Any remaining elements need to be zero-initialized, possibly
680 // using the filler expression. We can skip this if the we're
681 // emitting to zeroed memory.
682 if (NumInitElements != NumArrayElements &&
683 !(Dest.isZeroed() && hasTrivialFiller &&
684 CGF.getTypes().isZeroInitializable(elementType))) {
685
686 // Use an actual loop. This is basically
687 // do { *array++ = filler; } while (array != end);
688
689 // Advance to the start of the rest of the array.
690 llvm::Value *element = begin;
691 if (NumInitElements) {
692 element = Builder.CreateInBoundsGEP(
693 llvmElementType, element,
694 llvm::ConstantInt::get(CGF.SizeTy, NumInitElements),
695 "arrayinit.start");
696 if (endOfInit.isValid())
697 Builder.CreateStore(element, endOfInit);
698 }
699
700 // Compute the end of the array.
701 llvm::Value *end = Builder.CreateInBoundsGEP(
702 llvmElementType, begin,
703 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");
704
705 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
706 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
707
708 // Jump into the body.
709 CGF.EmitBlock(bodyBB);
710 llvm::PHINode *currentElement =
711 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
712 currentElement->addIncoming(element, entryBB);
713
715 CGF.ConvergenceTokenStack.push_back(CGF.emitConvergenceLoopToken(bodyBB));
716
717 // Emit the actual filler expression.
718 {
719 // C++1z [class.temporary]p5:
720 // when a default constructor is called to initialize an element of
721 // an array with no corresponding initializer [...] the destruction of
722 // every temporary created in a default argument is sequenced before
723 // the construction of the next array element, if any
724 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
725 LValue elementLV = CGF.MakeAddrLValue(
726 Address(currentElement, llvmElementType, elementAlign), elementType);
727 if (ArrayFiller)
728 EmitInitializationToLValue(ArrayFiller, elementLV);
729 else
730 EmitNullInitializationToLValue(elementLV);
731 }
732
733 // Move on to the next element.
734 llvm::Value *nextElement = Builder.CreateInBoundsGEP(
735 llvmElementType, currentElement, one, "arrayinit.next");
736
737 // Tell the EH cleanup that we finished with the last element.
738 if (endOfInit.isValid())
739 Builder.CreateStore(nextElement, endOfInit);
740
741 // Leave the loop if we're done.
742 llvm::Value *done =
743 Builder.CreateICmpEQ(nextElement, end, "arrayinit.done");
744 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
745 Builder.CreateCondBr(done, endBB, bodyBB);
746 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
747
749 CGF.ConvergenceTokenStack.pop_back();
750
751 CGF.EmitBlock(endBB);
752 }
753}
754
755//===----------------------------------------------------------------------===//
756// Visitor Methods
757//===----------------------------------------------------------------------===//
758
759void AggExprEmitter::VisitMaterializeTemporaryExpr(
760 MaterializeTemporaryExpr *E) {
761 Visit(E->getSubExpr());
762}
763
764void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
765 // If this is a unique OVE, just visit its source expression.
766 if (e->isUnique())
767 Visit(e->getSourceExpr());
768 else
769 EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
770}
771
772void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
773 if (Dest.isPotentiallyAliased()) {
774 // Just emit a load of the lvalue + a copy, because our compound literal
775 // might alias the destination.
776 EmitAggLoadOfLValue(E);
777 return;
778 }
779
780 AggValueSlot Slot = EnsureSlot(E->getType());
781
782 // Block-scope compound literals are destroyed at the end of the enclosing
783 // scope in C.
784 bool Destruct =
785 !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();
786 if (Destruct)
788
789 CGF.EmitAggExpr(E->getInitializer(), Slot);
790
791 if (Destruct)
793 CGF.pushLifetimeExtendedDestroy(DtorKind, Slot.getAddress(),
794 E->getType());
795}
796
797/// Attempt to look through various unimportant expressions to find a
798/// cast of the given kind.
799static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
800 op = op->IgnoreParenNoopCasts(ctx);
801 if (auto castE = dyn_cast<CastExpr>(op)) {
802 if (castE->getCastKind() == kind)
803 return castE->getSubExpr();
804 }
805 return nullptr;
806}
807
808void AggExprEmitter::VisitCastExpr(CastExpr *E) {
809 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
810 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
811 switch (E->getCastKind()) {
812 case CK_Dynamic: {
813 // FIXME: Can this actually happen? We have no test coverage for it.
814 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
815 LValue LV =
817 // FIXME: Do we also need to handle property references here?
818 if (LV.isSimple())
819 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
820 else
821 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
822
823 if (!Dest.isIgnored())
824 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
825 break;
826 }
827
828 case CK_ToUnion: {
829 // Evaluate even if the destination is ignored.
830 if (Dest.isIgnored()) {
832 /*ignoreResult=*/true);
833 break;
834 }
835
836 // GCC union extension
837 QualType Ty = E->getSubExpr()->getType();
838 Address CastPtr = Dest.getAddress().withElementType(CGF.ConvertType(Ty));
839 EmitInitializationToLValue(E->getSubExpr(),
840 CGF.MakeAddrLValue(CastPtr, Ty));
841 break;
842 }
843
844 case CK_LValueToRValueBitCast: {
845 if (Dest.isIgnored()) {
847 /*ignoreResult=*/true);
848 break;
849 }
850
851 LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
852 Address SourceAddress = SourceLV.getAddress().withElementType(CGF.Int8Ty);
853 Address DestAddress = Dest.getAddress().withElementType(CGF.Int8Ty);
854 llvm::Value *SizeVal = llvm::ConstantInt::get(
855 CGF.SizeTy,
857 Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
858 break;
859 }
860
861 case CK_DerivedToBase: {
862 assert(CGF.getLangOpts().HLSL &&
863 "Derived/Base casts in EmitAggExpr are only supported in HLSL");
864
865 // Create a temporary for the derived record, switch it out with the current
866 // Dest slot, and emit the derived value.
867 QualType DerivedTy = E->getSubExpr()->getType();
868 RawAddress DerivedAddr = CGF.CreateMemTempWithoutCast(DerivedTy);
869 AggValueSlot DerivedTmpSlot = AggValueSlot::forAddr(
870 DerivedAddr, DerivedTy.getQualifiers(), AggValueSlot::IsNotDestructed,
873
874 AggValueSlot DestBaseSlot = Dest;
875 Dest = DerivedTmpSlot;
876
877 Visit(E->getSubExpr());
878
879 // Perform derived-to-base address conversion to get the address
880 // of the base record within the derived record. In HLSL this should
881 // always be same as the derived because of single inheritance, but let's
882 // do it properly.
883 Address BaseAddrInDerived = CGF.GetAddressOfBaseClass(
884 DerivedTmpSlot.getAddress(), DerivedTy->castAsCXXRecordDecl(),
885 E->path_begin(), E->path_end(),
886 /*NullCheckValue=*/false, E->getExprLoc());
887
888 AggValueSlot SrcBaseSlot = AggValueSlot::forAddr(
889 BaseAddrInDerived, E->getType().getQualifiers(),
892
893 // Copy the base class to the original destination slot and restore it.
894 EmitCopy(E->getType(), DestBaseSlot, SrcBaseSlot);
895 Dest = DestBaseSlot;
896 break;
897 }
898
899 case CK_BaseToDerived:
900 case CK_UncheckedDerivedToBase: {
901 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
902 "should have been unpacked before we got here");
903 }
904
905 case CK_NonAtomicToAtomic:
906 case CK_AtomicToNonAtomic: {
907 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
908
909 // Determine the atomic and value types.
910 QualType atomicType = E->getSubExpr()->getType();
911 QualType valueType = E->getType();
912 if (isToAtomic)
913 std::swap(atomicType, valueType);
914
915 assert(atomicType->isAtomicType());
917 valueType, atomicType->castAs<AtomicType>()->getValueType()));
918
919 // Just recurse normally if we're ignoring the result or the
920 // atomic type doesn't change representation.
921 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
922 return Visit(E->getSubExpr());
923 }
924
925 CastKind peepholeTarget =
926 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
927
928 // These two cases are reverses of each other; try to peephole them.
929 if (Expr *op =
930 findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
931 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
932 E->getType()) &&
933 "peephole significantly changed types?");
934 return Visit(op);
935 }
936
937 // If we're converting an r-value of non-atomic type to an r-value
938 // of atomic type, just emit directly into the relevant sub-object.
939 if (isToAtomic) {
940 AggValueSlot valueDest = Dest;
941 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
942 // Zero-initialize. (Strictly speaking, we only need to initialize
943 // the padding at the end, but this is simpler.)
944 if (!Dest.isZeroed())
946
947 // Build a GEP to refer to the subobject.
948 Address valueAddr =
949 CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
950 valueDest = AggValueSlot::forAddr(
951 valueAddr, valueDest.getQualifiers(),
952 valueDest.isExternallyDestructed(), valueDest.requiresGCollection(),
955 }
956
957 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
958 return;
959 }
960
961 // Otherwise, we're converting an atomic type to a non-atomic type.
962 // Make an atomic temporary, emit into that, and then copy the value out.
963 AggValueSlot atomicSlot =
964 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
965 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
966
967 Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
968 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
969 return EmitFinalDestCopy(valueType, rvalue);
970 }
971 case CK_AddressSpaceConversion:
972 return Visit(E->getSubExpr());
973
974 case CK_LValueToRValue:
975 // If we're loading from a volatile type, force the destination
976 // into existence.
977 if (E->getSubExpr()->getType().isVolatileQualified()) {
978 bool Destruct =
979 !Dest.isExternallyDestructed() &&
981 if (Destruct)
983 EnsureDest(E->getType());
984 Visit(E->getSubExpr());
985
986 if (Destruct)
988 E->getType());
989
990 return;
991 }
992
993 [[fallthrough]];
994
995 case CK_HLSLArrayRValue:
996 if (CGF.getLangOpts().HLSL &&
998 if (CGF.CGM.getHLSLRuntime().emitGlobalResourceArray(CGF, E, Dest))
999 break;
1000 Visit(E->getSubExpr());
1001 break;
1002 case CK_HLSLAggregateSplatCast: {
1003 Expr *Src = E->getSubExpr();
1004 QualType SrcTy = Src->getType();
1005 RValue RV = CGF.EmitAnyExpr(Src);
1006 LValue DestLVal = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1007 SourceLocation Loc = E->getExprLoc();
1008
1009 assert(RV.isScalar() && SrcTy->isScalarType() &&
1010 "RHS of HLSL splat cast must be a scalar.");
1011 llvm::Value *SrcVal = RV.getScalarVal();
1012 EmitHLSLScalarElementwiseAndSplatCasts(CGF, DestLVal, SrcVal, SrcTy, Loc);
1013 break;
1014 }
1015 case CK_HLSLElementwiseCast: {
1016 Expr *Src = E->getSubExpr();
1017 QualType SrcTy = Src->getType();
1018 RValue RV = CGF.EmitAnyExpr(Src);
1019 LValue DestLVal = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1020 SourceLocation Loc = E->getExprLoc();
1021
1022 if (RV.isScalar()) {
1023 llvm::Value *SrcVal = RV.getScalarVal();
1024 assert(SrcTy->isVectorType() &&
1025 "HLSL Elementwise cast doesn't handle splatting.");
1026 EmitHLSLScalarElementwiseAndSplatCasts(CGF, DestLVal, SrcVal, SrcTy, Loc);
1027 } else {
1028 assert(RV.isAggregate() &&
1029 "Can't perform HLSL Aggregate cast on a complex type.");
1030 Address SrcVal = RV.getAggregateAddress();
1031 EmitHLSLElementwiseCast(CGF, DestLVal, CGF.MakeAddrLValue(SrcVal, SrcTy),
1032 Loc);
1033 }
1034 break;
1035 }
1036 case CK_NoOp:
1037 case CK_UserDefinedConversion:
1038 case CK_ConstructorConversion:
1040 E->getType()) &&
1041 "Implicit cast types must be compatible");
1042 Visit(E->getSubExpr());
1043 break;
1044
1045 case CK_LValueBitCast:
1046 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
1047
1048 case CK_Dependent:
1049 case CK_BitCast:
1050 case CK_ArrayToPointerDecay:
1051 case CK_FunctionToPointerDecay:
1052 case CK_NullToPointer:
1053 case CK_NullToMemberPointer:
1054 case CK_BaseToDerivedMemberPointer:
1055 case CK_DerivedToBaseMemberPointer:
1056 case CK_MemberPointerToBoolean:
1057 case CK_ReinterpretMemberPointer:
1058 case CK_IntegralToPointer:
1059 case CK_PointerToIntegral:
1060 case CK_PointerToBoolean:
1061 case CK_ToVoid:
1062 case CK_VectorSplat:
1063 case CK_IntegralCast:
1064 case CK_BooleanToSignedIntegral:
1065 case CK_IntegralToBoolean:
1066 case CK_IntegralToFloating:
1067 case CK_FloatingToIntegral:
1068 case CK_FloatingToBoolean:
1069 case CK_FloatingCast:
1070 case CK_CPointerToObjCPointerCast:
1071 case CK_BlockPointerToObjCPointerCast:
1072 case CK_AnyPointerToBlockPointerCast:
1073 case CK_ObjCObjectLValueCast:
1074 case CK_FloatingRealToComplex:
1075 case CK_FloatingComplexToReal:
1076 case CK_FloatingComplexToBoolean:
1077 case CK_FloatingComplexCast:
1078 case CK_FloatingComplexToIntegralComplex:
1079 case CK_IntegralRealToComplex:
1080 case CK_IntegralComplexToReal:
1081 case CK_IntegralComplexToBoolean:
1082 case CK_IntegralComplexCast:
1083 case CK_IntegralComplexToFloatingComplex:
1084 case CK_ARCProduceObject:
1085 case CK_ARCConsumeObject:
1086 case CK_ARCReclaimReturnedObject:
1087 case CK_ARCExtendBlockObject:
1088 case CK_CopyAndAutoreleaseBlockObject:
1089 case CK_BuiltinFnToFnPtr:
1090 case CK_ZeroToOCLOpaqueType:
1091 case CK_MatrixCast:
1092 case CK_HLSLVectorTruncation:
1093 case CK_HLSLMatrixTruncation:
1094 case CK_IntToOCLSampler:
1095 case CK_FloatingToFixedPoint:
1096 case CK_FixedPointToFloating:
1097 case CK_FixedPointCast:
1098 case CK_FixedPointToBoolean:
1099 case CK_FixedPointToIntegral:
1100 case CK_IntegralToFixedPoint:
1101 llvm_unreachable("cast kind invalid for aggregate types");
1102 }
1103}
1104
1105void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
1106 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
1107 EmitAggLoadOfLValue(E);
1108 return;
1109 }
1110
1111 withReturnValueSlot(
1112 E, [&](ReturnValueSlot Slot) { return CGF.EmitCallExpr(E, Slot); });
1113}
1114
1115void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1116 withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
1117 return CGF.EmitObjCMessageExpr(E, Slot);
1118 });
1119}
1120
1121void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
1122 CGF.EmitIgnoredExpr(E->getLHS());
1123 Visit(E->getRHS());
1124}
1125
1126void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1127 CodeGenFunction::StmtExprEvaluation eval(CGF);
1128 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
1129}
1130
1136
1137static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
1138 const BinaryOperator *E, llvm::Value *LHS,
1139 llvm::Value *RHS, CompareKind Kind,
1140 const char *NameSuffix = "") {
1141 QualType ArgTy = E->getLHS()->getType();
1142 if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
1143 ArgTy = CT->getElementType();
1144
1145 if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
1146 assert(Kind == CK_Equal &&
1147 "member pointers may only be compared for equality");
1149 CGF, LHS, RHS, MPT, /*IsInequality*/ false);
1150 }
1151
1152 // Compute the comparison instructions for the specified comparison kind.
1153 struct CmpInstInfo {
1154 const char *Name;
1155 llvm::CmpInst::Predicate FCmp;
1156 llvm::CmpInst::Predicate SCmp;
1157 llvm::CmpInst::Predicate UCmp;
1158 };
1159 CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
1160 using FI = llvm::FCmpInst;
1161 using II = llvm::ICmpInst;
1162 switch (Kind) {
1163 case CK_Less:
1164 return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
1165 case CK_Greater:
1166 return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
1167 case CK_Equal:
1168 return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
1169 }
1170 llvm_unreachable("Unrecognised CompareKind enum");
1171 }();
1172
1173 if (ArgTy->hasFloatingRepresentation())
1174 return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
1175 llvm::Twine(InstInfo.Name) + NameSuffix);
1176 if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
1177 auto Inst =
1178 ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
1179 return Builder.CreateICmp(Inst, LHS, RHS,
1180 llvm::Twine(InstInfo.Name) + NameSuffix);
1181 }
1182
1183 llvm_unreachable("unsupported aggregate binary expression should have "
1184 "already been handled");
1185}
1186
1187void AggExprEmitter::EmitComparisonResult(const Expr *E,
1188 const ComparisonCategoryInfo &CmpInfo,
1189 llvm::Value *ResultValue) {
1190 // Create the return value in the destination slot.
1191 EnsureDest(E->getType());
1192 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1193
1194 // Emit the address of the first (and only) field in the comparison category
1195 // type, and initialize it from the constant integer value selected above.
1196 LValue FieldLV = CGF.EmitLValueForFieldInitialization(
1197 DestLV, *CmpInfo.Record->field_begin());
1198 CGF.EmitStoreThroughLValue(RValue::get(ResultValue), FieldLV,
1199 /*IsInit=*/true);
1200}
1201
1202void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
1203 using llvm::BasicBlock;
1204 using llvm::PHINode;
1205 using llvm::Value;
1206 assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
1207 E->getRHS()->getType()));
1208 const ComparisonCategoryInfo &CmpInfo =
1210 assert(CmpInfo.Record->isTriviallyCopyable() &&
1211 "cannot copy non-trivially copyable aggregate");
1212
1213 QualType ArgTy = E->getLHS()->getType();
1214
1215 if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
1216 !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
1217 !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
1218 return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
1219 }
1220 bool IsComplex = ArgTy->isAnyComplexType();
1221
1222 // Evaluate the operands to the expression and extract their values.
1223 auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
1224 RValue RV = CGF.EmitAnyExpr(E);
1225 if (RV.isScalar())
1226 return {RV.getScalarVal(), nullptr};
1227 if (RV.isAggregate())
1228 return {RV.getAggregatePointer(E->getType(), CGF), nullptr};
1229 assert(RV.isComplex());
1230 return RV.getComplexVal();
1231 };
1232 auto LHSValues = EmitOperand(E->getLHS()),
1233 RHSValues = EmitOperand(E->getRHS());
1234
1235 auto EmitCmp = [&](CompareKind K) {
1236 Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
1237 K, IsComplex ? ".r" : "");
1238 if (!IsComplex)
1239 return Cmp;
1240 assert(K == CompareKind::CK_Equal);
1241 Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
1242 RHSValues.second, K, ".i");
1243 return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
1244 };
1245 auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
1246 return Builder.getInt(VInfo->getIntValue());
1247 };
1248
1249 Value *Select;
1250 if (ArgTy->isNullPtrType()) {
1251 Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
1252 } else if (!CmpInfo.isPartial()) {
1253 Value *SelectOne =
1254 Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
1255 EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
1256 Select = Builder.CreateSelect(EmitCmp(CK_Equal),
1257 EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1258 SelectOne, "sel.eq");
1259 } else {
1260 Value *SelectEq = Builder.CreateSelect(
1261 EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1262 EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
1263 Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
1264 EmitCmpRes(CmpInfo.getGreater()),
1265 SelectEq, "sel.gt");
1266 Select = Builder.CreateSelect(
1267 EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
1268 }
1269
1270 EmitComparisonResult(E, CmpInfo, Select);
1271}
1272
1273void AggExprEmitter::VisitTypeTraitExpr(const TypeTraitExpr *E) {
1274 assert(E->isStoredAsComparisonResult() &&
1275 "expected a strong_ordering type trait with a stored value");
1276
1277 const ComparisonCategoryInfo &CmpInfo =
1279 const auto Result =
1280 ComparisonCategoryResult(E->getAPValue().getInt().getZExtValue());
1281 llvm::Value *ResultValue =
1282 Builder.getInt(CmpInfo.getValueInfo(Result)->getIntValue());
1283
1284 EmitComparisonResult(E, CmpInfo, ResultValue);
1285}
1286
1287void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
1288 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
1289 VisitPointerToDataMemberBinaryOperator(E);
1290 else
1291 CGF.ErrorUnsupported(E, "aggregate binary expression");
1292}
1293
1294void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
1295 const BinaryOperator *E) {
1296 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
1297 EmitFinalDestCopy(E->getType(), LV);
1298}
1299
1300void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1301 ApplyAtomGroup Grp(CGF.getDebugInfo());
1302 // For an assignment to work, the value on the right has
1303 // to be compatible with the value on the left.
1304 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1305 E->getRHS()->getType()) &&
1306 "Invalid assignment");
1307
1308 // If the LHS might be a __block variable, and the RHS can
1309 // potentially cause a block copy, we need to evaluate the RHS first
1310 // so that the assignment goes the right place.
1311 // This is pretty semantically fragile.
1313 E->getRHS()->HasSideEffects(CGF.getContext())) {
1314 // Ensure that we have a destination, and evaluate the RHS into that.
1315 EnsureDest(E->getRHS()->getType());
1316 Visit(E->getRHS());
1317
1318 // Now emit the LHS and copy into it.
1319 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1320
1321 // That copy is an atomic copy if the LHS is atomic.
1322 if (LHS.getType()->isAtomicType() ||
1324 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1325 return;
1326 }
1327
1328 EmitCopy(E->getLHS()->getType(),
1330 needsGC(E->getLHS()->getType()),
1333 Dest);
1334 return;
1335 }
1336
1337 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1338
1339 // If we have an atomic type, evaluate into the destination and then
1340 // do an atomic copy.
1341 if (LHS.getType()->isAtomicType() ||
1343 EnsureDest(E->getRHS()->getType());
1344 Visit(E->getRHS());
1345 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1346 return;
1347 }
1348
1349 // Codegen the RHS so that it stores directly into the LHS.
1350 AggValueSlot LHSSlot = AggValueSlot::forLValue(
1351 LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
1353 // A non-volatile aggregate destination might have volatile member.
1354 if (!LHSSlot.isVolatile() && CGF.hasVolatileMember(E->getLHS()->getType()))
1355 LHSSlot.setVolatile(true);
1356
1357 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
1358
1359 // Copy into the destination if the assignment isn't ignored.
1360 EmitFinalDestCopy(E->getType(), LHS);
1361
1362 if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
1365 E->getType());
1366}
1367
1368void AggExprEmitter::VisitAbstractConditionalOperator(
1369 const AbstractConditionalOperator *E) {
1370 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1371 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1372 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1373
1374 // Bind the common expression if necessary.
1375 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1376
1377 CodeGenFunction::ConditionalEvaluation eval(CGF);
1378 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1379 CGF.getProfileCount(E));
1380
1381 // Save whether the destination's lifetime is externally managed.
1382 bool isExternallyDestructed = Dest.isExternallyDestructed();
1383 bool destructNonTrivialCStruct =
1384 !isExternallyDestructed &&
1386 isExternallyDestructed |= destructNonTrivialCStruct;
1387 Dest.setExternallyDestructed(isExternallyDestructed);
1388
1389 eval.begin(CGF);
1390 CGF.EmitBlock(LHSBlock);
1392 Visit(E->getTrueExpr());
1393 eval.end(CGF);
1394
1395 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1396 CGF.Builder.CreateBr(ContBlock);
1397
1398 // If the result of an agg expression is unused, then the emission
1399 // of the LHS might need to create a destination slot. That's fine
1400 // with us, and we can safely emit the RHS into the same slot, but
1401 // we shouldn't claim that it's already being destructed.
1402 Dest.setExternallyDestructed(isExternallyDestructed);
1403
1404 eval.begin(CGF);
1405 CGF.EmitBlock(RHSBlock);
1407 Visit(E->getFalseExpr());
1408 eval.end(CGF);
1409
1410 if (destructNonTrivialCStruct)
1412 E->getType());
1413
1414 CGF.EmitBlock(ContBlock);
1415}
1416
1417void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
1418 Visit(CE->getChosenSubExpr());
1419}
1420
1421void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1422 Address ArgValue = Address::invalid();
1423 CGF.EmitVAArg(VE, ArgValue, Dest);
1424
1425 // If EmitVAArg fails, emit an error.
1426 if (!ArgValue.isValid()) {
1427 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1428 return;
1429 }
1430}
1431
1432void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1433 // Ensure that we have a slot, but if we already do, remember
1434 // whether it was externally destructed.
1435 bool wasExternallyDestructed = Dest.isExternallyDestructed();
1436 EnsureDest(E->getType());
1437
1438 // We're going to push a destructor if there isn't already one.
1440
1441 Visit(E->getSubExpr());
1442
1443 // Push that destructor we promised.
1444 if (!wasExternallyDestructed)
1445 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1446}
1447
1448void AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1449 AggValueSlot Slot = EnsureSlot(E->getType());
1450 CGF.EmitCXXConstructExpr(E, Slot);
1451}
1452
1453void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1454 const CXXInheritedCtorInitExpr *E) {
1455 AggValueSlot Slot = EnsureSlot(E->getType());
1457 Slot.getAddress(),
1458 E->inheritedFromVBase(), E);
1459}
1460
1461void AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1462 AggValueSlot Slot = EnsureSlot(E->getType());
1463 LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
1464
1465 // We'll need to enter cleanup scopes in case any of the element
1466 // initializers throws an exception or contains branch out of the expressions.
1467 CodeGenFunction::CleanupDeactivationScope scope(CGF);
1468
1469 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1471 e = E->capture_init_end();
1472 i != e; ++i, ++CurField) {
1473 // Emit initialization
1474 LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
1475 if (CurField->hasCapturedVLAType()) {
1476 CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
1477 continue;
1478 }
1479
1480 EmitInitializationToLValue(*i, LV);
1481
1482 // Push a destructor if necessary.
1483 if (QualType::DestructionKind DtorKind =
1484 CurField->getType().isDestructedType()) {
1485 assert(LV.isSimple());
1486 if (DtorKind)
1488 CurField->getType(),
1489 CGF.getDestroyer(DtorKind), false);
1490 }
1491 }
1492}
1493
1494void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1495 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1496 Visit(E->getSubExpr());
1497}
1498
1499void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1500 QualType T = E->getType();
1501 AggValueSlot Slot = EnsureSlot(T);
1502 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1503}
1504
1505void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1506 QualType T = E->getType();
1507 AggValueSlot Slot = EnsureSlot(T);
1508 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1509}
1510
1511void AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1512 QualType type = LV.getType();
1513 // FIXME: Ignore result?
1514 // FIXME: Are initializers affected by volatile?
1515 if (Dest.isZeroed() && CodeGenUtils::isSimpleZero(E, CGF)) {
1516 // Storing "i32 0" to a zero'd memory location is a noop.
1517 return;
1519 return EmitNullInitializationToLValue(LV);
1520 } else if (isa<NoInitExpr>(E)) {
1521 // Do nothing.
1522 return;
1523 } else if (type->isReferenceType()) {
1524 RValue RV = CGF.EmitReferenceBindingToExpr(E);
1525 return CGF.EmitStoreThroughLValue(RV, LV);
1526 }
1527
1528 CGF.EmitInitializationToLValue(E, LV, Dest.isZeroed());
1529}
1530
1531void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1532 QualType type = lv.getType();
1533
1534 // If the destination slot is already zeroed out before the aggregate is
1535 // copied into it, we don't have to emit any zeros here.
1536 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1537 return;
1538
1539 if (CGF.hasScalarEvaluationKind(type)) {
1540 // For non-aggregates, we can store the appropriate null constant.
1541 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1542 // Note that the following is not equivalent to
1543 // EmitStoreThroughBitfieldLValue for ARC types.
1544 if (lv.isBitField()) {
1546 } else {
1547 assert(lv.isSimple());
1548 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1549 }
1550 } else {
1551 // There's a potential optimization opportunity in combining
1552 // memsets; that would be easy for arrays, but relatively
1553 // difficult for structures with the current code.
1554 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1555 }
1556}
1557
1558void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
1559 VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
1561 E->getArrayFiller());
1562}
1563
1564void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1565 if (E->hadArrayRangeDesignator())
1566 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1567
1568 if (E->isTransparent())
1569 return Visit(E->getInit(0));
1570
1571 VisitCXXParenListOrInitListExpr(
1572 E, E->inits(), E->getInitializedFieldInUnion(), E->getArrayFiller());
1573}
1574
1575void AggExprEmitter::VisitCXXParenListOrInitListExpr(
1576 Expr *ExprToVisit, ArrayRef<Expr *> InitExprs,
1577 FieldDecl *InitializedFieldInUnion, Expr *ArrayFiller) {
1578#if 0
1579 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1580 // (Length of globals? Chunks of zeroed-out space?).
1581 //
1582 // If we can, prefer a copy from a global; this is a lot less code for long
1583 // globals, and it's easier for the current optimizers to analyze.
1584 if (llvm::Constant *C =
1585 CGF.CGM.EmitConstantExpr(ExprToVisit, ExprToVisit->getType(), &CGF)) {
1586 llvm::GlobalVariable* GV =
1587 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1588 llvm::GlobalValue::InternalLinkage, C, "");
1589 EmitFinalDestCopy(ExprToVisit->getType(),
1590 CGF.MakeAddrLValue(GV, ExprToVisit->getType()));
1591 return;
1592 }
1593#endif
1594
1595 // HLSL initialization lists in the AST are an expansion which can contain
1596 // side-effecting expressions wrapped in opaque value expressions. To properly
1597 // emit these we need to emit the opaque values before we emit the argument
1598 // expressions themselves. This is a little hacky, but it prevents us needing
1599 // to do a bigger AST-level change for a language feature that we need
1600 // deprecate in the near future. See related HLSL language proposals:
1601 // * 0005-strict-initializer-lists.md
1602 // * https://github.com/microsoft/hlsl-specs/pull/325
1603 if (CGF.getLangOpts().HLSL && isa<InitListExpr>(ExprToVisit))
1605 CGF, cast<InitListExpr>(ExprToVisit));
1606
1607 AggValueSlot Dest = EnsureSlot(ExprToVisit->getType());
1608
1609 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), ExprToVisit->getType());
1610
1611 // Handle initialization of an array.
1612 if (ExprToVisit->getType()->isConstantArrayType()) {
1613 auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1614 EmitArrayInit(Dest.getAddress(), AType, ExprToVisit->getType(), ExprToVisit,
1615 InitExprs, ArrayFiller);
1616 return;
1617 } else if (ExprToVisit->getType()->isVariableArrayType()) {
1618 // A variable array type that has an initializer can only do empty
1619 // initialization. And because this feature is not exposed as an extension
1620 // in C++, we can safely memset the array memory to zero.
1621 assert(InitExprs.size() == 0 &&
1622 "you can only use an empty initializer with VLAs");
1623 CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());
1624 return;
1625 }
1626
1627 assert(ExprToVisit->getType()->isRecordType() &&
1628 "Only support structs/unions here!");
1629
1630 // Do struct initialization; this code just sets each individual member
1631 // to the approprate value. This makes bitfield support automatic;
1632 // the disadvantage is that the generated code is more difficult for
1633 // the optimizer, especially with bitfields.
1634 unsigned NumInitElements = InitExprs.size();
1635 RecordDecl *record = ExprToVisit->getType()->castAsRecordDecl();
1636
1637 // We'll need to enter cleanup scopes in case any of the element
1638 // initializers throws an exception.
1639 CodeGenFunction::CleanupDeactivationScope DeactivateCleanups(CGF);
1640
1641 unsigned curInitIndex = 0;
1642
1643 // Emit initialization of base classes.
1644 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1645 assert(NumInitElements >= CXXRD->getNumBases() &&
1646 "missing initializer for base class");
1647 for (auto &Base : CXXRD->bases()) {
1648 assert(!Base.isVirtual() && "should not see vbases here");
1649 auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1651 Dest.getAddress(), CXXRD, BaseRD,
1652 /*isBaseVirtual*/ false);
1653 AggValueSlot AggSlot = AggValueSlot::forAddr(
1654 V, Qualifiers(), AggValueSlot::IsDestructed,
1656 CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
1657 CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot);
1658
1659 if (QualType::DestructionKind dtorKind =
1660 Base.getType().isDestructedType())
1661 CGF.pushDestroyAndDeferDeactivation(dtorKind, V, Base.getType());
1662 }
1663 }
1664
1665 // Prepare a 'this' for CXXDefaultInitExprs.
1666 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1667
1668 const bool ZeroInitPadding =
1669 CGF.CGM.shouldZeroInitPadding() && !Dest.isZeroed();
1670
1671 if (record->isUnion()) {
1672 // Only initialize one field of a union. The field itself is
1673 // specified by the initializer list.
1674 if (!InitializedFieldInUnion) {
1675 // Empty union; we have nothing to do.
1676
1677#ifndef NDEBUG
1678 // Make sure that it's really an empty and not a failure of
1679 // semantic analysis.
1680 for (const auto *Field : record->fields())
1681 assert(
1682 (Field->isUnnamedBitField() || Field->isAnonymousStructOrUnion()) &&
1683 "Only unnamed bitfields or anonymous class allowed");
1684#endif
1685 return;
1686 }
1687
1688 // FIXME: volatility
1689 FieldDecl *Field = InitializedFieldInUnion;
1690
1691 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1692 if (NumInitElements) {
1693 // Store the initializer into the field
1694 EmitInitializationToLValue(InitExprs[0], FieldLoc);
1695 if (ZeroInitPadding) {
1696 uint64_t TotalSize = CGF.getContext().toBits(
1697 Dest.getPreferredSize(CGF.getContext(), DestLV.getType()));
1698 uint64_t FieldSize = CGF.getContext().getTypeSize(FieldLoc.getType());
1699 DoZeroInitPadding(FieldSize, TotalSize, nullptr);
1700 }
1701 } else {
1702 // Default-initialize to null.
1703 if (ZeroInitPadding)
1704 EmitNullInitializationToLValue(DestLV);
1705 else
1706 EmitNullInitializationToLValue(FieldLoc);
1707 }
1708 return;
1709 }
1710
1711 // Here we iterate over the fields; this makes it simpler to both
1712 // default-initialize fields and skip over unnamed fields.
1713 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(record);
1714 uint64_t PaddingStart = 0;
1715
1716 for (const auto *field : record->fields()) {
1717 // We're done once we hit the flexible array member.
1718 if (field->getType()->isIncompleteArrayType())
1719 break;
1720
1721 // Always skip anonymous bitfields.
1722 if (field->isUnnamedBitField())
1723 continue;
1724
1725 // We're done if we reach the end of the explicit initializers, we
1726 // have a zeroed object, and the rest of the fields are
1727 // zero-initializable.
1728 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1729 CGF.getTypes().isZeroInitializable(ExprToVisit->getType()))
1730 break;
1731
1732 if (ZeroInitPadding)
1733 DoZeroInitPadding(PaddingStart,
1734 Layout.getFieldOffset(field->getFieldIndex()), field);
1735
1736 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1737 // We never generate write-barries for initialized fields.
1738 LV.setNonGC(true);
1739
1740 if (curInitIndex < NumInitElements) {
1741 // Store the initializer into the field.
1742 EmitInitializationToLValue(InitExprs[curInitIndex++], LV);
1743 } else {
1744 // We're out of initializers; default-initialize to null
1745 EmitNullInitializationToLValue(LV);
1746 }
1747
1748 // Push a destructor if necessary.
1749 // FIXME: if we have an array of structures, all explicitly
1750 // initialized, we can end up pushing a linear number of cleanups.
1751 if (QualType::DestructionKind dtorKind =
1752 field->getType().isDestructedType()) {
1753 assert(LV.isSimple());
1754 if (dtorKind) {
1756 field->getType(),
1757 CGF.getDestroyer(dtorKind), false);
1758 }
1759 }
1760 }
1761 if (ZeroInitPadding) {
1762 uint64_t TotalSize = CGF.getContext().toBits(
1763 Dest.getPreferredSize(CGF.getContext(), DestLV.getType()));
1764 DoZeroInitPadding(PaddingStart, TotalSize, nullptr);
1765 }
1766}
1767
1768void AggExprEmitter::DoZeroInitPadding(uint64_t &PaddingStart,
1769 uint64_t PaddingEnd,
1770 const FieldDecl *NextField) {
1771
1772 auto InitBytes = [&](uint64_t StartBit, uint64_t EndBit) {
1773 CharUnits Start = CGF.getContext().toCharUnitsFromBits(StartBit);
1774 CharUnits End = CGF.getContext().toCharUnitsFromBits(EndBit);
1776 if (!Start.isZero())
1777 Addr = Builder.CreateConstGEP(Addr, Start.getQuantity());
1778 llvm::Constant *SizeVal = Builder.getInt64((End - Start).getQuantity());
1779 CGF.Builder.CreateMemSet(Addr, Builder.getInt8(0), SizeVal, false);
1780 };
1781
1782 if (NextField != nullptr && NextField->isBitField()) {
1783 // For bitfield, zero init StorageSize before storing the bits. So we don't
1784 // need to handle big/little endian.
1785 const CGRecordLayout &RL =
1786 CGF.getTypes().getCGRecordLayout(NextField->getParent());
1787 const CGBitFieldInfo &Info = RL.getBitFieldInfo(NextField);
1788 uint64_t StorageStart = CGF.getContext().toBits(Info.StorageOffset);
1789 if (StorageStart + Info.StorageSize > PaddingStart) {
1790 if (StorageStart > PaddingStart)
1791 InitBytes(PaddingStart, StorageStart);
1792 Address Addr = Dest.getAddress();
1793 if (!Info.StorageOffset.isZero())
1794 Addr = Builder.CreateConstGEP(Addr.withElementType(CGF.CharTy),
1795 Info.StorageOffset.getQuantity());
1796 Addr = Addr.withElementType(
1797 llvm::Type::getIntNTy(CGF.getLLVMContext(), Info.StorageSize));
1798 Builder.CreateStore(Builder.getIntN(Info.StorageSize, 0), Addr);
1799 PaddingStart = StorageStart + Info.StorageSize;
1800 }
1801 return;
1802 }
1803
1804 if (PaddingStart < PaddingEnd)
1805 InitBytes(PaddingStart, PaddingEnd);
1806 if (NextField != nullptr)
1807 PaddingStart =
1808 PaddingEnd + CGF.getContext().getTypeSize(NextField->getType());
1809}
1810
1811void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1812 llvm::Value *outerBegin) {
1813 // Emit the common subexpression.
1814 CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1815
1816 Address destPtr = EnsureSlot(E->getType()).getAddress();
1817 uint64_t numElements = E->getArraySize().getZExtValue();
1818
1819 if (!numElements)
1820 return;
1821
1822 // destPtr is an array*. Construct an elementType* by drilling down a level.
1823 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1824 llvm::Value *indices[] = {zero, zero};
1825 llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getElementType(),
1826 destPtr.emitRawPointer(CGF),
1827 indices, "arrayinit.begin");
1828
1829 // Prepare to special-case multidimensional array initialization: we avoid
1830 // emitting multiple destructor loops in that case.
1831 if (!outerBegin)
1832 outerBegin = begin;
1833 ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1834
1835 QualType elementType =
1837 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1838 CharUnits elementAlign =
1839 destPtr.getAlignment().alignmentOfArrayElement(elementSize);
1840 llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
1841
1842 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1843 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1844
1845 // Jump into the body.
1846 CGF.EmitBlock(bodyBB);
1847 llvm::PHINode *index =
1848 Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
1849 index->addIncoming(zero, entryBB);
1850 llvm::Value *element =
1851 Builder.CreateInBoundsGEP(llvmElementType, begin, index);
1852
1854 CGF.ConvergenceTokenStack.push_back(CGF.emitConvergenceLoopToken(bodyBB));
1855
1856 // Prepare for a cleanup.
1857 QualType::DestructionKind dtorKind = elementType.isDestructedType();
1858 EHScopeStack::stable_iterator cleanup;
1859 if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
1860 if (outerBegin->getType() != element->getType())
1861 outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
1862 CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
1863 elementAlign,
1864 CGF.getDestroyer(dtorKind));
1866 } else {
1867 dtorKind = QualType::DK_none;
1868 }
1869
1870 // Emit the actual filler expression.
1871 {
1872 // Temporaries created in an array initialization loop are destroyed
1873 // at the end of each iteration.
1874 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
1875 CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
1876 LValue elementLV = CGF.MakeAddrLValue(
1877 Address(element, llvmElementType, elementAlign), elementType);
1878
1879 if (InnerLoop) {
1880 // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
1881 auto elementSlot = AggValueSlot::forLValue(
1882 elementLV, AggValueSlot::IsDestructed,
1885 AggExprEmitter(CGF, elementSlot, false)
1886 .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
1887 } else
1888 EmitInitializationToLValue(E->getSubExpr(), elementLV);
1889 }
1890
1891 // Move on to the next element.
1892 llvm::Value *nextIndex = Builder.CreateNUWAdd(
1893 index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
1894 index->addIncoming(nextIndex, Builder.GetInsertBlock());
1895
1896 // Leave the loop if we're done.
1897 llvm::Value *done = Builder.CreateICmpEQ(
1898 nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
1899 "arrayinit.done");
1900 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
1901 Builder.CreateCondBr(done, endBB, bodyBB);
1902
1904 CGF.ConvergenceTokenStack.pop_back();
1905
1906 CGF.EmitBlock(endBB);
1907
1908 // Leave the partial-array cleanup if we entered one.
1909 if (dtorKind)
1910 CGF.DeactivateCleanupBlock(cleanup, index);
1911}
1912
1913void AggExprEmitter::VisitDesignatedInitUpdateExpr(
1914 DesignatedInitUpdateExpr *E) {
1915 AggValueSlot Dest = EnsureSlot(E->getType());
1916
1917 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1918 EmitInitializationToLValue(E->getBase(), DestLV);
1919 VisitInitListExpr(E->getUpdater());
1920}
1921
1922//===----------------------------------------------------------------------===//
1923// Entry Points into this File
1924//===----------------------------------------------------------------------===//
1925
1926/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1927/// zeros in it, emit a memset and avoid storing the individual zeros.
1928///
1929static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1930 CodeGenFunction &CGF) {
1931 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1932 // volatile stores.
1933 if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
1934 return;
1935
1936 // C++ objects with a user-declared constructor don't need zero'ing.
1937 if (CGF.getLangOpts().CPlusPlus)
1938 if (const RecordType *RT = CGF.getContext()
1940 ->getAsCanonical<RecordType>()) {
1941 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
1943 return;
1944 }
1945
1946 // If the type is 16-bytes or smaller, prefer individual stores over memset.
1947 CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
1948 if (Size <= CharUnits::fromQuantity(16))
1949 return;
1950
1951 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1952 // we prefer to emit memset + individual stores for the rest.
1953 CharUnits NumNonZeroBytes = CodeGenUtils::GetNumNonZeroBytesInInit(E, CGF);
1954 if (NumNonZeroBytes * 4 > Size)
1955 return;
1956
1957 // Okay, it seems like a good idea to use an initial memset, emit the call.
1958 llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
1959
1960 Address Loc = Slot.getAddress().withElementType(CGF.Int8Ty);
1961 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
1962
1963 // Tell the AggExprEmitter that the slot is known zero.
1964 Slot.setZeroed();
1965}
1966
1967/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1968/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1969/// the value of the aggregate expression is not needed. If VolatileDest is
1970/// true, DestPtr cannot be 0.
1972 assert(E && hasAggregateEvaluationKind(E->getType()) &&
1973 "Invalid aggregate expression to emit");
1974 assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
1975 "slot has bits but no address");
1976
1977 // Optimize the slot if possible.
1978 CheckAggExprForMemSetUse(Slot, E, *this);
1979
1980 AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr *>(E));
1981}
1982
1993
1995 const LValue &Src,
1996 ExprValueKind SrcKind) {
1997 return AggExprEmitter(*this, Dest, Dest.isIgnored())
1998 .EmitFinalDestCopy(Type, Src, SrcKind);
1999}
2000
2003 if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
2005
2006 // Empty fields can overlap earlier fields.
2007 if (FD->getType()->getAsCXXRecordDecl()->isEmpty())
2009
2010 // If the field lies entirely within the enclosing class's nvsize, its tail
2011 // padding cannot overlap any already-initialized object. (The only subobjects
2012 // with greater addresses that might already be initialized are vbases.)
2013 const RecordDecl *ClassRD = FD->getParent();
2014 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
2015 if (Layout.getFieldOffset(FD->getFieldIndex()) +
2016 getContext().getTypeSize(FD->getType()) <=
2017 (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
2019
2020 // The tail padding may contain values we need to preserve.
2022}
2023
2025 const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
2026 // If the most-derived object is a field declared with [[no_unique_address]],
2027 // the tail padding of any virtual base could be reused for other subobjects
2028 // of that field's class.
2029 if (IsVirtual)
2031
2032 // Empty bases can overlap earlier bases.
2033 if (BaseRD->isEmpty())
2035
2036 // If the base class is laid out entirely within the nvsize of the derived
2037 // class, its tail padding cannot yet be initialized, so we can issue
2038 // stores at the full width of the base class.
2039 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2040 if (Layout.getBaseClassOffset(BaseRD) +
2041 getContext().getASTRecordLayout(BaseRD).getSize() <=
2042 Layout.getNonVirtualSize())
2044
2045 // The tail padding may contain values we need to preserve.
2047}
2048
2050 AggValueSlot::Overlap_t MayOverlap,
2051 bool isVolatile) {
2052 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
2053
2054 Address DestPtr = Dest.getAddress();
2055 Address SrcPtr = Src.getAddress();
2056
2057 if (getLangOpts().CPlusPlus) {
2058 if (const auto *Record = Ty->getAsCXXRecordDecl()) {
2059 assert((Record->hasTrivialCopyConstructorForCall() ||
2060 Record->hasTrivialCopyAssignment() ||
2061 Record->hasTrivialMoveConstructorForCall() ||
2062 Record->hasTrivialMoveAssignment() || Record->isUnion() ||
2063 // HLSL uses aggregate-copy for user-defined record types.
2064 (getLangOpts().HLSL && !Record->isHLSLBuiltinRecord())) &&
2065 "Trying to aggregate-copy a type without a trivial copy/move "
2066 "constructor or assignment operator");
2067 // Ignore empty classes in C++.
2068 if (Record->isEmpty())
2069 return;
2070 }
2071 }
2072
2073 if (getLangOpts().CUDAIsDevice) {
2075 if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
2076 Src))
2077 return;
2078 } else if (Ty->isCUDADeviceBuiltinTextureType()) {
2079 if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
2080 Src))
2081 return;
2082 }
2083 }
2084
2085 assert(Ty.getAddressSpace() != LangAS::hlsl_constant &&
2086 "copies of aggregates in hlsl_constant address space should be "
2087 "handled earlier by the HLSL runtime");
2088
2089 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
2090 // C99 6.5.16.1p3, which states "If the value being stored in an object is
2091 // read from another object that overlaps in anyway the storage of the first
2092 // object, then the overlap shall be exact and the two objects shall have
2093 // qualified or unqualified versions of a compatible type."
2094 //
2095 // memcpy is not defined if the source and destination pointers are exactly
2096 // equal, but other compilers do this optimization, and almost every memcpy
2097 // implementation handles this case safely. If there is a libc that does not
2098 // safely handle this, we can add a target hook.
2099
2100 // Get data size info for this aggregate. Don't copy the tail padding if this
2101 // might be a potentially-overlapping subobject, since the tail padding might
2102 // be occupied by a different object. Otherwise, copying it is fine.
2104 if (MayOverlap)
2105 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
2106 else
2107 TypeInfo = getContext().getTypeInfoInChars(Ty);
2108
2109 llvm::Value *SizeVal = nullptr;
2110 if (TypeInfo.Width.isZero()) {
2111 // But note that getTypeInfo returns 0 for a VLA.
2112 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
2113 getContext().getAsArrayType(Ty))) {
2114 QualType BaseEltTy;
2115 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
2116 TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
2117 assert(!TypeInfo.Width.isZero());
2118 SizeVal = Builder.CreateNUWMul(
2119 SizeVal,
2120 llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));
2121 }
2122 }
2123 if (!SizeVal) {
2124 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());
2125 }
2126
2127 // FIXME: If we have a volatile struct, the optimizer can remove what might
2128 // appear to be `extra' memory ops:
2129 //
2130 // volatile struct { int i; } a, b;
2131 //
2132 // int main() {
2133 // a = b;
2134 // a = b;
2135 // }
2136 //
2137 // we need to use a different call here. We use isVolatile to indicate when
2138 // either the source or the destination is volatile.
2139
2140 DestPtr = DestPtr.withElementType(Int8Ty);
2141 SrcPtr = SrcPtr.withElementType(Int8Ty);
2142
2143 // Don't do any of the memmove_collectable tests if GC isn't set.
2144 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
2145 // fall through
2146 } else if (const auto *Record = Ty->getAsRecordDecl()) {
2147 if (Record->hasObjectMember()) {
2148 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2149 SizeVal);
2150 return;
2151 }
2152 } else if (Ty->isArrayType()) {
2153 QualType BaseType = getContext().getBaseElementType(Ty);
2154 if (const auto *Record = BaseType->getAsRecordDecl()) {
2155 if (Record->hasObjectMember()) {
2156 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2157 SizeVal);
2158 return;
2159 }
2160 }
2161 }
2162
2163 auto *Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
2164 addInstToCurrentSourceAtom(Inst, nullptr);
2165 emitPFPPostCopyUpdates(DestPtr, SrcPtr, Ty);
2166
2167 // Determine the metadata to describe the position of any padding in this
2168 // memcpy, as well as the TBAA tags for the members of the struct, in case
2169 // the optimizer wishes to expand it in to scalar memory operations.
2170 if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
2171 Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
2172
2173 if (CGM.getCodeGenOpts().NewStructPathTBAA) {
2174 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
2175 Dest.getTBAAInfo(), Src.getTBAAInfo());
2176 CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
2177 }
2178}
Defines the clang::ASTContext interface.
#define V(N, I)
CompareKind
@ CK_Greater
@ CK_Less
@ CK_Equal
static Expr * findPeephole(Expr *op, CastKind kind, const ASTContext &ctx)
Attempt to look through various unimportant expressions to find a cast of the given kind.
static llvm::Value * EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF, const BinaryOperator *E, llvm::Value *LHS, llvm::Value *RHS, CompareKind Kind, const char *NameSuffix="")
static void EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue DestVal, LValue SrcVal, SourceLocation Loc)
static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, CodeGenFunction &CGF)
CheckAggExprForMemSetUse - If the initializer is large and has a lot of zeros in it,...
static void EmitHLSLScalarElementwiseAndSplatCasts(CodeGenFunction &CGF, LValue DestVal, llvm::Value *SrcVal, QualType SrcTy, SourceLocation Loc)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Record Record
Definition MachO.h:31
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
llvm::json::Array Array
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
APSInt & getInt()
Definition APValue.h:577
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
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.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned getTargetAddressSpace(LangAS AS) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
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
llvm::APInt getArraySize() const
Definition Expr.h:6076
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6069
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6074
QualType getElementType() const
Definition TypeBase.h:3832
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
Opcode getOpcode() const
Definition Expr.h:4152
CXXTemporary * getTemporary()
Definition ExprCXX.h:1516
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
bool constructsVBase() const
Determine whether this constructor is actually constructing a base class (rather than a complete obje...
Definition ExprCXX.h:1797
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1793
bool inheritedFromVBase() const
Determine whether the inherited constructor is inherited from a virtual base of the object we constru...
Definition ExprCXX.h:1807
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5235
FieldDecl * getInitializedFieldInUnion()
Definition ExprCXX.h:5273
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1357
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:613
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1317
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1294
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1344
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition DeclCXX.h:786
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
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
path_iterator path_begin()
Definition Expr.h:3815
CastKind getCastKind() const
Definition Expr.h:3789
path_iterator path_end()
Definition Expr.h:3816
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:184
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
bool isValid() const
Definition Address.h:177
An aggregate value slot.
Definition CGValue.h:551
void setVolatile(bool flag)
Definition CGValue.h:670
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
Address getAddress() const
Definition CGValue.h:689
CharUnits getPreferredSize(ASTContext &Ctx, QualType Type) const
Get the preferred size to use when storing a value to this slot.
Definition CGValue.h:727
NeedsGCBarriers_t requiresGCollection() const
Definition CGValue.h:681
void setExternallyDestructed(bool destructed=true)
Definition CGValue.h:660
void setZeroed(bool V=true)
Definition CGValue.h:719
IsZeroed_t isZeroed() const
Definition CGValue.h:720
Qualifiers getQualifiers() const
Definition CGValue.h:664
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:649
IsAliased_t isPotentiallyAliased() const
Definition CGValue.h:699
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
IsDestructed_t isExternallyDestructed() const
Definition CGValue.h:657
Overlap_t mayOverlap() const
Definition CGValue.h:703
RValue asRValue() const
Definition CGValue.h:711
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Definition CGValue.h:685
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:440
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:239
virtual llvm::Value * EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality)
Emit a comparison between two member pointers. Returns an i1.
Definition CGCXXABI.cpp:84
bool emitBufferCopy(CodeGenFunction &CGF, const Expr *E, const LValue &SrcLV, AggValueSlot &DestSlot)
bool emitGlobalResourceArray(CodeGenFunction &CGF, const Expr *E, AggValueSlot &DestSlot)
void emitInitListOpaqueValues(CodeGenFunction &CGF, InitListExpr *E)
virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, Address DestPtr, Address SrcPtr, llvm::Value *Size)=0
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition CGObjC.cpp:591
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD)
Determine whether a field initialization may overlap some other object.
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
void callCStructMoveConstructor(LValue Dst, LValue Src)
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition CGClass.cpp:283
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
pushRegularPartialArrayCleanup - Push an EH cleanup to destroy already-constructed elements of the gi...
Definition CGDecl.cpp:2687
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
SmallVector< llvm::ConvergenceControlInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition CGExpr.cpp:3062
bool hasVolatileMember(QualType T)
hasVolatileMember - returns true if aggregate type has a volatile member.
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
Definition CGCall.cpp:6957
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7544
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual)
Determine whether a base class initialization may overlap some other object.
const LangOptions & getLangOpts() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:705
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition CGExpr.cpp:7362
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2370
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to destroy already-constructed elements ...
Definition CGDecl.cpp:2671
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2343
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition CGExpr.cpp:7549
void CreateCoercedStore(llvm::Value *Src, QualType SrcFETy, Address Dst, llvm::TypeSize DstSize, bool DstIsVolatile)
Create a store to.
Definition CGCall.cpp:1792
llvm::ConvergenceControlInst * emitConvergenceLoopToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3692
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:263
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6658
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2549
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
Definition CGDecl.cpp:2395
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
void callCStructCopyAssignmentOperator(LValue Dst, LValue Src)
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
void callCStructCopyConstructor(LValue Dst, LValue Src)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1376
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:6139
Address GetAddressOfDirectBaseInCompleteClass(Address Value, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, bool BaseIsVirtual)
GetAddressOfBaseOfCompleteClass - Convert the given pointer to a complete class to the given direct b...
Definition CGClass.cpp:216
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:164
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6597
const TargetCodeGenInfo & getTargetHooks() const
void EmitLifetimeEnd(llvm::Value *Addr)
Definition CGDecl.cpp:1387
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:236
void callCStructMoveAssignmentOperator(LValue Dst, LValue Src)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2801
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2424
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:576
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:285
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:944
void emitPFPPostCopyUpdates(Address DestPtr, Address SrcPtr, QualType Ty)
Copy all PFP fields from SrcPtr to DestPtr while updating signatures, assuming that DestPtr was alrea...
CodeGenTypes & getTypes() const
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
Definition CGExpr.cpp:7553
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1742
void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, bool ForVirtualBase, Address This, bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E)
Emit a call to a constructor inherited from a base class, passing the current constructor's arguments...
Definition CGClass.cpp:2318
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Definition CGExpr.cpp:344
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
static bool hasAggregateEvaluationKind(QualType T)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV)
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1777
llvm::LLVMContext & getLLVMContext()
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:659
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1457
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Module & getModule() const
bool isPaddedAtomicType(QualType type)
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
ASTContext & getContext() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition CGCleanup.h:666
LValue - This represents an lvalue references.
Definition CGValue.h:183
Address getAddress() const
Definition CGValue.h:373
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:347
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
llvm::Value * getAggregatePointer(QualType PointeeType, CodeGenFunction &CGF) const
Definition CGValue.h:89
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
bool isComplex() const
Definition CGValue.h:65
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
virtual LangAS getSRetAddrSpace(const CXXRecordDecl *RD) const
Get the address space for an indirect (sret) return of the given type.
Definition TargetInfo.h:354
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
bool isPartial() const
True iff the comparison is not totally ordered.
const ValueInfo * getLess() const
const ValueInfo * getUnordered() const
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
const ValueInfo * getGreater() const
const ValueInfo * getEqualOrEquiv() const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
const Expr * getInitializer() const
Definition Expr.h:3702
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
bool hasAttr() const
Definition DeclBase.h:586
InitListExpr * getUpdater() const
Definition Expr.h:6022
This represents one expression.
Definition Expr.h:114
bool isGLValue() const
Definition Expr.h:289
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
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
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
const Expr * getSubExpr() const
Definition Expr.h:1107
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5515
bool hadArrayRangeDesignator() const
Definition Expr.h:5569
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2111
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition ExprCXX.h:2085
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2099
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1432
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
bool isUnique() const
Definition Expr.h:1281
Expr * getSelectedExpr() const
Definition ExprCXX.h:4693
const Expr * getSubExpr() const
Definition Expr.h:2268
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3099
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
@ PCK_Struct
The type is a struct containing a field whose type is neither PCK_Trivial nor PCK_VolatileTrivial.
Definition TypeBase.h:1533
Represents a struct/union/class.
Definition Decl.h:4506
bool hasObjectMember() const
Definition Decl.h:4566
field_range fields() const
Definition Decl.h:4709
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
field_iterator field_begin() const
Definition Decl.cpp:5386
Encodes a location in the source.
CompoundStmt * getSubStmt()
Definition Expr.h:4681
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool isUnion() const
Definition Decl.h:4109
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2958
const APValue & getAPValue() const
Definition ExprCXX.h:2967
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 isConstantArrayType() const
Definition TypeBase.h:8918
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8914
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8815
bool isReferenceType() const
Definition TypeBase.h:8839
bool isScalarType() const
Definition TypeBase.h:9310
bool isVariableArrayType() const
Definition TypeBase.h:8926
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5659
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2438
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5668
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2527
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2535
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5724
Expr * getSubExpr() const
Definition Expr.h:2354
QualType getType() const
Definition Decl.h:725
Represents a GCC generic vector type.
Definition TypeBase.h:4398
bool isTrivialFiller(const Expr *E)
Check whether E is a trivial array filler, that is, one that is equivalent to zero-initialization.
bool isBlockVarRef(const Expr *E)
Check whether the value of E is possibly a reference to or into a __block variable.
Definition ExprUtils.cpp:24
CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunctionTy &CGF)
GetNumNonZeroBytesInInit - Get an approximate count of the number of non-zero bytes that will be stor...
Definition ExprUtils.h:86
bool isSimpleZero(const Expr *E, CodeGenFunctionTy &CGF)
isSimpleZero - If emitting this value will obviously just cause a store of zero to memory,...
Definition ExprUtils.h:51
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< AtomicType > atomicType
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4564
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1527
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
llvm::APSInt getIntValue() const
Get the constant integer value used by this variable to represent the comparison category result type...