clang 23.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"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Instruction.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Intrinsics.h"
34using namespace clang;
35using namespace CodeGen;
36
37//===----------------------------------------------------------------------===//
38// Aggregate Expression Emitter
39//===----------------------------------------------------------------------===//
40
41namespace {
42class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
43 CodeGenFunction &CGF;
44 CGBuilderTy &Builder;
45 AggValueSlot Dest;
46 bool IsResultUnused;
47
48 AggValueSlot EnsureSlot(QualType T) {
49 if (!Dest.isIgnored())
50 return Dest;
51 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
52 }
53 void EnsureDest(QualType T) {
54 if (!Dest.isIgnored())
55 return;
56 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
57 }
58
59 // Calls `Fn` with a valid return value slot, potentially creating a temporary
60 // to do so. If a temporary is created, an appropriate copy into `Dest` will
61 // be emitted, as will lifetime markers.
62 //
63 // The given function should take a ReturnValueSlot, and return an RValue that
64 // points to said slot.
65 void withReturnValueSlot(const Expr *E,
66 llvm::function_ref<RValue(ReturnValueSlot)> Fn);
67
68 void DoZeroInitPadding(uint64_t &PaddingStart, uint64_t PaddingEnd,
69 const FieldDecl *NextField);
70
71public:
72 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
73 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
74 IsResultUnused(IsResultUnused) {}
75
76 //===--------------------------------------------------------------------===//
77 // Utilities
78 //===--------------------------------------------------------------------===//
79
80 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
81 /// represents a value lvalue, this method emits the address of the lvalue,
82 /// then loads the result into DestPtr.
83 void EmitAggLoadOfLValue(const Expr *E);
84
85 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
86 /// SrcIsRValue is true if source comes from an RValue.
87 void EmitFinalDestCopy(QualType type, const LValue &src,
90 void EmitFinalDestCopy(QualType type, RValue src);
91 void EmitCopy(QualType type, const AggValueSlot &dest,
92 const AggValueSlot &src);
93
94 void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, QualType ArrayQTy,
95 Expr *ExprToVisit, ArrayRef<Expr *> Args,
96 Expr *ArrayFiller);
97
98 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
99 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
102 }
103
104 bool TypeRequiresGCollection(QualType T);
105
106 //===--------------------------------------------------------------------===//
107 // Visitor Methods
108 //===--------------------------------------------------------------------===//
109
110 void Visit(Expr *E) {
111 ApplyDebugLocation DL(CGF, E);
112 StmtVisitor<AggExprEmitter>::Visit(E);
113 }
114
115 void VisitStmt(Stmt *S) { CGF.ErrorUnsupported(S, "aggregate expression"); }
116 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
117 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
118 Visit(GE->getResultExpr());
119 }
120 void VisitCoawaitExpr(CoawaitExpr *E) {
121 CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
122 }
123 void VisitCoyieldExpr(CoyieldExpr *E) {
124 CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
125 }
126 void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
127 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
128 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
129 return Visit(E->getReplacement());
130 }
131
132 void VisitConstantExpr(ConstantExpr *E) {
133 EnsureDest(E->getType());
134
135 if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
137 Result, E->getType(), Dest.getAddress(),
138 llvm::TypeSize::getFixed(
139 Dest.getPreferredSize(CGF.getContext(), E->getType())
140 .getQuantity()),
142 return;
143 }
144 return Visit(E->getSubExpr());
145 }
146
147 // l-values.
148 void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
149 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
150 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
151 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
152 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
153 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
154 EmitAggLoadOfLValue(E);
155 }
156 void VisitPredefinedExpr(const PredefinedExpr *E) { EmitAggLoadOfLValue(E); }
157
158 // Operators.
159 void VisitCastExpr(CastExpr *E);
160 void VisitCallExpr(const CallExpr *E);
161 void VisitStmtExpr(const StmtExpr *E);
162 void VisitBinaryOperator(const BinaryOperator *BO);
163 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
164 void VisitBinAssign(const BinaryOperator *E);
165 void VisitBinComma(const BinaryOperator *E);
166 void VisitBinCmp(const BinaryOperator *E);
167 void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
168 Visit(E->getSemanticForm());
169 }
170
171 void VisitObjCMessageExpr(ObjCMessageExpr *E);
172 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { EmitAggLoadOfLValue(E); }
173
174 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
175 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
176 void VisitChooseExpr(const ChooseExpr *CE);
177 void VisitInitListExpr(InitListExpr *E);
178 void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
179 FieldDecl *InitializedFieldInUnion,
180 Expr *ArrayFiller);
181 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
182 llvm::Value *outerBegin = nullptr);
183 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
184 void VisitNoInitExpr(NoInitExpr *E) {} // Do nothing.
185 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
186 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
187 Visit(DAE->getExpr());
188 }
189 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
190 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
191 Visit(DIE->getExpr());
192 }
193 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
194 void VisitCXXConstructExpr(const CXXConstructExpr *E);
195 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
196 void VisitLambdaExpr(LambdaExpr *E);
197 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
198 void VisitExprWithCleanups(ExprWithCleanups *E);
199 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
200 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
201 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
202 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
203
204 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
205 if (E->isGLValue()) {
206 LValue LV = CGF.EmitPseudoObjectLValue(E);
207 return EmitFinalDestCopy(E->getType(), LV);
208 }
209
210 AggValueSlot Slot = EnsureSlot(E->getType());
211 bool NeedsDestruction =
212 !Slot.isExternallyDestructed() &&
214 if (NeedsDestruction)
216 CGF.EmitPseudoObjectRValue(E, Slot);
217 if (NeedsDestruction)
219 E->getType());
220 }
221
222 void VisitVAArgExpr(VAArgExpr *E);
223 void VisitCXXParenListInitExpr(CXXParenListInitExpr *E);
224 void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
225 Expr *ArrayFiller);
226
227 void EmitInitializationToLValue(Expr *E, LValue Address);
228 void EmitNullInitializationToLValue(LValue Address);
229 // case Expr::ChooseExprClass:
230 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
231 void VisitAtomicExpr(AtomicExpr *E) {
232 RValue Res = CGF.EmitAtomicExpr(E);
233 EmitFinalDestCopy(E->getType(), Res);
234 }
235 void VisitPackIndexingExpr(PackIndexingExpr *E) {
236 Visit(E->getSelectedExpr());
237 }
238};
239} // end anonymous namespace.
240
241//===----------------------------------------------------------------------===//
242// Utilities
243//===----------------------------------------------------------------------===//
244
245/// EmitAggLoadOfLValue - Given an expression with aggregate type that
246/// represents a value lvalue, this method emits the address of the lvalue,
247/// then loads the result into DestPtr.
248void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
250
251 // If the type of the l-value is atomic, then do an atomic load.
252 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
253 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
254 return;
255 }
256
257 EmitFinalDestCopy(E->getType(), LV);
258}
259
260/// True if the given aggregate type requires special GC API calls.
261bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
262 // Only record types have members that might require garbage collection.
263 const auto *Record = T->getAsRecordDecl();
264 if (!Record)
265 return false;
266
267 // Don't mess with non-trivial C++ types.
269 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
270 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
271 return false;
272
273 // Check whether the type has an object member.
274 return Record->hasObjectMember();
275}
276
277void AggExprEmitter::withReturnValueSlot(
278 const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
279 QualType RetTy = E->getType();
280 bool RequiresDestruction =
281 !Dest.isExternallyDestructed() &&
283
284 // If it makes no observable difference, save a memcpy + temporary.
285 //
286 // We need to always provide our own temporary if destruction is required.
287 // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
288 // its lifetime before we have the chance to emit a proper destructor call.
289 //
290 // We also need a temporary if the destination is in a different address space
291 // from the sret AS. Use the target hook to get the actual sret AS for this
292 // return type.
293 const CXXRecordDecl *RD = RetTy->getAsCXXRecordDecl();
294 LangAS SRetLangAS = CGF.CGM.getTargetCodeGenInfo().getSRetAddrSpace(RD);
295 unsigned SRetAS = CGF.getContext().getTargetAddressSpace(SRetLangAS);
296 bool CanAggregateCopy =
297 RD ? (RD->hasTrivialCopyConstructor() ||
299 RD->hasTrivialMoveAssignment() || RD->hasAttr<TrivialABIAttr>() ||
300 RD->isUnion())
301 : RetTy.isTriviallyCopyableType(CGF.getContext());
302 bool DestASMismatch = !Dest.isIgnored() && CanAggregateCopy &&
303 Dest.getAddress()
305 ->stripPointerCasts()
306 ->getType()
307 ->getPointerAddressSpace() != SRetAS;
308 bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
309 (RequiresDestruction && Dest.isIgnored()) || DestASMismatch;
310
311 Address RetAddr = Address::invalid();
312
313 EHScopeStack::stable_iterator LifetimeEndBlock;
314 llvm::IntrinsicInst *LifetimeStartInst = nullptr;
315 if (!UseTemp) {
316 RetAddr = Dest.getAddress();
317 if (RetAddr.isValid() && RetAddr.getAddressSpace() != SRetAS) {
318 llvm::Type *SRetPtrTy =
319 llvm::PointerType::get(CGF.getLLVMContext(), SRetAS);
320 RetAddr = RetAddr.withPointer(
321 CGF.performAddrSpaceCast(RetAddr.getBasePointer(), SRetPtrTy),
322 RetAddr.isKnownNonNull());
323 }
324 } else {
325 RetAddr = CGF.CreateMemTempWithoutCast(RetTy, "tmp");
326 if (CGF.EmitLifetimeStart(RetAddr.getBasePointer())) {
327 LifetimeStartInst =
328 cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
329 assert(LifetimeStartInst->getIntrinsicID() ==
330 llvm::Intrinsic::lifetime_start &&
331 "Last insertion wasn't a lifetime.start?");
332
333 CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
334 NormalEHLifetimeMarker, RetAddr);
335 LifetimeEndBlock = CGF.EHStack.stable_begin();
336 }
337 }
338
339 RValue Src =
340 EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
341 Dest.isExternallyDestructed()));
342
343 if (!UseTemp)
344 return;
345
346 assert(Dest.isIgnored() || Dest.emitRawPointer(CGF) !=
347 Src.getAggregatePointer(E->getType(), CGF));
348 EmitFinalDestCopy(E->getType(), Src);
349
350 if (!RequiresDestruction && LifetimeStartInst) {
351 // If there's no dtor to run, the copy was the last use of our temporary.
352 // Since we're not guaranteed to be in an ExprWithCleanups, clean up
353 // eagerly.
354 CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
355 CGF.EmitLifetimeEnd(RetAddr.getBasePointer());
356 }
357}
358
359/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
360void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
361 assert(src.isAggregate() && "value must be aggregate value!");
362 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
363 EmitFinalDestCopy(type, srcLV, CodeGenFunction::EVK_RValue);
364}
365
366/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
367void AggExprEmitter::EmitFinalDestCopy(
368 QualType type, const LValue &src,
369 CodeGenFunction::ExprValueKind SrcValueKind) {
370 // If Dest is ignored, then we're evaluating an aggregate expression
371 // in a context that doesn't care about the result. Note that loads
372 // from volatile l-values force the existence of a non-ignored
373 // destination.
374 if (Dest.isIgnored())
375 return;
376
377 // Copy non-trivial C structs here.
378 LValue DstLV = CGF.MakeAddrLValue(
379 Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
380
381 if (SrcValueKind == CodeGenFunction::EVK_RValue) {
382 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
383 if (Dest.isPotentiallyAliased())
384 CGF.callCStructMoveAssignmentOperator(DstLV, src);
385 else
386 CGF.callCStructMoveConstructor(DstLV, src);
387 return;
388 }
389 } else {
390 if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
391 if (Dest.isPotentiallyAliased())
392 CGF.callCStructCopyAssignmentOperator(DstLV, src);
393 else
394 CGF.callCStructCopyConstructor(DstLV, src);
395 return;
396 }
397 }
398
399 AggValueSlot srcAgg = AggValueSlot::forLValue(
402 EmitCopy(type, Dest, srcAgg);
403}
404
405/// Perform a copy from the source into the destination.
406///
407/// \param type - the type of the aggregate being copied; qualifiers are
408/// ignored
409void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
410 const AggValueSlot &src) {
411 if (dest.requiresGCollection()) {
412 CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
413 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
415 src.getAddress(), size);
416 return;
417 }
418
419 // If the result of the assignment is used, copy the LHS there also.
420 // It's volatile if either side is. Use the minimum alignment of
421 // the two sides.
422 LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
423 LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
424 CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
425 dest.isVolatile() || src.isVolatile());
426}
427
428/// Emit the initializer for a std::initializer_list initialized with a
429/// real initializer list.
430void AggExprEmitter::VisitCXXStdInitializerListExpr(
431 CXXStdInitializerListExpr *E) {
432 // Emit an array containing the elements. The array is externally destructed
433 // if the std::initializer_list object is.
434 ASTContext &Ctx = CGF.getContext();
435 LValue Array = CGF.EmitLValue(E->getSubExpr());
436 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
437 Address ArrayPtr = Array.getAddress();
438
439 const ConstantArrayType *ArrayType =
441 assert(ArrayType && "std::initializer_list constructed from non-array");
442
443 auto *Record = E->getType()->castAsRecordDecl();
444 RecordDecl::field_iterator Field = Record->field_begin();
445 assert(Field != Record->field_end() &&
446 Ctx.hasSameType(Field->getType()->getPointeeType(),
447 ArrayType->getElementType()) &&
448 "Expected std::initializer_list first field to be const E *");
449
450 // Start pointer.
451 AggValueSlot Dest = EnsureSlot(E->getType());
452 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
453 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
454 llvm::Value *ArrayStart = ArrayPtr.emitRawPointer(CGF);
455 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
456 ++Field;
457 assert(Field != Record->field_end() &&
458 "Expected std::initializer_list to have two fields");
459
460 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
461 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
462 if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
463 // Length.
464 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
465
466 } else {
467 // End pointer.
468 assert(Field->getType()->isPointerType() &&
469 Ctx.hasSameType(Field->getType()->getPointeeType(),
470 ArrayType->getElementType()) &&
471 "Expected std::initializer_list second field to be const E *");
472 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
473 llvm::Value *IdxEnd[] = {Zero, Size};
474 llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(
475 ArrayPtr.getElementType(), ArrayPtr.emitRawPointer(CGF), IdxEnd,
476 "arrayend");
477 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
478 }
479
480 assert(++Field == Record->field_end() &&
481 "Expected std::initializer_list to only have two fields");
482}
483
484/// Determine if E is a trivial array filler, that is, one that is
485/// equivalent to zero-initialization.
486static bool isTrivialFiller(Expr *E) {
487 if (!E)
488 return true;
489
491 return true;
492
493 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
494 if (ILE->getNumInits())
495 return false;
496 return isTrivialFiller(ILE->getArrayFiller());
497 }
498
499 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
500 return Cons->getConstructor()->isDefaultConstructor() &&
501 Cons->getConstructor()->isTrivial();
502
503 // FIXME: Are there other cases where we can avoid emitting an initializer?
504 return false;
505}
506
507// emit an elementwise cast where the RHS is a scalar or vector
508// or emit an aggregate splat cast
510 LValue DestVal,
511 llvm::Value *SrcVal,
512 QualType SrcTy,
513 SourceLocation Loc) {
514 // Flatten our destination
515 SmallVector<LValue, 16> StoreList;
516 CGF.FlattenAccessAndTypeLValue(DestVal, StoreList);
517
518 bool isVector = false;
519 if (auto *VT = SrcTy->getAs<VectorType>()) {
520 isVector = true;
521 SrcTy = VT->getElementType();
522 assert(StoreList.size() <= VT->getNumElements() &&
523 "Cannot perform HLSL flat cast when vector source \
524 object has less elements than flattened destination \
525 object.");
526 }
527
528 for (unsigned I = 0, Size = StoreList.size(); I < Size; I++) {
529 LValue DestLVal = StoreList[I];
530 llvm::Value *Load =
531 isVector ? CGF.Builder.CreateExtractElement(SrcVal, I, "vec.load")
532 : SrcVal;
533 llvm::Value *Cast =
534 CGF.EmitScalarConversion(Load, SrcTy, DestLVal.getType(), Loc);
535 CGF.EmitStoreThroughLValue(RValue::get(Cast), DestLVal);
536 }
537}
538
539// emit a flat cast where the RHS is an aggregate
540static void EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue DestVal,
541 LValue SrcVal, SourceLocation Loc) {
542 // Flatten our destination
543 SmallVector<LValue, 16> StoreList;
544 CGF.FlattenAccessAndTypeLValue(DestVal, StoreList);
545 // Flatten our src
547 CGF.FlattenAccessAndTypeLValue(SrcVal, LoadList);
548
549 assert(StoreList.size() <= LoadList.size() &&
550 "Cannot perform HLSL elementwise cast when flattened source object \
551 has less elements than flattened destination object.");
552 // apply casts to what we load from LoadList
553 // and store result in Dest
554 for (unsigned I = 0, E = StoreList.size(); I < E; I++) {
555 LValue DestLVal = StoreList[I];
556 LValue SrcLVal = LoadList[I];
557 RValue RVal = CGF.EmitLoadOfLValue(SrcLVal, Loc);
558 assert(RVal.isScalar() && "All flattened source values should be scalars");
559 llvm::Value *Val = RVal.getScalarVal();
560 llvm::Value *Cast = CGF.EmitScalarConversion(Val, SrcLVal.getType(),
561 DestLVal.getType(), Loc);
562 CGF.EmitStoreThroughLValue(RValue::get(Cast), DestLVal);
563 }
564}
565
566/// Emit initialization of an array from an initializer list. ExprToVisit must
567/// be either an InitListEpxr a CXXParenInitListExpr.
568void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
569 QualType ArrayQTy, Expr *ExprToVisit,
570 ArrayRef<Expr *> Args, Expr *ArrayFiller) {
571 uint64_t NumInitElements = Args.size();
572
573 uint64_t NumArrayElements = AType->getNumElements();
574 for (const auto *Init : Args) {
575 if (const auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
576 NumInitElements += Embed->getDataElementCount() - 1;
577 if (NumInitElements > NumArrayElements) {
578 NumInitElements = NumArrayElements;
579 break;
580 }
581 }
582 }
583
584 assert(NumInitElements <= NumArrayElements);
585
586 QualType elementType =
587 CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
588 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
589 CharUnits elementAlign =
590 DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
591 llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
592
593 // Consider initializing the array by copying from a global. For this to be
594 // more efficient than per-element initialization, the size of the elements
595 // with explicit initializers should be large enough.
596 if (NumInitElements * elementSize.getQuantity() > 16 &&
597 elementType.isTriviallyCopyableType(CGF.getContext())) {
598 CodeGen::CodeGenModule &CGM = CGF.CGM;
599 ConstantEmitter Emitter(CGF);
600 QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(
601 CGM.getContext().removeAddrSpaceQualType(ArrayQTy),
603 LangAS AS = GVArrayQTy.getAddressSpace();
604 if (llvm::Constant *C =
605 Emitter.tryEmitForInitializer(ExprToVisit, AS, GVArrayQTy)) {
606 auto GV = new llvm::GlobalVariable(
607 CGM.getModule(), C->getType(),
608 /* isConstant= */ true, llvm::GlobalValue::PrivateLinkage, C,
609 "constinit",
610 /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
612 Emitter.finalize(GV);
613 CharUnits Align = CGM.getContext().getTypeAlignInChars(GVArrayQTy);
614 GV->setAlignment(Align.getAsAlign());
615 Address GVAddr(GV, GV->getValueType(), Align);
616 EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, GVArrayQTy));
617 return;
618 }
619 }
620
621 // Exception safety requires us to destroy all the
622 // already-constructed members if an initializer throws.
623 // For that, we'll need an EH cleanup.
624 QualType::DestructionKind dtorKind = elementType.isDestructedType();
625 Address endOfInit = Address::invalid();
626 CodeGenFunction::CleanupDeactivationScope deactivation(CGF);
627
628 llvm::Value *begin = DestPtr.emitRawPointer(CGF);
629 if (dtorKind) {
630 CodeGenFunction::AllocaTrackerRAII allocaTracker(CGF);
631 // In principle we could tell the cleanup where we are more
632 // directly, but the control flow can get so varied here that it
633 // would actually be quite complex. Therefore we go through an
634 // alloca.
635 llvm::Instruction *dominatingIP =
636 Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(CGF.Int8PtrTy));
637 endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
638 "arrayinit.endOfInit");
639 Builder.CreateStore(begin, endOfInit);
640 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
641 elementAlign,
642 CGF.getDestroyer(dtorKind));
644 .AddAuxAllocas(allocaTracker.Take());
645
647 {CGF.EHStack.stable_begin(), dominatingIP});
648 }
649
650 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
651
652 auto Emit = [&](Expr *Init, uint64_t ArrayIndex) {
653 llvm::Value *element = begin;
654 if (ArrayIndex > 0) {
655 if (CGF.getLangOpts().EmitLogicalPointer)
656 element = Builder.CreateStructuredGEP(
657 AType, begin, llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex),
658 "arrayinit.element");
659 else
660 element = Builder.CreateInBoundsGEP(
661 llvmElementType, begin,
662 llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex),
663 "arrayinit.element");
664
665 // Tell the cleanup that it needs to destroy up to this
666 // element. TODO: some of these stores can be trivially
667 // observed to be unnecessary.
668 if (endOfInit.isValid())
669 Builder.CreateStore(element, endOfInit);
670 }
671
672 LValue elementLV = CGF.MakeAddrLValue(
673 Address(element, llvmElementType, elementAlign), elementType);
674 EmitInitializationToLValue(Init, elementLV);
675 return true;
676 };
677
678 unsigned ArrayIndex = 0;
679 // Emit the explicit initializers.
680 for (uint64_t i = 0; i != NumInitElements; ++i) {
681 if (ArrayIndex >= NumInitElements)
682 break;
683 if (auto *EmbedS = dyn_cast<EmbedExpr>(Args[i]->IgnoreParenImpCasts())) {
684 EmbedS->doForEachDataElement(Emit, ArrayIndex);
685 } else {
686 Emit(Args[i], ArrayIndex);
687 ArrayIndex++;
688 }
689 }
690
691 // Check whether there's a non-trivial array-fill expression.
692 bool hasTrivialFiller = isTrivialFiller(ArrayFiller);
693
694 // Any remaining elements need to be zero-initialized, possibly
695 // using the filler expression. We can skip this if the we're
696 // emitting to zeroed memory.
697 if (NumInitElements != NumArrayElements &&
698 !(Dest.isZeroed() && hasTrivialFiller &&
699 CGF.getTypes().isZeroInitializable(elementType))) {
700
701 // Use an actual loop. This is basically
702 // do { *array++ = filler; } while (array != end);
703
704 // Advance to the start of the rest of the array.
705 llvm::Value *element = begin;
706 if (NumInitElements) {
707 element = Builder.CreateInBoundsGEP(
708 llvmElementType, element,
709 llvm::ConstantInt::get(CGF.SizeTy, NumInitElements),
710 "arrayinit.start");
711 if (endOfInit.isValid())
712 Builder.CreateStore(element, endOfInit);
713 }
714
715 // Compute the end of the array.
716 llvm::Value *end = Builder.CreateInBoundsGEP(
717 llvmElementType, begin,
718 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");
719
720 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
721 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
722
723 // Jump into the body.
724 CGF.EmitBlock(bodyBB);
725 llvm::PHINode *currentElement =
726 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
727 currentElement->addIncoming(element, entryBB);
728
730 CGF.ConvergenceTokenStack.push_back(CGF.emitConvergenceLoopToken(bodyBB));
731
732 // Emit the actual filler expression.
733 {
734 // C++1z [class.temporary]p5:
735 // when a default constructor is called to initialize an element of
736 // an array with no corresponding initializer [...] the destruction of
737 // every temporary created in a default argument is sequenced before
738 // the construction of the next array element, if any
739 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
740 LValue elementLV = CGF.MakeAddrLValue(
741 Address(currentElement, llvmElementType, elementAlign), elementType);
742 if (ArrayFiller)
743 EmitInitializationToLValue(ArrayFiller, elementLV);
744 else
745 EmitNullInitializationToLValue(elementLV);
746 }
747
748 // Move on to the next element.
749 llvm::Value *nextElement = Builder.CreateInBoundsGEP(
750 llvmElementType, currentElement, one, "arrayinit.next");
751
752 // Tell the EH cleanup that we finished with the last element.
753 if (endOfInit.isValid())
754 Builder.CreateStore(nextElement, endOfInit);
755
756 // Leave the loop if we're done.
757 llvm::Value *done =
758 Builder.CreateICmpEQ(nextElement, end, "arrayinit.done");
759 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
760 Builder.CreateCondBr(done, endBB, bodyBB);
761 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
762
764 CGF.ConvergenceTokenStack.pop_back();
765
766 CGF.EmitBlock(endBB);
767 }
768}
769
770//===----------------------------------------------------------------------===//
771// Visitor Methods
772//===----------------------------------------------------------------------===//
773
774void AggExprEmitter::VisitMaterializeTemporaryExpr(
775 MaterializeTemporaryExpr *E) {
776 Visit(E->getSubExpr());
777}
778
779void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
780 // If this is a unique OVE, just visit its source expression.
781 if (e->isUnique())
782 Visit(e->getSourceExpr());
783 else
784 EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
785}
786
787void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
788 if (Dest.isPotentiallyAliased()) {
789 // Just emit a load of the lvalue + a copy, because our compound literal
790 // might alias the destination.
791 EmitAggLoadOfLValue(E);
792 return;
793 }
794
795 AggValueSlot Slot = EnsureSlot(E->getType());
796
797 // Block-scope compound literals are destroyed at the end of the enclosing
798 // scope in C.
799 bool Destruct =
800 !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();
801 if (Destruct)
803
804 CGF.EmitAggExpr(E->getInitializer(), Slot);
805
806 if (Destruct)
809 CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
810 CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
811}
812
813/// Attempt to look through various unimportant expressions to find a
814/// cast of the given kind.
815static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
816 op = op->IgnoreParenNoopCasts(ctx);
817 if (auto castE = dyn_cast<CastExpr>(op)) {
818 if (castE->getCastKind() == kind)
819 return castE->getSubExpr();
820 }
821 return nullptr;
822}
823
824void AggExprEmitter::VisitCastExpr(CastExpr *E) {
825 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
826 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
827 switch (E->getCastKind()) {
828 case CK_Dynamic: {
829 // FIXME: Can this actually happen? We have no test coverage for it.
830 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
831 LValue LV =
833 // FIXME: Do we also need to handle property references here?
834 if (LV.isSimple())
835 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
836 else
837 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
838
839 if (!Dest.isIgnored())
840 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
841 break;
842 }
843
844 case CK_ToUnion: {
845 // Evaluate even if the destination is ignored.
846 if (Dest.isIgnored()) {
848 /*ignoreResult=*/true);
849 break;
850 }
851
852 // GCC union extension
853 QualType Ty = E->getSubExpr()->getType();
854 Address CastPtr = Dest.getAddress().withElementType(CGF.ConvertType(Ty));
855 EmitInitializationToLValue(E->getSubExpr(),
856 CGF.MakeAddrLValue(CastPtr, Ty));
857 break;
858 }
859
860 case CK_LValueToRValueBitCast: {
861 if (Dest.isIgnored()) {
863 /*ignoreResult=*/true);
864 break;
865 }
866
867 LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
868 Address SourceAddress = SourceLV.getAddress().withElementType(CGF.Int8Ty);
869 Address DestAddress = Dest.getAddress().withElementType(CGF.Int8Ty);
870 llvm::Value *SizeVal = llvm::ConstantInt::get(
871 CGF.SizeTy,
873 Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
874 break;
875 }
876
877 case CK_DerivedToBase:
878 case CK_BaseToDerived:
879 case CK_UncheckedDerivedToBase: {
880 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
881 "should have been unpacked before we got here");
882 }
883
884 case CK_NonAtomicToAtomic:
885 case CK_AtomicToNonAtomic: {
886 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
887
888 // Determine the atomic and value types.
889 QualType atomicType = E->getSubExpr()->getType();
890 QualType valueType = E->getType();
891 if (isToAtomic)
892 std::swap(atomicType, valueType);
893
894 assert(atomicType->isAtomicType());
896 valueType, atomicType->castAs<AtomicType>()->getValueType()));
897
898 // Just recurse normally if we're ignoring the result or the
899 // atomic type doesn't change representation.
900 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
901 return Visit(E->getSubExpr());
902 }
903
904 CastKind peepholeTarget =
905 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
906
907 // These two cases are reverses of each other; try to peephole them.
908 if (Expr *op =
909 findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
910 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
911 E->getType()) &&
912 "peephole significantly changed types?");
913 return Visit(op);
914 }
915
916 // If we're converting an r-value of non-atomic type to an r-value
917 // of atomic type, just emit directly into the relevant sub-object.
918 if (isToAtomic) {
919 AggValueSlot valueDest = Dest;
920 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
921 // Zero-initialize. (Strictly speaking, we only need to initialize
922 // the padding at the end, but this is simpler.)
923 if (!Dest.isZeroed())
925
926 // Build a GEP to refer to the subobject.
927 Address valueAddr =
928 CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
929 valueDest = AggValueSlot::forAddr(
930 valueAddr, valueDest.getQualifiers(),
931 valueDest.isExternallyDestructed(), valueDest.requiresGCollection(),
934 }
935
936 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
937 return;
938 }
939
940 // Otherwise, we're converting an atomic type to a non-atomic type.
941 // Make an atomic temporary, emit into that, and then copy the value out.
942 AggValueSlot atomicSlot =
943 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
944 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
945
946 Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
947 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
948 return EmitFinalDestCopy(valueType, rvalue);
949 }
950 case CK_AddressSpaceConversion:
951 return Visit(E->getSubExpr());
952
953 case CK_LValueToRValue:
954 // If we're loading from a volatile type, force the destination
955 // into existence.
956 if (E->getSubExpr()->getType().isVolatileQualified()) {
957 bool Destruct =
958 !Dest.isExternallyDestructed() &&
960 if (Destruct)
962 EnsureDest(E->getType());
963 Visit(E->getSubExpr());
964
965 if (Destruct)
967 E->getType());
968
969 return;
970 }
971
972 [[fallthrough]];
973
974 case CK_HLSLArrayRValue:
975 Visit(E->getSubExpr());
976 break;
977 case CK_HLSLAggregateSplatCast: {
978 Expr *Src = E->getSubExpr();
979 QualType SrcTy = Src->getType();
980 RValue RV = CGF.EmitAnyExpr(Src);
981 LValue DestLVal = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
982 SourceLocation Loc = E->getExprLoc();
983
984 assert(RV.isScalar() && SrcTy->isScalarType() &&
985 "RHS of HLSL splat cast must be a scalar.");
986 llvm::Value *SrcVal = RV.getScalarVal();
987 EmitHLSLScalarElementwiseAndSplatCasts(CGF, DestLVal, SrcVal, SrcTy, Loc);
988 break;
989 }
990 case CK_HLSLElementwiseCast: {
991 Expr *Src = E->getSubExpr();
992 QualType SrcTy = Src->getType();
993 RValue RV = CGF.EmitAnyExpr(Src);
994 LValue DestLVal = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
995 SourceLocation Loc = E->getExprLoc();
996
997 if (RV.isScalar()) {
998 llvm::Value *SrcVal = RV.getScalarVal();
999 assert(SrcTy->isVectorType() &&
1000 "HLSL Elementwise cast doesn't handle splatting.");
1001 EmitHLSLScalarElementwiseAndSplatCasts(CGF, DestLVal, SrcVal, SrcTy, Loc);
1002 } else {
1003 assert(RV.isAggregate() &&
1004 "Can't perform HLSL Aggregate cast on a complex type.");
1005 Address SrcVal = RV.getAggregateAddress();
1006 EmitHLSLElementwiseCast(CGF, DestLVal, CGF.MakeAddrLValue(SrcVal, SrcTy),
1007 Loc);
1008 }
1009 break;
1010 }
1011 case CK_NoOp:
1012 case CK_UserDefinedConversion:
1013 case CK_ConstructorConversion:
1015 E->getType()) &&
1016 "Implicit cast types must be compatible");
1017 Visit(E->getSubExpr());
1018 break;
1019
1020 case CK_LValueBitCast:
1021 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
1022
1023 case CK_Dependent:
1024 case CK_BitCast:
1025 case CK_ArrayToPointerDecay:
1026 case CK_FunctionToPointerDecay:
1027 case CK_NullToPointer:
1028 case CK_NullToMemberPointer:
1029 case CK_BaseToDerivedMemberPointer:
1030 case CK_DerivedToBaseMemberPointer:
1031 case CK_MemberPointerToBoolean:
1032 case CK_ReinterpretMemberPointer:
1033 case CK_IntegralToPointer:
1034 case CK_PointerToIntegral:
1035 case CK_PointerToBoolean:
1036 case CK_ToVoid:
1037 case CK_VectorSplat:
1038 case CK_IntegralCast:
1039 case CK_BooleanToSignedIntegral:
1040 case CK_IntegralToBoolean:
1041 case CK_IntegralToFloating:
1042 case CK_FloatingToIntegral:
1043 case CK_FloatingToBoolean:
1044 case CK_FloatingCast:
1045 case CK_CPointerToObjCPointerCast:
1046 case CK_BlockPointerToObjCPointerCast:
1047 case CK_AnyPointerToBlockPointerCast:
1048 case CK_ObjCObjectLValueCast:
1049 case CK_FloatingRealToComplex:
1050 case CK_FloatingComplexToReal:
1051 case CK_FloatingComplexToBoolean:
1052 case CK_FloatingComplexCast:
1053 case CK_FloatingComplexToIntegralComplex:
1054 case CK_IntegralRealToComplex:
1055 case CK_IntegralComplexToReal:
1056 case CK_IntegralComplexToBoolean:
1057 case CK_IntegralComplexCast:
1058 case CK_IntegralComplexToFloatingComplex:
1059 case CK_ARCProduceObject:
1060 case CK_ARCConsumeObject:
1061 case CK_ARCReclaimReturnedObject:
1062 case CK_ARCExtendBlockObject:
1063 case CK_CopyAndAutoreleaseBlockObject:
1064 case CK_BuiltinFnToFnPtr:
1065 case CK_ZeroToOCLOpaqueType:
1066 case CK_MatrixCast:
1067 case CK_HLSLVectorTruncation:
1068 case CK_HLSLMatrixTruncation:
1069 case CK_IntToOCLSampler:
1070 case CK_FloatingToFixedPoint:
1071 case CK_FixedPointToFloating:
1072 case CK_FixedPointCast:
1073 case CK_FixedPointToBoolean:
1074 case CK_FixedPointToIntegral:
1075 case CK_IntegralToFixedPoint:
1076 llvm_unreachable("cast kind invalid for aggregate types");
1077 }
1078}
1079
1080void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
1081 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
1082 EmitAggLoadOfLValue(E);
1083 return;
1084 }
1085
1086 withReturnValueSlot(
1087 E, [&](ReturnValueSlot Slot) { return CGF.EmitCallExpr(E, Slot); });
1088}
1089
1090void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1091 withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
1092 return CGF.EmitObjCMessageExpr(E, Slot);
1093 });
1094}
1095
1096void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
1097 CGF.EmitIgnoredExpr(E->getLHS());
1098 Visit(E->getRHS());
1099}
1100
1101void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1102 CodeGenFunction::StmtExprEvaluation eval(CGF);
1103 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
1104}
1105
1111
1112static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
1113 const BinaryOperator *E, llvm::Value *LHS,
1114 llvm::Value *RHS, CompareKind Kind,
1115 const char *NameSuffix = "") {
1116 QualType ArgTy = E->getLHS()->getType();
1117 if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
1118 ArgTy = CT->getElementType();
1119
1120 if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
1121 assert(Kind == CK_Equal &&
1122 "member pointers may only be compared for equality");
1124 CGF, LHS, RHS, MPT, /*IsInequality*/ false);
1125 }
1126
1127 // Compute the comparison instructions for the specified comparison kind.
1128 struct CmpInstInfo {
1129 const char *Name;
1130 llvm::CmpInst::Predicate FCmp;
1131 llvm::CmpInst::Predicate SCmp;
1132 llvm::CmpInst::Predicate UCmp;
1133 };
1134 CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
1135 using FI = llvm::FCmpInst;
1136 using II = llvm::ICmpInst;
1137 switch (Kind) {
1138 case CK_Less:
1139 return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
1140 case CK_Greater:
1141 return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
1142 case CK_Equal:
1143 return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
1144 }
1145 llvm_unreachable("Unrecognised CompareKind enum");
1146 }();
1147
1148 if (ArgTy->hasFloatingRepresentation())
1149 return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
1150 llvm::Twine(InstInfo.Name) + NameSuffix);
1151 if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
1152 auto Inst =
1153 ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
1154 return Builder.CreateICmp(Inst, LHS, RHS,
1155 llvm::Twine(InstInfo.Name) + NameSuffix);
1156 }
1157
1158 llvm_unreachable("unsupported aggregate binary expression should have "
1159 "already been handled");
1160}
1161
1162void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
1163 using llvm::BasicBlock;
1164 using llvm::PHINode;
1165 using llvm::Value;
1166 assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
1167 E->getRHS()->getType()));
1168 const ComparisonCategoryInfo &CmpInfo =
1170 assert(CmpInfo.Record->isTriviallyCopyable() &&
1171 "cannot copy non-trivially copyable aggregate");
1172
1173 QualType ArgTy = E->getLHS()->getType();
1174
1175 if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
1176 !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
1177 !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
1178 return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
1179 }
1180 bool IsComplex = ArgTy->isAnyComplexType();
1181
1182 // Evaluate the operands to the expression and extract their values.
1183 auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
1184 RValue RV = CGF.EmitAnyExpr(E);
1185 if (RV.isScalar())
1186 return {RV.getScalarVal(), nullptr};
1187 if (RV.isAggregate())
1188 return {RV.getAggregatePointer(E->getType(), CGF), nullptr};
1189 assert(RV.isComplex());
1190 return RV.getComplexVal();
1191 };
1192 auto LHSValues = EmitOperand(E->getLHS()),
1193 RHSValues = EmitOperand(E->getRHS());
1194
1195 auto EmitCmp = [&](CompareKind K) {
1196 Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
1197 K, IsComplex ? ".r" : "");
1198 if (!IsComplex)
1199 return Cmp;
1200 assert(K == CompareKind::CK_Equal);
1201 Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
1202 RHSValues.second, K, ".i");
1203 return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
1204 };
1205 auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
1206 return Builder.getInt(VInfo->getIntValue());
1207 };
1208
1209 Value *Select;
1210 if (ArgTy->isNullPtrType()) {
1211 Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
1212 } else if (!CmpInfo.isPartial()) {
1213 Value *SelectOne =
1214 Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
1215 EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
1216 Select = Builder.CreateSelect(EmitCmp(CK_Equal),
1217 EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1218 SelectOne, "sel.eq");
1219 } else {
1220 Value *SelectEq = Builder.CreateSelect(
1221 EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1222 EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
1223 Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
1224 EmitCmpRes(CmpInfo.getGreater()),
1225 SelectEq, "sel.gt");
1226 Select = Builder.CreateSelect(
1227 EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
1228 }
1229 // Create the return value in the destination slot.
1230 EnsureDest(E->getType());
1231 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1232
1233 // Emit the address of the first (and only) field in the comparison category
1234 // type, and initialize it from the constant integer value selected above.
1235 LValue FieldLV = CGF.EmitLValueForFieldInitialization(
1236 DestLV, *CmpInfo.Record->field_begin());
1237 CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
1238
1239 // All done! The result is in the Dest slot.
1240}
1241
1242void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
1243 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
1244 VisitPointerToDataMemberBinaryOperator(E);
1245 else
1246 CGF.ErrorUnsupported(E, "aggregate binary expression");
1247}
1248
1249void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
1250 const BinaryOperator *E) {
1251 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
1252 EmitFinalDestCopy(E->getType(), LV);
1253}
1254
1255/// Is the value of the given expression possibly a reference to or
1256/// into a __block variable?
1257static bool isBlockVarRef(const Expr *E) {
1258 // Make sure we look through parens.
1259 E = E->IgnoreParens();
1260
1261 // Check for a direct reference to a __block variable.
1262 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1263 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
1264 return (var && var->hasAttr<BlocksAttr>());
1265 }
1266
1267 // More complicated stuff.
1268
1269 // Binary operators.
1270 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
1271 // For an assignment or pointer-to-member operation, just care
1272 // about the LHS.
1273 if (op->isAssignmentOp() || op->isPtrMemOp())
1274 return isBlockVarRef(op->getLHS());
1275
1276 // For a comma, just care about the RHS.
1277 if (op->getOpcode() == BO_Comma)
1278 return isBlockVarRef(op->getRHS());
1279
1280 // FIXME: pointer arithmetic?
1281 return false;
1282
1283 // Check both sides of a conditional operator.
1284 } else if (const AbstractConditionalOperator *op =
1285 dyn_cast<AbstractConditionalOperator>(E)) {
1286 return isBlockVarRef(op->getTrueExpr()) ||
1287 isBlockVarRef(op->getFalseExpr());
1288
1289 // OVEs are required to support BinaryConditionalOperators.
1290 } else if (const OpaqueValueExpr *op = dyn_cast<OpaqueValueExpr>(E)) {
1291 if (const Expr *src = op->getSourceExpr())
1292 return isBlockVarRef(src);
1293
1294 // Casts are necessary to get things like (*(int*)&var) = foo().
1295 // We don't really care about the kind of cast here, except
1296 // we don't want to look through l2r casts, because it's okay
1297 // to get the *value* in a __block variable.
1298 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
1299 if (cast->getCastKind() == CK_LValueToRValue)
1300 return false;
1301 return isBlockVarRef(cast->getSubExpr());
1302
1303 // Handle unary operators. Again, just aggressively look through
1304 // it, ignoring the operation.
1305 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
1306 return isBlockVarRef(uop->getSubExpr());
1307
1308 // Look into the base of a field access.
1309 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
1310 return isBlockVarRef(mem->getBase());
1311
1312 // Look into the base of a subscript.
1313 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
1314 return isBlockVarRef(sub->getBase());
1315 }
1316
1317 return false;
1318}
1319
1320void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1321 ApplyAtomGroup Grp(CGF.getDebugInfo());
1322 // For an assignment to work, the value on the right has
1323 // to be compatible with the value on the left.
1324 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1325 E->getRHS()->getType()) &&
1326 "Invalid assignment");
1327
1328 // If the LHS might be a __block variable, and the RHS can
1329 // potentially cause a block copy, we need to evaluate the RHS first
1330 // so that the assignment goes the right place.
1331 // This is pretty semantically fragile.
1332 if (isBlockVarRef(E->getLHS()) &&
1333 E->getRHS()->HasSideEffects(CGF.getContext())) {
1334 // Ensure that we have a destination, and evaluate the RHS into that.
1335 EnsureDest(E->getRHS()->getType());
1336 Visit(E->getRHS());
1337
1338 // Now emit the LHS and copy into it.
1339 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1340
1341 // That copy is an atomic copy if the LHS is atomic.
1342 if (LHS.getType()->isAtomicType() ||
1344 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1345 return;
1346 }
1347
1348 EmitCopy(E->getLHS()->getType(),
1350 needsGC(E->getLHS()->getType()),
1353 Dest);
1354 return;
1355 }
1356
1357 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1358
1359 // If we have an atomic type, evaluate into the destination and then
1360 // do an atomic copy.
1361 if (LHS.getType()->isAtomicType() ||
1363 EnsureDest(E->getRHS()->getType());
1364 Visit(E->getRHS());
1365 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1366 return;
1367 }
1368
1369 // Codegen the RHS so that it stores directly into the LHS.
1370 AggValueSlot LHSSlot = AggValueSlot::forLValue(
1371 LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
1373 // A non-volatile aggregate destination might have volatile member.
1374 if (!LHSSlot.isVolatile() && CGF.hasVolatileMember(E->getLHS()->getType()))
1375 LHSSlot.setVolatile(true);
1376
1377 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
1378
1379 // Copy into the destination if the assignment isn't ignored.
1380 EmitFinalDestCopy(E->getType(), LHS);
1381
1382 if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
1385 E->getType());
1386}
1387
1388void AggExprEmitter::VisitAbstractConditionalOperator(
1389 const AbstractConditionalOperator *E) {
1390 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1391 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1392 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1393
1394 // Bind the common expression if necessary.
1395 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1396
1397 CodeGenFunction::ConditionalEvaluation eval(CGF);
1398 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1399 CGF.getProfileCount(E));
1400
1401 // Save whether the destination's lifetime is externally managed.
1402 bool isExternallyDestructed = Dest.isExternallyDestructed();
1403 bool destructNonTrivialCStruct =
1404 !isExternallyDestructed &&
1406 isExternallyDestructed |= destructNonTrivialCStruct;
1407 Dest.setExternallyDestructed(isExternallyDestructed);
1408
1409 eval.begin(CGF);
1410 CGF.EmitBlock(LHSBlock);
1412 Visit(E->getTrueExpr());
1413 eval.end(CGF);
1414
1415 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1416 CGF.Builder.CreateBr(ContBlock);
1417
1418 // If the result of an agg expression is unused, then the emission
1419 // of the LHS might need to create a destination slot. That's fine
1420 // with us, and we can safely emit the RHS into the same slot, but
1421 // we shouldn't claim that it's already being destructed.
1422 Dest.setExternallyDestructed(isExternallyDestructed);
1423
1424 eval.begin(CGF);
1425 CGF.EmitBlock(RHSBlock);
1427 Visit(E->getFalseExpr());
1428 eval.end(CGF);
1429
1430 if (destructNonTrivialCStruct)
1432 E->getType());
1433
1434 CGF.EmitBlock(ContBlock);
1435}
1436
1437void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
1438 Visit(CE->getChosenSubExpr());
1439}
1440
1441void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1442 Address ArgValue = Address::invalid();
1443 CGF.EmitVAArg(VE, ArgValue, Dest);
1444
1445 // If EmitVAArg fails, emit an error.
1446 if (!ArgValue.isValid()) {
1447 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1448 return;
1449 }
1450}
1451
1452void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1453 // Ensure that we have a slot, but if we already do, remember
1454 // whether it was externally destructed.
1455 bool wasExternallyDestructed = Dest.isExternallyDestructed();
1456 EnsureDest(E->getType());
1457
1458 // We're going to push a destructor if there isn't already one.
1460
1461 Visit(E->getSubExpr());
1462
1463 // Push that destructor we promised.
1464 if (!wasExternallyDestructed)
1465 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1466}
1467
1468void AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1469 AggValueSlot Slot = EnsureSlot(E->getType());
1470 CGF.EmitCXXConstructExpr(E, Slot);
1471}
1472
1473void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1474 const CXXInheritedCtorInitExpr *E) {
1475 AggValueSlot Slot = EnsureSlot(E->getType());
1477 Slot.getAddress(),
1478 E->inheritedFromVBase(), E);
1479}
1480
1481void AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1482 AggValueSlot Slot = EnsureSlot(E->getType());
1483 LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
1484
1485 // We'll need to enter cleanup scopes in case any of the element
1486 // initializers throws an exception or contains branch out of the expressions.
1487 CodeGenFunction::CleanupDeactivationScope scope(CGF);
1488
1489 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1491 e = E->capture_init_end();
1492 i != e; ++i, ++CurField) {
1493 // Emit initialization
1494 LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
1495 if (CurField->hasCapturedVLAType()) {
1496 CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
1497 continue;
1498 }
1499
1500 EmitInitializationToLValue(*i, LV);
1501
1502 // Push a destructor if necessary.
1503 if (QualType::DestructionKind DtorKind =
1504 CurField->getType().isDestructedType()) {
1505 assert(LV.isSimple());
1506 if (DtorKind)
1508 CurField->getType(),
1509 CGF.getDestroyer(DtorKind), false);
1510 }
1511 }
1512}
1513
1514void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1515 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1516 Visit(E->getSubExpr());
1517}
1518
1519void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1520 QualType T = E->getType();
1521 AggValueSlot Slot = EnsureSlot(T);
1522 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1523}
1524
1525void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1526 QualType T = E->getType();
1527 AggValueSlot Slot = EnsureSlot(T);
1528 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1529}
1530
1531/// Determine whether the given cast kind is known to always convert values
1532/// with all zero bits in their value representation to values with all zero
1533/// bits in their value representation.
1534static bool castPreservesZero(const CastExpr *CE) {
1535 switch (CE->getCastKind()) {
1536 // No-ops.
1537 case CK_NoOp:
1538 case CK_UserDefinedConversion:
1539 case CK_ConstructorConversion:
1540 case CK_BitCast:
1541 case CK_ToUnion:
1542 case CK_ToVoid:
1543 // Conversions between (possibly-complex) integral, (possibly-complex)
1544 // floating-point, and bool.
1545 case CK_BooleanToSignedIntegral:
1546 case CK_FloatingCast:
1547 case CK_FloatingComplexCast:
1548 case CK_FloatingComplexToBoolean:
1549 case CK_FloatingComplexToIntegralComplex:
1550 case CK_FloatingComplexToReal:
1551 case CK_FloatingRealToComplex:
1552 case CK_FloatingToBoolean:
1553 case CK_FloatingToIntegral:
1554 case CK_IntegralCast:
1555 case CK_IntegralComplexCast:
1556 case CK_IntegralComplexToBoolean:
1557 case CK_IntegralComplexToFloatingComplex:
1558 case CK_IntegralComplexToReal:
1559 case CK_IntegralRealToComplex:
1560 case CK_IntegralToBoolean:
1561 case CK_IntegralToFloating:
1562 // Reinterpreting integers as pointers and vice versa.
1563 case CK_IntegralToPointer:
1564 case CK_PointerToIntegral:
1565 // Language extensions.
1566 case CK_VectorSplat:
1567 case CK_MatrixCast:
1568 case CK_NonAtomicToAtomic:
1569 case CK_AtomicToNonAtomic:
1570 case CK_HLSLVectorTruncation:
1571 case CK_HLSLMatrixTruncation:
1572 case CK_HLSLElementwiseCast:
1573 case CK_HLSLAggregateSplatCast:
1574 return true;
1575
1576 case CK_BaseToDerivedMemberPointer:
1577 case CK_DerivedToBaseMemberPointer:
1578 case CK_MemberPointerToBoolean:
1579 case CK_NullToMemberPointer:
1580 case CK_ReinterpretMemberPointer:
1581 // FIXME: ABI-dependent.
1582 return false;
1583
1584 case CK_AnyPointerToBlockPointerCast:
1585 case CK_BlockPointerToObjCPointerCast:
1586 case CK_CPointerToObjCPointerCast:
1587 case CK_ObjCObjectLValueCast:
1588 case CK_IntToOCLSampler:
1589 case CK_ZeroToOCLOpaqueType:
1590 // FIXME: Check these.
1591 return false;
1592
1593 case CK_FixedPointCast:
1594 case CK_FixedPointToBoolean:
1595 case CK_FixedPointToFloating:
1596 case CK_FixedPointToIntegral:
1597 case CK_FloatingToFixedPoint:
1598 case CK_IntegralToFixedPoint:
1599 // FIXME: Do all fixed-point types represent zero as all 0 bits?
1600 return false;
1601
1602 case CK_AddressSpaceConversion:
1603 case CK_BaseToDerived:
1604 case CK_DerivedToBase:
1605 case CK_Dynamic:
1606 case CK_NullToPointer:
1607 case CK_PointerToBoolean:
1608 // FIXME: Preserves zeroes only if zero pointers and null pointers have the
1609 // same representation in all involved address spaces.
1610 return false;
1611
1612 case CK_ARCConsumeObject:
1613 case CK_ARCExtendBlockObject:
1614 case CK_ARCProduceObject:
1615 case CK_ARCReclaimReturnedObject:
1616 case CK_CopyAndAutoreleaseBlockObject:
1617 case CK_ArrayToPointerDecay:
1618 case CK_FunctionToPointerDecay:
1619 case CK_BuiltinFnToFnPtr:
1620 case CK_Dependent:
1621 case CK_LValueBitCast:
1622 case CK_LValueToRValue:
1623 case CK_LValueToRValueBitCast:
1624 case CK_UncheckedDerivedToBase:
1625 case CK_HLSLArrayRValue:
1626 return false;
1627 }
1628 llvm_unreachable("Unhandled clang::CastKind enum");
1629}
1630
1631/// isSimpleZero - If emitting this value will obviously just cause a store of
1632/// zero to memory, return true. This can return false if uncertain, so it just
1633/// handles simple cases.
1634static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1635 E = E->IgnoreParens();
1636 while (auto *CE = dyn_cast<CastExpr>(E)) {
1637 if (!castPreservesZero(CE))
1638 break;
1639 E = CE->getSubExpr()->IgnoreParens();
1640 }
1641
1642 // 0
1643 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1644 return IL->getValue() == 0;
1645 // +0.0
1646 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1647 return FL->getValue().isPosZero();
1648 // int()
1651 return true;
1652 // (int*)0 - Null pointer expressions.
1653 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1654 return ICE->getCastKind() == CK_NullToPointer &&
1656 !E->HasSideEffects(CGF.getContext());
1657 // '\0'
1658 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1659 return CL->getValue() == 0;
1660
1661 // Otherwise, hard case: conservatively return false.
1662 return false;
1663}
1664
1665void AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1666 QualType type = LV.getType();
1667 // FIXME: Ignore result?
1668 // FIXME: Are initializers affected by volatile?
1669 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1670 // Storing "i32 0" to a zero'd memory location is a noop.
1671 return;
1673 return EmitNullInitializationToLValue(LV);
1674 } else if (isa<NoInitExpr>(E)) {
1675 // Do nothing.
1676 return;
1677 } else if (type->isReferenceType()) {
1678 RValue RV = CGF.EmitReferenceBindingToExpr(E);
1679 return CGF.EmitStoreThroughLValue(RV, LV);
1680 }
1681
1682 CGF.EmitInitializationToLValue(E, LV, Dest.isZeroed());
1683}
1684
1685void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1686 QualType type = lv.getType();
1687
1688 // If the destination slot is already zeroed out before the aggregate is
1689 // copied into it, we don't have to emit any zeros here.
1690 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1691 return;
1692
1693 if (CGF.hasScalarEvaluationKind(type)) {
1694 // For non-aggregates, we can store the appropriate null constant.
1695 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1696 // Note that the following is not equivalent to
1697 // EmitStoreThroughBitfieldLValue for ARC types.
1698 if (lv.isBitField()) {
1700 } else {
1701 assert(lv.isSimple());
1702 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1703 }
1704 } else {
1705 // There's a potential optimization opportunity in combining
1706 // memsets; that would be easy for arrays, but relatively
1707 // difficult for structures with the current code.
1708 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1709 }
1710}
1711
1712void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
1713 VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
1715 E->getArrayFiller());
1716}
1717
1718void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1719 if (E->hadArrayRangeDesignator())
1720 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1721
1722 if (E->isTransparent())
1723 return Visit(E->getInit(0));
1724
1725 VisitCXXParenListOrInitListExpr(
1726 E, E->inits(), E->getInitializedFieldInUnion(), E->getArrayFiller());
1727}
1728
1729void AggExprEmitter::VisitCXXParenListOrInitListExpr(
1730 Expr *ExprToVisit, ArrayRef<Expr *> InitExprs,
1731 FieldDecl *InitializedFieldInUnion, Expr *ArrayFiller) {
1732#if 0
1733 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1734 // (Length of globals? Chunks of zeroed-out space?).
1735 //
1736 // If we can, prefer a copy from a global; this is a lot less code for long
1737 // globals, and it's easier for the current optimizers to analyze.
1738 if (llvm::Constant *C =
1739 CGF.CGM.EmitConstantExpr(ExprToVisit, ExprToVisit->getType(), &CGF)) {
1740 llvm::GlobalVariable* GV =
1741 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1742 llvm::GlobalValue::InternalLinkage, C, "");
1743 EmitFinalDestCopy(ExprToVisit->getType(),
1744 CGF.MakeAddrLValue(GV, ExprToVisit->getType()));
1745 return;
1746 }
1747#endif
1748
1749 // HLSL initialization lists in the AST are an expansion which can contain
1750 // side-effecting expressions wrapped in opaque value expressions. To properly
1751 // emit these we need to emit the opaque values before we emit the argument
1752 // expressions themselves. This is a little hacky, but it prevents us needing
1753 // to do a bigger AST-level change for a language feature that we need
1754 // deprecate in the near future. See related HLSL language proposals:
1755 // * 0005-strict-initializer-lists.md
1756 // * https://github.com/microsoft/hlsl-specs/pull/325
1757 if (CGF.getLangOpts().HLSL && isa<InitListExpr>(ExprToVisit))
1759 CGF, cast<InitListExpr>(ExprToVisit));
1760
1761 AggValueSlot Dest = EnsureSlot(ExprToVisit->getType());
1762
1763 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), ExprToVisit->getType());
1764
1765 // Handle initialization of an array.
1766 if (ExprToVisit->getType()->isConstantArrayType()) {
1767 auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1768 EmitArrayInit(Dest.getAddress(), AType, ExprToVisit->getType(), ExprToVisit,
1769 InitExprs, ArrayFiller);
1770 return;
1771 } else if (ExprToVisit->getType()->isVariableArrayType()) {
1772 // A variable array type that has an initializer can only do empty
1773 // initialization. And because this feature is not exposed as an extension
1774 // in C++, we can safely memset the array memory to zero.
1775 assert(InitExprs.size() == 0 &&
1776 "you can only use an empty initializer with VLAs");
1777 CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());
1778 return;
1779 }
1780
1781 assert(ExprToVisit->getType()->isRecordType() &&
1782 "Only support structs/unions here!");
1783
1784 // Do struct initialization; this code just sets each individual member
1785 // to the approprate value. This makes bitfield support automatic;
1786 // the disadvantage is that the generated code is more difficult for
1787 // the optimizer, especially with bitfields.
1788 unsigned NumInitElements = InitExprs.size();
1789 RecordDecl *record = ExprToVisit->getType()->castAsRecordDecl();
1790
1791 // We'll need to enter cleanup scopes in case any of the element
1792 // initializers throws an exception.
1793 CodeGenFunction::CleanupDeactivationScope DeactivateCleanups(CGF);
1794
1795 unsigned curInitIndex = 0;
1796
1797 // Emit initialization of base classes.
1798 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1799 assert(NumInitElements >= CXXRD->getNumBases() &&
1800 "missing initializer for base class");
1801 for (auto &Base : CXXRD->bases()) {
1802 assert(!Base.isVirtual() && "should not see vbases here");
1803 auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1805 Dest.getAddress(), CXXRD, BaseRD,
1806 /*isBaseVirtual*/ false);
1807 AggValueSlot AggSlot = AggValueSlot::forAddr(
1808 V, Qualifiers(), AggValueSlot::IsDestructed,
1810 CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
1811 CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot);
1812
1813 if (QualType::DestructionKind dtorKind =
1814 Base.getType().isDestructedType())
1815 CGF.pushDestroyAndDeferDeactivation(dtorKind, V, Base.getType());
1816 }
1817 }
1818
1819 // Prepare a 'this' for CXXDefaultInitExprs.
1820 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1821
1822 const bool ZeroInitPadding =
1823 CGF.CGM.shouldZeroInitPadding() && !Dest.isZeroed();
1824
1825 if (record->isUnion()) {
1826 // Only initialize one field of a union. The field itself is
1827 // specified by the initializer list.
1828 if (!InitializedFieldInUnion) {
1829 // Empty union; we have nothing to do.
1830
1831#ifndef NDEBUG
1832 // Make sure that it's really an empty and not a failure of
1833 // semantic analysis.
1834 for (const auto *Field : record->fields())
1835 assert(
1836 (Field->isUnnamedBitField() || Field->isAnonymousStructOrUnion()) &&
1837 "Only unnamed bitfields or anonymous class allowed");
1838#endif
1839 return;
1840 }
1841
1842 // FIXME: volatility
1843 FieldDecl *Field = InitializedFieldInUnion;
1844
1845 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1846 if (NumInitElements) {
1847 // Store the initializer into the field
1848 EmitInitializationToLValue(InitExprs[0], FieldLoc);
1849 if (ZeroInitPadding) {
1850 uint64_t TotalSize = CGF.getContext().toBits(
1851 Dest.getPreferredSize(CGF.getContext(), DestLV.getType()));
1852 uint64_t FieldSize = CGF.getContext().getTypeSize(FieldLoc.getType());
1853 DoZeroInitPadding(FieldSize, TotalSize, nullptr);
1854 }
1855 } else {
1856 // Default-initialize to null.
1857 if (ZeroInitPadding)
1858 EmitNullInitializationToLValue(DestLV);
1859 else
1860 EmitNullInitializationToLValue(FieldLoc);
1861 }
1862 return;
1863 }
1864
1865 // Here we iterate over the fields; this makes it simpler to both
1866 // default-initialize fields and skip over unnamed fields.
1867 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(record);
1868 uint64_t PaddingStart = 0;
1869
1870 for (const auto *field : record->fields()) {
1871 // We're done once we hit the flexible array member.
1872 if (field->getType()->isIncompleteArrayType())
1873 break;
1874
1875 // Always skip anonymous bitfields.
1876 if (field->isUnnamedBitField())
1877 continue;
1878
1879 // We're done if we reach the end of the explicit initializers, we
1880 // have a zeroed object, and the rest of the fields are
1881 // zero-initializable.
1882 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1883 CGF.getTypes().isZeroInitializable(ExprToVisit->getType()))
1884 break;
1885
1886 if (ZeroInitPadding)
1887 DoZeroInitPadding(PaddingStart,
1888 Layout.getFieldOffset(field->getFieldIndex()), field);
1889
1890 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1891 // We never generate write-barries for initialized fields.
1892 LV.setNonGC(true);
1893
1894 if (curInitIndex < NumInitElements) {
1895 // Store the initializer into the field.
1896 EmitInitializationToLValue(InitExprs[curInitIndex++], LV);
1897 } else {
1898 // We're out of initializers; default-initialize to null
1899 EmitNullInitializationToLValue(LV);
1900 }
1901
1902 // Push a destructor if necessary.
1903 // FIXME: if we have an array of structures, all explicitly
1904 // initialized, we can end up pushing a linear number of cleanups.
1905 if (QualType::DestructionKind dtorKind =
1906 field->getType().isDestructedType()) {
1907 assert(LV.isSimple());
1908 if (dtorKind) {
1910 field->getType(),
1911 CGF.getDestroyer(dtorKind), false);
1912 }
1913 }
1914 }
1915 if (ZeroInitPadding) {
1916 uint64_t TotalSize = CGF.getContext().toBits(
1917 Dest.getPreferredSize(CGF.getContext(), DestLV.getType()));
1918 DoZeroInitPadding(PaddingStart, TotalSize, nullptr);
1919 }
1920}
1921
1922void AggExprEmitter::DoZeroInitPadding(uint64_t &PaddingStart,
1923 uint64_t PaddingEnd,
1924 const FieldDecl *NextField) {
1925
1926 auto InitBytes = [&](uint64_t StartBit, uint64_t EndBit) {
1927 CharUnits Start = CGF.getContext().toCharUnitsFromBits(StartBit);
1928 CharUnits End = CGF.getContext().toCharUnitsFromBits(EndBit);
1930 if (!Start.isZero())
1931 Addr = Builder.CreateConstGEP(Addr, Start.getQuantity());
1932 llvm::Constant *SizeVal = Builder.getInt64((End - Start).getQuantity());
1933 CGF.Builder.CreateMemSet(Addr, Builder.getInt8(0), SizeVal, false);
1934 };
1935
1936 if (NextField != nullptr && NextField->isBitField()) {
1937 // For bitfield, zero init StorageSize before storing the bits. So we don't
1938 // need to handle big/little endian.
1939 const CGRecordLayout &RL =
1940 CGF.getTypes().getCGRecordLayout(NextField->getParent());
1941 const CGBitFieldInfo &Info = RL.getBitFieldInfo(NextField);
1942 uint64_t StorageStart = CGF.getContext().toBits(Info.StorageOffset);
1943 if (StorageStart + Info.StorageSize > PaddingStart) {
1944 if (StorageStart > PaddingStart)
1945 InitBytes(PaddingStart, StorageStart);
1946 Address Addr = Dest.getAddress();
1947 if (!Info.StorageOffset.isZero())
1948 Addr = Builder.CreateConstGEP(Addr.withElementType(CGF.CharTy),
1949 Info.StorageOffset.getQuantity());
1950 Addr = Addr.withElementType(
1951 llvm::Type::getIntNTy(CGF.getLLVMContext(), Info.StorageSize));
1952 Builder.CreateStore(Builder.getIntN(Info.StorageSize, 0), Addr);
1953 PaddingStart = StorageStart + Info.StorageSize;
1954 }
1955 return;
1956 }
1957
1958 if (PaddingStart < PaddingEnd)
1959 InitBytes(PaddingStart, PaddingEnd);
1960 if (NextField != nullptr)
1961 PaddingStart =
1962 PaddingEnd + CGF.getContext().getTypeSize(NextField->getType());
1963}
1964
1965void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1966 llvm::Value *outerBegin) {
1967 // Emit the common subexpression.
1968 CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1969
1970 Address destPtr = EnsureSlot(E->getType()).getAddress();
1971 uint64_t numElements = E->getArraySize().getZExtValue();
1972
1973 if (!numElements)
1974 return;
1975
1976 // destPtr is an array*. Construct an elementType* by drilling down a level.
1977 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1978 llvm::Value *indices[] = {zero, zero};
1979 llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getElementType(),
1980 destPtr.emitRawPointer(CGF),
1981 indices, "arrayinit.begin");
1982
1983 // Prepare to special-case multidimensional array initialization: we avoid
1984 // emitting multiple destructor loops in that case.
1985 if (!outerBegin)
1986 outerBegin = begin;
1987 ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1988
1989 QualType elementType =
1991 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1992 CharUnits elementAlign =
1993 destPtr.getAlignment().alignmentOfArrayElement(elementSize);
1994 llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
1995
1996 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1997 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1998
1999 // Jump into the body.
2000 CGF.EmitBlock(bodyBB);
2001 llvm::PHINode *index =
2002 Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
2003 index->addIncoming(zero, entryBB);
2004 llvm::Value *element =
2005 Builder.CreateInBoundsGEP(llvmElementType, begin, index);
2006
2008 CGF.ConvergenceTokenStack.push_back(CGF.emitConvergenceLoopToken(bodyBB));
2009
2010 // Prepare for a cleanup.
2011 QualType::DestructionKind dtorKind = elementType.isDestructedType();
2012 EHScopeStack::stable_iterator cleanup;
2013 if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
2014 if (outerBegin->getType() != element->getType())
2015 outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
2016 CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
2017 elementAlign,
2018 CGF.getDestroyer(dtorKind));
2020 } else {
2021 dtorKind = QualType::DK_none;
2022 }
2023
2024 // Emit the actual filler expression.
2025 {
2026 // Temporaries created in an array initialization loop are destroyed
2027 // at the end of each iteration.
2028 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
2029 CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
2030 LValue elementLV = CGF.MakeAddrLValue(
2031 Address(element, llvmElementType, elementAlign), elementType);
2032
2033 if (InnerLoop) {
2034 // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
2035 auto elementSlot = AggValueSlot::forLValue(
2036 elementLV, AggValueSlot::IsDestructed,
2039 AggExprEmitter(CGF, elementSlot, false)
2040 .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
2041 } else
2042 EmitInitializationToLValue(E->getSubExpr(), elementLV);
2043 }
2044
2045 // Move on to the next element.
2046 llvm::Value *nextIndex = Builder.CreateNUWAdd(
2047 index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
2048 index->addIncoming(nextIndex, Builder.GetInsertBlock());
2049
2050 // Leave the loop if we're done.
2051 llvm::Value *done = Builder.CreateICmpEQ(
2052 nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
2053 "arrayinit.done");
2054 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
2055 Builder.CreateCondBr(done, endBB, bodyBB);
2056
2058 CGF.ConvergenceTokenStack.pop_back();
2059
2060 CGF.EmitBlock(endBB);
2061
2062 // Leave the partial-array cleanup if we entered one.
2063 if (dtorKind)
2064 CGF.DeactivateCleanupBlock(cleanup, index);
2065}
2066
2067void AggExprEmitter::VisitDesignatedInitUpdateExpr(
2068 DesignatedInitUpdateExpr *E) {
2069 AggValueSlot Dest = EnsureSlot(E->getType());
2070
2071 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
2072 EmitInitializationToLValue(E->getBase(), DestLV);
2073 VisitInitListExpr(E->getUpdater());
2074}
2075
2076//===----------------------------------------------------------------------===//
2077// Entry Points into this File
2078//===----------------------------------------------------------------------===//
2079
2080/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
2081/// non-zero bytes that will be stored when outputting the initializer for the
2082/// specified initializer expression.
2084 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2085 E = MTE->getSubExpr();
2086 E = E->IgnoreParenNoopCasts(CGF.getContext());
2087
2088 // 0 and 0.0 won't require any non-zero stores!
2089 if (isSimpleZero(E, CGF))
2090 return CharUnits::Zero();
2091
2092 // If this is an initlist expr, sum up the size of sizes of the (present)
2093 // elements. If this is something weird, assume the whole thing is non-zero.
2094 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2095 while (ILE && ILE->isTransparent())
2096 ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
2097 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
2098 return CGF.getContext().getTypeSizeInChars(E->getType());
2099
2100 // InitListExprs for structs have to be handled carefully. If there are
2101 // reference members, we need to consider the size of the reference, not the
2102 // referencee. InitListExprs for unions and arrays can't have references.
2103 if (const RecordType *RT = E->getType()->getAsCanonical<RecordType>()) {
2104 if (!RT->isUnionType()) {
2105 RecordDecl *SD = RT->getDecl()->getDefinitionOrSelf();
2106 CharUnits NumNonZeroBytes = CharUnits::Zero();
2107
2108 unsigned ILEElement = 0;
2109 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
2110 while (ILEElement != CXXRD->getNumBases())
2111 NumNonZeroBytes +=
2112 GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
2113 for (const auto *Field : SD->fields()) {
2114 // We're done once we hit the flexible array member or run out of
2115 // InitListExpr elements.
2116 if (Field->getType()->isIncompleteArrayType() ||
2117 ILEElement == ILE->getNumInits())
2118 break;
2119 if (Field->isUnnamedBitField())
2120 continue;
2121
2122 const Expr *E = ILE->getInit(ILEElement++);
2123
2124 // Reference values are always non-null and have the width of a pointer.
2125 if (Field->getType()->isReferenceType())
2126 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
2128 else
2129 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
2130 }
2131
2132 return NumNonZeroBytes;
2133 }
2134 }
2135
2136 // FIXME: This overestimates the number of non-zero bytes for bit-fields.
2137 CharUnits NumNonZeroBytes = CharUnits::Zero();
2138 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
2139 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
2140 return NumNonZeroBytes;
2141}
2142
2143/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
2144/// zeros in it, emit a memset and avoid storing the individual zeros.
2145///
2146static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
2147 CodeGenFunction &CGF) {
2148 // If the slot is already known to be zeroed, nothing to do. Don't mess with
2149 // volatile stores.
2150 if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
2151 return;
2152
2153 // C++ objects with a user-declared constructor don't need zero'ing.
2154 if (CGF.getLangOpts().CPlusPlus)
2155 if (const RecordType *RT = CGF.getContext()
2157 ->getAsCanonical<RecordType>()) {
2158 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
2160 return;
2161 }
2162
2163 // If the type is 16-bytes or smaller, prefer individual stores over memset.
2164 CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
2165 if (Size <= CharUnits::fromQuantity(16))
2166 return;
2167
2168 // Check to see if over 3/4 of the initializer are known to be zero. If so,
2169 // we prefer to emit memset + individual stores for the rest.
2170 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
2171 if (NumNonZeroBytes * 4 > Size)
2172 return;
2173
2174 // Okay, it seems like a good idea to use an initial memset, emit the call.
2175 llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
2176
2177 Address Loc = Slot.getAddress().withElementType(CGF.Int8Ty);
2178 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
2179
2180 // Tell the AggExprEmitter that the slot is known zero.
2181 Slot.setZeroed();
2182}
2183
2184/// EmitAggExpr - Emit the computation of the specified expression of aggregate
2185/// type. The result is computed into DestPtr. Note that if DestPtr is null,
2186/// the value of the aggregate expression is not needed. If VolatileDest is
2187/// true, DestPtr cannot be 0.
2189 assert(E && hasAggregateEvaluationKind(E->getType()) &&
2190 "Invalid aggregate expression to emit");
2191 assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
2192 "slot has bits but no address");
2193
2194 // Optimize the slot if possible.
2195 CheckAggExprForMemSetUse(Slot, E, *this);
2196
2197 AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr *>(E));
2198}
2199
2210
2212 const LValue &Src,
2213 ExprValueKind SrcKind) {
2214 return AggExprEmitter(*this, Dest, Dest.isIgnored())
2215 .EmitFinalDestCopy(Type, Src, SrcKind);
2216}
2217
2220 if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
2222
2223 // Empty fields can overlap earlier fields.
2224 if (FD->getType()->getAsCXXRecordDecl()->isEmpty())
2226
2227 // If the field lies entirely within the enclosing class's nvsize, its tail
2228 // padding cannot overlap any already-initialized object. (The only subobjects
2229 // with greater addresses that might already be initialized are vbases.)
2230 const RecordDecl *ClassRD = FD->getParent();
2231 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
2232 if (Layout.getFieldOffset(FD->getFieldIndex()) +
2233 getContext().getTypeSize(FD->getType()) <=
2234 (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
2236
2237 // The tail padding may contain values we need to preserve.
2239}
2240
2242 const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
2243 // If the most-derived object is a field declared with [[no_unique_address]],
2244 // the tail padding of any virtual base could be reused for other subobjects
2245 // of that field's class.
2246 if (IsVirtual)
2248
2249 // Empty bases can overlap earlier bases.
2250 if (BaseRD->isEmpty())
2252
2253 // If the base class is laid out entirely within the nvsize of the derived
2254 // class, its tail padding cannot yet be initialized, so we can issue
2255 // stores at the full width of the base class.
2256 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2257 if (Layout.getBaseClassOffset(BaseRD) +
2258 getContext().getASTRecordLayout(BaseRD).getSize() <=
2259 Layout.getNonVirtualSize())
2261
2262 // The tail padding may contain values we need to preserve.
2264}
2265
2267 AggValueSlot::Overlap_t MayOverlap,
2268 bool isVolatile) {
2269 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
2270
2271 Address DestPtr = Dest.getAddress();
2272 Address SrcPtr = Src.getAddress();
2273
2274 if (getLangOpts().CPlusPlus) {
2275 if (const auto *Record = Ty->getAsCXXRecordDecl()) {
2276 assert((Record->hasTrivialCopyConstructor() ||
2277 Record->hasTrivialCopyAssignment() ||
2278 Record->hasTrivialMoveConstructor() ||
2279 Record->hasTrivialMoveAssignment() ||
2280 Record->hasAttr<TrivialABIAttr>() || Record->isUnion()) &&
2281 "Trying to aggregate-copy a type without a trivial copy/move "
2282 "constructor or assignment operator");
2283 // Ignore empty classes in C++.
2284 if (Record->isEmpty())
2285 return;
2286 }
2287 }
2288
2289 if (getLangOpts().CUDAIsDevice) {
2291 if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
2292 Src))
2293 return;
2294 } else if (Ty->isCUDADeviceBuiltinTextureType()) {
2295 if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
2296 Src))
2297 return;
2298 }
2299 }
2300
2302 if (CGM.getHLSLRuntime().emitBufferCopy(*this, DestPtr, SrcPtr, Ty))
2303 return;
2304
2305 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
2306 // C99 6.5.16.1p3, which states "If the value being stored in an object is
2307 // read from another object that overlaps in anyway the storage of the first
2308 // object, then the overlap shall be exact and the two objects shall have
2309 // qualified or unqualified versions of a compatible type."
2310 //
2311 // memcpy is not defined if the source and destination pointers are exactly
2312 // equal, but other compilers do this optimization, and almost every memcpy
2313 // implementation handles this case safely. If there is a libc that does not
2314 // safely handle this, we can add a target hook.
2315
2316 // Get data size info for this aggregate. Don't copy the tail padding if this
2317 // might be a potentially-overlapping subobject, since the tail padding might
2318 // be occupied by a different object. Otherwise, copying it is fine.
2320 if (MayOverlap)
2321 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
2322 else
2323 TypeInfo = getContext().getTypeInfoInChars(Ty);
2324
2325 llvm::Value *SizeVal = nullptr;
2326 if (TypeInfo.Width.isZero()) {
2327 // But note that getTypeInfo returns 0 for a VLA.
2328 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
2329 getContext().getAsArrayType(Ty))) {
2330 QualType BaseEltTy;
2331 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
2332 TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
2333 assert(!TypeInfo.Width.isZero());
2334 SizeVal = Builder.CreateNUWMul(
2335 SizeVal,
2336 llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));
2337 }
2338 }
2339 if (!SizeVal) {
2340 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());
2341 }
2342
2343 // FIXME: If we have a volatile struct, the optimizer can remove what might
2344 // appear to be `extra' memory ops:
2345 //
2346 // volatile struct { int i; } a, b;
2347 //
2348 // int main() {
2349 // a = b;
2350 // a = b;
2351 // }
2352 //
2353 // we need to use a different call here. We use isVolatile to indicate when
2354 // either the source or the destination is volatile.
2355
2356 DestPtr = DestPtr.withElementType(Int8Ty);
2357 SrcPtr = SrcPtr.withElementType(Int8Ty);
2358
2359 // Don't do any of the memmove_collectable tests if GC isn't set.
2360 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
2361 // fall through
2362 } else if (const auto *Record = Ty->getAsRecordDecl()) {
2363 if (Record->hasObjectMember()) {
2364 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2365 SizeVal);
2366 return;
2367 }
2368 } else if (Ty->isArrayType()) {
2369 QualType BaseType = getContext().getBaseElementType(Ty);
2370 if (const auto *Record = BaseType->getAsRecordDecl()) {
2371 if (Record->hasObjectMember()) {
2372 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2373 SizeVal);
2374 return;
2375 }
2376 }
2377 }
2378
2379 auto *Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
2380 addInstToCurrentSourceAtom(Inst, nullptr);
2381 emitPFPPostCopyUpdates(DestPtr, SrcPtr, Ty);
2382
2383 // Determine the metadata to describe the position of any padding in this
2384 // memcpy, as well as the TBAA tags for the members of the struct, in case
2385 // the optimizer wishes to expand it in to scalar memory operations.
2386 if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
2387 Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
2388
2389 if (CGM.getCodeGenOpts().NewStructPathTBAA) {
2390 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
2391 Dest.getTBAAInfo(), Src.getTBAAInfo());
2392 CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
2393 }
2394}
Defines the clang::ASTContext interface.
#define V(N, I)
CompareKind
@ CK_Greater
@ CK_Less
@ CK_Equal
static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF)
GetNumNonZeroBytesInInit - Get an approximate count of the number of non-zero bytes that will be stor...
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 bool isBlockVarRef(const Expr *E)
Is the value of the given expression possibly a reference to or into a __block variable?
static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF)
isSimpleZero - If emitting this value will obviously just cause a store of zero to memory,...
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 bool castPreservesZero(const CastExpr *CE)
Determine whether the given cast kind is known to always convert values with all zero bits in their v...
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)
static bool isTrivialFiller(Expr *e)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
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.
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.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:228
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...
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4356
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4534
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4540
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4546
llvm::APInt getArraySize() const
Definition Expr.h:5990
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5983
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5988
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
QualType getElementType() const
Definition TypeBase.h:3796
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
Expr * getRHS() const
Definition Expr.h:4093
Opcode getOpcode() const
Definition Expr.h:4086
CXXTemporary * getTemporary()
Definition ExprCXX.h:1515
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
bool constructsVBase() const
Determine whether this constructor is actually constructing a base class (rather than a complete obje...
Definition ExprCXX.h:1796
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
bool inheritedFromVBase() const
Determine whether the inherited constructor is inherited from a virtual base of the object we constru...
Definition ExprCXX.h:1806
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
FieldDecl * getInitializedFieldInUnion()
Definition ExprCXX.h:5215
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:1347
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:610
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1307
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1284
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1334
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition DeclCXX.h:780
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1608
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
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:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4887
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:691
CharUnits getPreferredSize(ASTContext &Ctx, QualType Type) const
Get the preferred size to use when storing a value to this slot.
Definition CGValue.h:729
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:721
IsZeroed_t isZeroed() const
Definition CGValue.h:722
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:701
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:705
RValue asRValue() const
Definition CGValue.h:713
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Definition CGValue.h:687
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:430
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
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
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.
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:2615
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:3038
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:6585
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7336
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:701
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition CGExpr.cpp:7164
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:2299
@ 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:2599
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2272
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition CGExpr.cpp:7341
void CreateCoercedStore(llvm::Value *Src, QualType SrcFETy, Address Dst, llvm::TypeSize DstSize, bool DstIsVolatile)
Create a store to.
Definition CGCall.cpp:1567
llvm::ConvergenceControlInst * emitConvergenceLoopToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3449
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
const TargetInfo & getTarget() const
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:257
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6448
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2524
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
Definition CGDecl.cpp:2324
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:1357
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:5939
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:214
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:158
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6387
const TargetCodeGenInfo & getTargetHooks() const
void EmitLifetimeEnd(llvm::Value *Addr)
Definition CGDecl.cpp:1369
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:230
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:2776
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2352
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:560
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:279
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
CleanupKind getCleanupKind(QualType::DestructionKind kind)
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:914
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:7345
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:1681
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:2403
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Definition CGExpr.cpp:338
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:1716
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:643
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1396
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...
bool isPointerZeroInitializable(QualType T)
Check if the pointer type can be zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
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:654
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:324
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 * getGreater() const
const ValueInfo * getEqualOrEquiv() const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3337
const Expr * getInitializer() const
Definition Expr.h:3636
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3878
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
bool hasAttr() const
Definition DeclBase.h:585
InitListExpr * getUpdater() const
Definition Expr.h:5936
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
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:3124
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3093
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:3695
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:282
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3178
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3281
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3263
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
const Expr * getSubExpr() const
Definition Expr.h:1065
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2469
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5429
unsigned getNumInits() const
Definition Expr.h:5335
bool hadArrayRangeDesignator() const
Definition Expr.h:5483
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5405
const Expr * getInit(unsigned Init) const
Definition Expr.h:5357
ArrayRef< Expr * > inits() const
Definition Expr.h:5355
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2110
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition ExprCXX.h:2084
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1407
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3715
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1231
bool isUnique() const
Definition Expr.h:1239
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2202
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2962
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
@ PCK_Struct
The type is a struct containing a field whose type is neither PCK_Trivial nor PCK_VolatileTrivial.
Definition TypeBase.h:1532
Represents a struct/union/class.
Definition Decl.h:4343
bool hasObjectMember() const
Definition Decl.h:4403
field_range fields() const
Definition Decl.h:4546
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4543
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4531
field_iterator field_begin() const
Definition Decl.cpp:5249
Encodes a location in the source.
CompoundStmt * getSubStmt()
Definition Expr.h:4615
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool isUnion() const
Definition Decl.h:3946
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:490
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:8785
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8781
bool isPointerType() const
Definition TypeBase.h:8682
bool isReferenceType() const
Definition TypeBase.h:8706
bool isScalarType() const
Definition TypeBase.h:9154
bool isVariableArrayType() const
Definition TypeBase.h:8793
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5460
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8817
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2310
bool isMemberPointerType() const
Definition TypeBase.h:8763
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5469
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2397
bool isVectorType() const
Definition TypeBase.h:8821
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2983
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8809
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Expr * getSubExpr() const
Definition Expr.h:2288
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
Represents a GCC generic vector type.
Definition TypeBase.h:4237
Definition SPIR.cpp:35
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< AtomicType > atomicType
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1488
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Result
The result type of a method or function.
Definition TypeBase.h:905
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
unsigned long 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