clang 24.0.0git
CodeGenFunction.cpp
Go to the documentation of this file.
1//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
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 coordinates the per-function state used while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenFunction.h"
14#include "CGBlocks.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.h"
17#include "CGCleanup.h"
18#include "CGDebugInfo.h"
19#include "CGHLSLRuntime.h"
20#include "CGOpenMPRuntime.h"
21#include "CodeGenModule.h"
22#include "CodeGenPGO.h"
23#include "TargetInfo.h"
25#include "clang/AST/ASTLambda.h"
26#include "clang/AST/Attr.h"
27#include "clang/AST/Decl.h"
28#include "clang/AST/DeclCXX.h"
29#include "clang/AST/Expr.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/Dominators.h"
46#include "llvm/IR/FPEnv.h"
47#include "llvm/IR/Instruction.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/Intrinsics.h"
50#include "llvm/IR/IntrinsicsPowerPC.h"
51#include "llvm/IR/MDBuilder.h"
52#include "llvm/Support/CRC.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include "llvm/Support/SipHash.h"
55#include "llvm/Support/xxhash.h"
56#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include <optional>
59
60using namespace clang;
61using namespace CodeGen;
62
63CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
64 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
65 Builder(cgm, cgm.getModule().getContext(), CGBuilderInserterTy(this)),
67 DebugInfo(CGM.getModuleDebugInfo()),
68 PGO(std::make_unique<CodeGenPGO>(cgm)),
69 ShouldEmitLifetimeMarkers(CodeGenUtils::shouldEmitLifetimeMarkers(
70 CGM.getCodeGenOpts(), CGM.getLangOpts())) {
71 if (!suppressNewContext)
72 CGM.getCXXABI().getMangleContext().startNewFunction();
73 EHStack.setCGF(this);
74
76}
77
79 const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
80 if (!FD)
81 FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
82 return FD;
83}
84
86 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
87 assert(DeferredDeactivationCleanupStack.empty() &&
88 "missed to deactivate a cleanup");
89
90 if (getLangOpts().OpenMP && CurFn)
91 CGM.getOpenMPRuntime().functionFinished(*this);
92
93 // If we have an OpenMPIRBuilder we want to finalize functions (incl.
94 // outlining etc) at some point. Doing it once the function codegen is done
95 // seems to be a reasonable spot. We do it here, as opposed to the deletion
96 // time of the CodeGenModule, because we have to ensure the IR has not yet
97 // been "emitted" to the outside, thus, modifications are still sensible.
98 if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
99 CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
100}
101
102// Map the LangOption for exception behavior into
103// the corresponding enum in the IR.
104llvm::fp::ExceptionBehavior
106
107 switch (Kind) {
108 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
109 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
110 case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
111 default:
112 llvm_unreachable("Unsupported FP Exception Behavior");
113 }
114}
115
117 llvm::FastMathFlags FMF;
118 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
119 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
120 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
121 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
122 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
123 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
124 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
125 Builder.setFastMathFlags(FMF);
126}
127
129 const Expr *E)
130 : CGF(CGF) {
131 ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
132}
133
135 FPOptions FPFeatures)
136 : CGF(CGF) {
137 ConstructorHelper(FPFeatures);
138}
139
140void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
141 OldFPFeatures = CGF.CurFPFeatures;
142 CGF.CurFPFeatures = FPFeatures;
143
144 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
145 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
146
147 if (OldFPFeatures == FPFeatures)
148 return;
149
150 FMFGuard.emplace(CGF.Builder);
151
152 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
153 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
154 auto NewExceptionBehavior =
156 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
157
158 CGF.SetFastMathFlags(FPFeatures);
159
160 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
161 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
162 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
163 (NewExceptionBehavior == llvm::fp::ebIgnore &&
164 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
165 "FPConstrained should be enabled on entire function");
166
167 auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
168 auto OldValue =
169 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
170 auto NewValue = OldValue & Value;
171 if (OldValue != NewValue)
172 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
173 };
174 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
175}
176
178 CGF.CurFPFeatures = OldFPFeatures;
179 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
180 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
181}
182
183static LValue
184makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType,
185 bool MightBeSigned, CodeGenFunction &CGF,
186 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
187 LValueBaseInfo BaseInfo;
188 TBAAAccessInfo TBAAInfo;
189 CharUnits Alignment =
190 CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType);
191 Address Addr =
192 MightBeSigned
193 ? CGF.makeNaturalAddressForPointer(V, T, Alignment, false, nullptr,
194 nullptr, IsKnownNonNull)
195 : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull);
196 return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
197}
198
199LValue
201 KnownNonNull_t IsKnownNonNull) {
202 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
203 /*MightBeSigned*/ true, *this,
204 IsKnownNonNull);
205}
206
207LValue
209 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
210 /*MightBeSigned*/ true, *this);
211}
212
214 QualType T) {
215 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
216 /*MightBeSigned*/ false, *this);
217}
218
220 QualType T) {
221 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
222 /*MightBeSigned*/ false, *this);
223}
224
226 return CGM.getTypes().ConvertTypeForMem(T);
227}
228
230 return CGM.getTypes().ConvertType(T);
231}
232
234 llvm::Type *LLVMTy) {
235 return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
236}
237
239 type = type.getCanonicalType();
240 while (true) {
241 switch (type->getTypeClass()) {
242#define TYPE(name, parent)
243#define ABSTRACT_TYPE(name, parent)
244#define NON_CANONICAL_TYPE(name, parent) case Type::name:
245#define DEPENDENT_TYPE(name, parent) case Type::name:
246#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
247#include "clang/AST/TypeNodes.inc"
248 llvm_unreachable("non-canonical or dependent type in IR-generation");
249
250 case Type::Auto:
251 case Type::DeducedTemplateSpecialization:
252 llvm_unreachable("undeduced type in IR-generation");
253
254 // Various scalar types.
255 case Type::Builtin:
256 case Type::Pointer:
257 case Type::BlockPointer:
258 case Type::LValueReference:
259 case Type::RValueReference:
260 case Type::MemberPointer:
261 case Type::Vector:
262 case Type::ExtVector:
263 case Type::ConstantMatrix:
264 case Type::FunctionProto:
265 case Type::FunctionNoProto:
266 case Type::Enum:
267 case Type::ObjCObjectPointer:
268 case Type::Pipe:
269 case Type::BitInt:
270 case Type::HLSLAttributedResource:
271 case Type::HLSLInlineSpirv:
272 case Type::OverflowBehavior:
273 return TEK_Scalar;
274
275 // Complexes.
276 case Type::Complex:
277 return TEK_Complex;
278
279 // Arrays, records, and Objective-C objects.
280 case Type::ConstantArray:
281 case Type::IncompleteArray:
282 case Type::VariableArray:
283 case Type::Record:
284 case Type::ObjCObject:
285 case Type::ObjCInterface:
286 case Type::ArrayParameter:
287 return TEK_Aggregate;
288
289 // We operate on atomic values according to their underlying type.
290 case Type::Atomic:
291 type = cast<AtomicType>(type)->getValueType();
292 continue;
293 }
294 llvm_unreachable("unknown type kind!");
295 }
296}
297
299 // For cleanliness, we try to avoid emitting the return block for
300 // simple cases.
301 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
302
303 if (CurBB) {
304 assert(!CurBB->hasTerminator() && "Unexpected terminated block.");
305
306 // We have a valid insert point, reuse it if it is empty or there are no
307 // explicit jumps to the return block.
308 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
309 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
310 delete ReturnBlock.getBlock();
312 } else
313 EmitBlock(ReturnBlock.getBlock());
314 return llvm::DebugLoc();
315 }
316
317 // Otherwise, if the return block is the target of a single direct
318 // branch then we can just put the code in that block instead. This
319 // cleans up functions which started with a unified return block.
320 if (ReturnBlock.getBlock()->hasOneUse()) {
321 auto *BI =
322 dyn_cast<llvm::UncondBrInst>(*ReturnBlock.getBlock()->user_begin());
323 if (BI && BI->getSuccessor(0) == ReturnBlock.getBlock()) {
324 // Record/return the DebugLoc of the simple 'return' expression to be used
325 // later by the actual 'ret' instruction.
326 llvm::DebugLoc Loc = BI->getDebugLoc();
327 Builder.SetInsertPoint(BI->getParent());
328 BI->eraseFromParent();
329 delete ReturnBlock.getBlock();
331 return Loc;
332 }
333 }
334
335 // FIXME: We are at an unreachable point, there is no reason to emit the block
336 // unless it has uses. However, we still need a place to put the debug
337 // region.end for now.
338
339 EmitBlock(ReturnBlock.getBlock());
340 return llvm::DebugLoc();
341}
342
343static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
344 if (!BB) return;
345 if (!BB->use_empty()) {
346 CGF.CurFn->insert(CGF.CurFn->end(), BB);
347 return;
348 }
349 delete BB;
350}
351
353 assert(BreakContinueStack.empty() &&
354 "mismatched push/pop in break/continue stack!");
355 assert(LifetimeExtendedCleanupStack.empty() &&
356 "mismatched push/pop of cleanups in EHStack!");
357 assert(DeferredDeactivationCleanupStack.empty() &&
358 "mismatched activate/deactivate of cleanups!");
359
360 if (CGM.shouldEmitConvergenceTokens()) {
361 ConvergenceTokenStack.pop_back();
362 assert(ConvergenceTokenStack.empty() &&
363 "mismatched push/pop in convergence stack!");
364 }
365
366 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
367 && NumSimpleReturnExprs == NumReturnExprs
368 && ReturnBlock.getBlock()->use_empty();
369 // Usually the return expression is evaluated before the cleanup
370 // code. If the function contains only a simple return statement,
371 // such as a constant, the location before the cleanup code becomes
372 // the last useful breakpoint in the function, because the simple
373 // return expression will be evaluated after the cleanup code. To be
374 // safe, set the debug location for cleanup code to the location of
375 // the return statement. Otherwise the cleanup code should be at the
376 // end of the function's lexical scope.
377 //
378 // If there are multiple branches to the return block, the branch
379 // instructions will get the location of the return statements and
380 // all will be fine.
381 if (CGDebugInfo *DI = getDebugInfo()) {
382 if (OnlySimpleReturnStmts)
383 DI->EmitLocation(Builder, LastStopPoint);
384 else
385 DI->EmitLocation(Builder, EndLoc);
386 }
387
388 // Pop any cleanups that might have been associated with the
389 // parameters. Do this in whatever block we're currently in; it's
390 // important to do this before we enter the return block or return
391 // edges will be *really* confused.
392 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
393 bool HasOnlyNoopCleanups =
394 HasCleanups && EHStack.containsOnlyNoopCleanups(PrologueCleanupDepth);
395 bool EmitRetDbgLoc = !HasCleanups || HasOnlyNoopCleanups;
396
397 std::optional<ApplyDebugLocation> OAL;
398 if (HasCleanups) {
399 // Make sure the line table doesn't jump back into the body for
400 // the ret after it's been at EndLoc.
401 if (CGDebugInfo *DI = getDebugInfo()) {
402 if (OnlySimpleReturnStmts)
403 DI->EmitLocation(Builder, EndLoc);
404 else
405 // We may not have a valid end location. Try to apply it anyway, and
406 // fall back to an artificial location if needed.
408 }
409
411 }
412
413 // Emit function epilog (to return).
414 llvm::DebugLoc Loc = EmitReturnBlock();
415
417 if (CGM.getCodeGenOpts().InstrumentFunctions)
418 CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
419 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
420 CurFn->addFnAttr("instrument-function-exit-inlined",
421 "__cyg_profile_func_exit");
422 }
423
424 // Emit debug descriptor for function end.
425 if (CGDebugInfo *DI = getDebugInfo())
426 DI->EmitFunctionEnd(Builder, CurFn);
427
428 // Reset the debug location to that of the simple 'return' expression, if any
429 // rather than that of the end of the function's scope '}'.
430 uint64_t RetKeyInstructionsAtomGroup = Loc ? Loc->getAtomGroup() : 0;
431 ApplyDebugLocation AL(*this, Loc);
432 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc,
433 RetKeyInstructionsAtomGroup);
435
436 assert(EHStack.empty() &&
437 "did not remove all scopes from cleanup stack!");
438
439 // If someone did an indirect goto, emit the indirect goto block at the end of
440 // the function.
441 if (IndirectBranch) {
442 EmitBlock(IndirectBranch->getParent());
443 Builder.ClearInsertionPoint();
444 }
445
446 // If some of our locals escaped, insert a call to llvm.localescape in the
447 // entry block.
448 if (!EscapedLocals.empty()) {
449 // Invert the map from local to index into a simple vector. There should be
450 // no holes.
452 EscapeArgs.resize(EscapedLocals.size());
453 for (auto &Pair : EscapedLocals)
454 EscapeArgs[Pair.second] = Pair.first;
455 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getOrInsertDeclaration(
456 &CGM.getModule(), llvm::Intrinsic::localescape);
457 CGBuilderTy(CGM, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
458 }
459
460 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
461 llvm::Instruction *Ptr = AllocaInsertPt;
462 AllocaInsertPt = nullptr;
463 Ptr->eraseFromParent();
464
465 // PostAllocaInsertPt, if created, was lazily created when it was required,
466 // remove it now since it was just created for our own convenience.
467 if (PostAllocaInsertPt) {
468 llvm::Instruction *PostPtr = PostAllocaInsertPt;
469 PostAllocaInsertPt = nullptr;
470 PostPtr->eraseFromParent();
471 }
472
473 // If someone took the address of a label but never did an indirect goto, we
474 // made a zero entry PHI node, which is illegal, zap it now.
475 if (IndirectBranch) {
476 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
477 if (PN->getNumIncomingValues() == 0) {
478 PN->replaceAllUsesWith(llvm::PoisonValue::get(PN->getType()));
479 PN->eraseFromParent();
480 }
481 }
482
484 EmitIfUsed(*this, TerminateLandingPad);
485 EmitIfUsed(*this, TerminateHandler);
486 EmitIfUsed(*this, UnreachableBlock);
487
488 for (const auto &FuncletAndParent : TerminateFunclets)
489 EmitIfUsed(*this, FuncletAndParent.second);
490
491 if (CGM.getCodeGenOpts().EmitDeclMetadata)
492 EmitDeclMetadata();
493
494 for (const auto &R : DeferredReplacements) {
495 if (llvm::Value *Old = R.first) {
496 Old->replaceAllUsesWith(R.second);
497 cast<llvm::Instruction>(Old)->eraseFromParent();
498 }
499 }
500 DeferredReplacements.clear();
501
502 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
503 // PHIs if the current function is a coroutine. We don't do it for all
504 // functions as it may result in slight increase in numbers of instructions
505 // if compiled with no optimizations. We do it for coroutine as the lifetime
506 // of CleanupDestSlot alloca make correct coroutine frame building very
507 // difficult.
508 if (NormalCleanupDest.isValid() && isCoroutine()) {
509 llvm::DominatorTree DT(*CurFn);
510 llvm::PromoteMemToReg(
511 cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
513 }
514
515 // Scan function arguments for vector width.
516 for (llvm::Argument &A : CurFn->args())
517 if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
518 LargestVectorWidth =
519 std::max((uint64_t)LargestVectorWidth,
520 VT->getPrimitiveSizeInBits().getKnownMinValue());
521
522 // Update vector width based on return type.
523 if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
524 LargestVectorWidth =
525 std::max((uint64_t)LargestVectorWidth,
526 VT->getPrimitiveSizeInBits().getKnownMinValue());
527
528 if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
529 LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
530
531 // Add the min-legal-vector-width attribute. This contains the max width from:
532 // 1. min-vector-width attribute used in the source program.
533 // 2. Any builtins used that have a vector width specified.
534 // 3. Values passed in and out of inline assembly.
535 // 4. Width of vector arguments and return types for this function.
536 // 5. Width of vector arguments and return types for functions called by this
537 // function.
538 if (getContext().getTargetInfo().getTriple().isX86())
539 CurFn->addFnAttr("min-legal-vector-width",
540 llvm::utostr(LargestVectorWidth));
541
542 // If we generated an unreachable return block, delete it now.
543 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
544 Builder.ClearInsertionPoint();
545 ReturnBlock.getBlock()->eraseFromParent();
546 }
547 if (ReturnValue.isValid()) {
548 auto *RetAlloca =
549 dyn_cast<llvm::AllocaInst>(ReturnValue.emitRawPointer(*this));
550 if (RetAlloca && RetAlloca->use_empty()) {
551 RetAlloca->eraseFromParent();
553 }
554 }
555}
556
557/// ShouldInstrumentFunction - Return true if the current function should be
558/// instrumented with __cyg_profile_func_* calls
560 if (!CGM.getCodeGenOpts().InstrumentFunctions &&
561 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
562 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
563 return false;
564 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
565 return false;
566 return true;
567}
568
570 if (!CurFuncDecl)
571 return false;
572 return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
573}
574
575/// ShouldXRayInstrument - Return true if the current function should be
576/// instrumented with XRay nop sleds.
578 return CGM.getCodeGenOpts().XRayInstrumentFunctions;
579}
580
581/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
582/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
584 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
585 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
586 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
588}
589
591 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
592 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
593 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
595}
596
597llvm::ConstantInt *
599 // Remove any (C++17) exception specifications, to allow calling e.g. a
600 // noexcept function through a non-noexcept pointer.
601 if (!Ty->isFunctionNoProtoType())
603 std::string Mangled;
604 llvm::raw_string_ostream Out(Mangled);
605 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out, false);
606 return llvm::ConstantInt::get(
607 CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled)));
608}
609
610void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
611 llvm::Function *Fn) {
612 if (!FD->hasAttr<DeviceKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
613 return;
614
615 llvm::LLVMContext &Context = getLLVMContext();
616
617 CGM.GenKernelArgMetadata(Fn, FD, this);
618
619 if (!(getLangOpts().OpenCL ||
620 (getLangOpts().CUDA &&
621 getContext().getTargetInfo().getTriple().isSPIRV())))
622 return;
623
624 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
625 QualType HintQTy = A->getTypeHint();
626 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
627 bool IsSignedInteger =
628 HintQTy->isSignedIntegerType() ||
629 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
630 llvm::Metadata *AttrMDArgs[] = {
631 llvm::ConstantAsMetadata::get(llvm::PoisonValue::get(
632 CGM.getTypes().ConvertType(A->getTypeHint()))),
633 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
634 llvm::IntegerType::get(Context, 32),
635 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
636 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
637 }
638
639 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
640 auto Eval = [&](Expr *E) {
641 return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
642 };
643 llvm::Metadata *AttrMDArgs[] = {
644 llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim()))),
645 llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim()))),
646 llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim())))};
647 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
648 }
649
650 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
651 auto Eval = [&](Expr *E) {
652 return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
653 };
654 llvm::Metadata *AttrMDArgs[] = {
655 llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim()))),
656 llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim()))),
657 llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim())))};
658 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
659 }
660
661 if (const OpenCLIntelReqdSubGroupSizeAttr *A =
662 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
663 llvm::Metadata *AttrMDArgs[] = {
664 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
665 Fn->setMetadata("intel_reqd_sub_group_size",
666 llvm::MDNode::get(Context, AttrMDArgs));
667 }
668}
669
670/// Determine whether the function F ends with a return stmt.
671static bool endsWithReturn(const Decl* F) {
672 const Stmt *Body = nullptr;
673 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
674 Body = FD->getBody();
675 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
676 Body = OMD->getBody();
677
678 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
679 auto LastStmt = CS->body_rbegin();
680 if (LastStmt != CS->body_rend())
681 return isa<ReturnStmt>(*LastStmt);
682 }
683 return false;
684}
685
687 if (SanOpts.has(SanitizerKind::Thread)) {
688 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
689 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
690 }
691}
692
693/// Check if the return value of this function requires sanitization.
694bool CodeGenFunction::requiresReturnValueCheck() const {
695 return requiresReturnValueNullabilityCheck() ||
696 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
697 CurCodeDecl->getAttr<ReturnsNonNullAttr>());
698}
699
700static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
701 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
702 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
703 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
704 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
705 return false;
706
707 if (!Ctx.hasSameType(MD->parameters()[0]->getType(), Ctx.getSizeType()))
708 return false;
709
710 if (MD->getNumParams() == 2) {
711 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
712 if (!PT || !PT->isVoidPointerType() ||
713 !PT->getPointeeType().isConstQualified())
714 return false;
715 }
716
717 return true;
718}
719
720bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
721 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
722 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
723}
724
725bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
726 return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
728 llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) {
729 return isInAllocaArgument(CGM.getCXXABI(), P->getType());
730 });
731}
732
733/// Return the UBSan prologue signature for \p FD if one is available.
734static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
735 const FunctionDecl *FD) {
736 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
737 if (!MD->isStatic())
738 return nullptr;
740}
741
743 llvm::Function *Fn,
744 const CGFunctionInfo &FnInfo,
745 const FunctionArgList &Args,
746 SourceLocation Loc,
747 SourceLocation StartLoc) {
748 assert(!CurFn &&
749 "Do not use a CodeGenFunction object for more than one function");
750
751 const Decl *D = GD.getDecl();
752
753 DidCallStackSave = false;
754 CurCodeDecl = D;
755 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
756 if (FD && FD->usesSEHTry())
757 CurSEHParent = GD;
758 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
759 FnRetTy = RetTy;
760 CurFn = Fn;
761 CurFnInfo = &FnInfo;
762 assert(CurFn->isDeclaration() && "Function already has body?");
763
764 // If this function is ignored for any of the enabled sanitizers,
765 // disable the sanitizer for the function.
766 do {
767#define SANITIZER(NAME, ID) \
768 if (SanOpts.empty()) \
769 break; \
770 if (SanOpts.has(SanitizerKind::ID)) \
771 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
772 SanOpts.set(SanitizerKind::ID, false);
773
774#include "clang/Basic/Sanitizers.def"
775#undef SANITIZER
776 } while (false);
777
778 if (D) {
779 const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
780 SanitizerMask no_sanitize_mask;
781 bool NoSanitizeCoverage = false;
782
783 for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
784 no_sanitize_mask |= Attr->getMask();
785 // SanitizeCoverage is not handled by SanOpts.
786 if (Attr->hasCoverage())
787 NoSanitizeCoverage = true;
788 }
789
790 // Apply the no_sanitize* attributes to SanOpts.
791 SanOpts.Mask &= ~no_sanitize_mask;
792 if (no_sanitize_mask & SanitizerKind::Address)
793 SanOpts.set(SanitizerKind::KernelAddress, false);
794 if (no_sanitize_mask & SanitizerKind::KernelAddress)
795 SanOpts.set(SanitizerKind::Address, false);
796 if (no_sanitize_mask & SanitizerKind::HWAddress)
797 SanOpts.set(SanitizerKind::KernelHWAddress, false);
798 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
799 SanOpts.set(SanitizerKind::HWAddress, false);
800
801 if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
802 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
803
804 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
805 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
806
807 // Some passes need the non-negated no_sanitize attribute. Pass them on.
808 if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
809 if (no_sanitize_mask & SanitizerKind::Thread)
810 Fn->addFnAttr("no_sanitize_thread");
811 }
812 }
813
815 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
816 } else {
817 // Apply sanitizer attributes to the function.
818 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
819 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
820 if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
821 SanitizerKind::KernelHWAddress))
822 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
823 if (SanOpts.has(SanitizerKind::MemtagStack))
824 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
825 if (SanOpts.has(SanitizerKind::Thread))
826 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
827 if (SanOpts.has(SanitizerKind::Type))
828 Fn->addFnAttr(llvm::Attribute::SanitizeType);
829 if (SanOpts.has(SanitizerKind::NumericalStability))
830 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
831 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
832 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
833 if (SanOpts.has(SanitizerKind::AllocToken))
834 Fn->addFnAttr(llvm::Attribute::SanitizeAllocToken);
835 }
836 if (SanOpts.has(SanitizerKind::SafeStack))
837 Fn->addFnAttr(llvm::Attribute::SafeStack);
838 if (SanOpts.has(SanitizerKind::ShadowCallStack))
839 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
840
841 if (SanOpts.has(SanitizerKind::Realtime))
842 if (FD && FD->getASTContext().hasAnyFunctionEffects())
843 for (const FunctionEffectWithCondition &Fe : FD->getFunctionEffects()) {
844 if (Fe.Effect.kind() == FunctionEffect::Kind::NonBlocking)
845 Fn->addFnAttr(llvm::Attribute::SanitizeRealtime);
846 else if (Fe.Effect.kind() == FunctionEffect::Kind::Blocking)
847 Fn->addFnAttr(llvm::Attribute::SanitizeRealtimeBlocking);
848 }
849
850 // Apply fuzzing attribute to the function.
851 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
852 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
853
854 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
855 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
856 if (SanOpts.has(SanitizerKind::Thread)) {
857 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
858 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
859 if (OMD->getMethodFamily() == OMF_dealloc ||
860 OMD->getMethodFamily() == OMF_initialize ||
861 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
863 }
864 }
865 }
866
867 // Ignore unrelated casts in STL allocate() since the allocator must cast
868 // from void* to T* before object initialization completes. Don't match on the
869 // namespace because not all allocators are in std::
870 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
872 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
873 }
874
875 // Ignore null checks in coroutine functions since the coroutines passes
876 // are not aware of how to move the extra UBSan instructions across the split
877 // coroutine boundaries.
878 if (D && SanOpts.has(SanitizerKind::Null))
879 if (FD && FD->getBody() &&
880 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
881 SanOpts.Mask &= ~SanitizerKind::Null;
882
883 // Apply xray attributes to the function (as a string, for now)
884 bool AlwaysXRayAttr = false;
885 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
886 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
888 CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
890 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
891 Fn->addFnAttr("function-instrument", "xray-always");
892 AlwaysXRayAttr = true;
893 }
894 if (XRayAttr->neverXRayInstrument())
895 Fn->addFnAttr("function-instrument", "xray-never");
896 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
898 Fn->addFnAttr("xray-log-args",
899 llvm::utostr(LogArgs->getArgumentCount()));
900 }
901 } else {
902 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
903 Fn->addFnAttr(
904 "xray-instruction-threshold",
905 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
906 }
907
909 if (CGM.getCodeGenOpts().XRayIgnoreLoops)
910 Fn->addFnAttr("xray-ignore-loops");
911
912 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
914 Fn->addFnAttr("xray-skip-exit");
915
916 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
918 Fn->addFnAttr("xray-skip-entry");
919
920 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
921 if (FuncGroups > 1) {
922 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
923 CurFn->getName().bytes_end());
924 auto Group = crc32(FuncName) % FuncGroups;
925 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
926 !AlwaysXRayAttr)
927 Fn->addFnAttr("function-instrument", "xray-never");
928 }
929 }
930
931 if (CGM.getCodeGenOpts().getProfileInstr() !=
932 llvm::driver::ProfileInstrKind::ProfileNone) {
933 switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
935 Fn->addFnAttr(llvm::Attribute::SkipProfile);
936 break;
938 Fn->addFnAttr(llvm::Attribute::NoProfile);
939 break;
941 break;
942 }
943 }
944
945 unsigned Count, Offset;
946 StringRef Section;
947 if (const auto *Attr =
948 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
949 Count = Attr->getCount();
950 Offset = Attr->getOffset();
951 Section = Attr->getSection();
952 } else {
953 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
954 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
955 }
956 if (Section.empty())
957 Section = CGM.getCodeGenOpts().PatchableFunctionEntrySection;
958 if (Count && Offset <= Count) {
959 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
960 if (Offset)
961 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
962 if (!Section.empty())
963 Fn->addFnAttr("patchable-function-entry-section", Section);
964 }
965 // Instruct that functions for COFF/CodeView targets should start with a
966 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
967 // backends as they don't need it -- instructions on these architectures are
968 // always atomically patchable at runtime.
969 if (CGM.getCodeGenOpts().HotPatch &&
970 getContext().getTargetInfo().getTriple().isX86() &&
971 getContext().getTargetInfo().getTriple().getEnvironment() !=
972 llvm::Triple::CODE16)
973 Fn->addFnAttr("patchable-function", "prologue-short-redirect");
974
975 // Add no-jump-tables value.
976 if (CGM.getCodeGenOpts().NoUseJumpTables)
977 Fn->addFnAttr("no-jump-tables", "true");
978
979 // Add no-inline-line-tables value.
980 if (CGM.getCodeGenOpts().NoInlineLineTables)
981 Fn->addFnAttr("no-inline-line-tables");
982
983 // Add profile-sample-accurate value.
984 if (CGM.getCodeGenOpts().ProfileSampleAccurate)
985 Fn->addFnAttr("profile-sample-accurate");
986
987 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
988 Fn->addFnAttr("use-sample-profile");
989
990 if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
991 Fn->addFnAttr("cfi-canonical-jump-table");
992
993 if (D && D->hasAttr<NoProfileFunctionAttr>())
994 Fn->addFnAttr(llvm::Attribute::NoProfile);
995
996 if (D && D->hasAttr<HybridPatchableAttr>())
997 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
998
999 if (D) {
1000 // Function attributes take precedence over command line flags.
1001 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1002 switch (A->getThunkType()) {
1003 case FunctionReturnThunksAttr::Kind::Keep:
1004 break;
1005 case FunctionReturnThunksAttr::Kind::Extern:
1006 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1007 break;
1008 }
1009 } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1010 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1011 }
1012
1013 if (FD && (getLangOpts().OpenCL ||
1014 (getLangOpts().CUDA &&
1015 getContext().getTargetInfo().getTriple().isSPIRV()) ||
1016 ((getLangOpts().HIP || getLangOpts().OffloadViaLLVM) &&
1017 getLangOpts().CUDAIsDevice))) {
1018 // Add metadata for a kernel function.
1019 EmitKernelMetadata(FD, Fn);
1020 }
1021
1022 if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
1023 Fn->setMetadata("clspv_libclc_builtin",
1024 llvm::MDNode::get(getLLVMContext(), {}));
1025 }
1026
1027 // If we are checking function types, emit a function type signature as
1028 // prologue data. Kernel functions have strict alignment requirements and
1029 // cannot be call indirectly so we do not instrument them.
1030 if (FD && SanOpts.has(SanitizerKind::Function) &&
1032 llvm::isCallableCC(Fn->getCallingConv())) {
1033 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1034 llvm::LLVMContext &Ctx = Fn->getContext();
1035 llvm::MDBuilder MDB(Ctx);
1036 Fn->setMetadata(
1037 llvm::LLVMContext::MD_func_sanitize,
1038 MDB.createRTTIPointerPrologue(
1039 PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
1040 }
1041 }
1042
1043 // If we're checking nullability, we need to know whether we can check the
1044 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1045 if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1046 auto Nullability = FnRetTy->getNullability();
1047 if (Nullability && *Nullability == NullabilityKind::NonNull &&
1048 !FnRetTy->isRecordType()) {
1049 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1050 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1051 RetValNullabilityPrecondition =
1052 llvm::ConstantInt::getTrue(getLLVMContext());
1053 }
1054 }
1055
1056 // If we're in C++ mode and the function name is "main", it is guaranteed
1057 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1058 // used within a program").
1059 //
1060 // OpenCL C 2.0 v2.2-11 s6.9.i:
1061 // Recursion is not supported.
1062 //
1063 // HLSL
1064 // Recursion is not supported.
1065 //
1066 // SYCL v1.2.1 s3.10:
1067 // kernels cannot include RTTI information, exception classes,
1068 // recursive code, virtual functions or make use of C++ libraries that
1069 // are not compiled for the device.
1070 if (FD &&
1071 ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
1072 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
1073 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1074 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1075
1076 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1077 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1078 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1079 Builder.setDefaultConstrainedRounding(RM);
1080 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1081 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1082 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1083 RM != llvm::RoundingMode::NearestTiesToEven))) {
1084 Builder.setIsFPConstrained(true);
1085 Fn->addFnAttr(llvm::Attribute::StrictFP);
1086 }
1087
1088 // If a custom alignment is used, force realigning to this alignment on
1089 // any main function which certainly will need it.
1090 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1091 CGM.getCodeGenOpts().StackAlignment))
1092 Fn->addFnAttr("stackrealign");
1093
1094 // "main" doesn't need to zero out call-used registers.
1095 if (FD && FD->isMain())
1096 Fn->removeFnAttr("zero-call-used-regs");
1097
1098 // Add vscale_range attribute if appropriate.
1099 llvm::StringMap<bool> FeatureMap;
1100 auto IsArmStreaming = TargetInfo::ArmStreamingKind::NotStreaming;
1101 if (FD) {
1102 getContext().getFunctionFeatureMap(FeatureMap, FD);
1103 if (const auto *T = FD->getType()->getAs<FunctionProtoType>())
1104 if (T->getAArch64SMEAttributes() &
1107
1108 if (IsArmStreamingFunction(FD, true))
1110 }
1111 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
1112 getContext().getTargetInfo().getVScaleRange(getLangOpts(), IsArmStreaming,
1113 &FeatureMap);
1114 if (VScaleRange) {
1115 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1116 getLLVMContext(), VScaleRange->first, VScaleRange->second));
1117 }
1118
1119 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1120
1121 // Create a marker to make it easy to insert allocas into the entryblock
1122 // later. Don't create this with the builder, because we don't want it
1123 // folded.
1124 llvm::Value *Poison = llvm::PoisonValue::get(Int32Ty);
1125 AllocaInsertPt = new llvm::BitCastInst(Poison, Int32Ty, "allocapt", EntryBB);
1126
1128
1129 Builder.SetInsertPoint(EntryBB);
1130
1131 // If we're checking the return value, allocate space for a pointer to a
1132 // precise source location of the checked return statement.
1133 if (requiresReturnValueCheck()) {
1134 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1135 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1136 ReturnLocation);
1137 }
1138
1139 // Emit subprogram debug descriptor.
1140 if (CGDebugInfo *DI = getDebugInfo()) {
1141 // Reconstruct the type from the argument list so that implicit parameters,
1142 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1143 // convention.
1144 DI->emitFunctionStart(GD, Loc, StartLoc,
1145 DI->getFunctionType(FD, RetTy, Args), CurFn,
1147 }
1148
1150 if (CGM.getCodeGenOpts().InstrumentFunctions)
1151 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1152 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1153 CurFn->addFnAttr("instrument-function-entry-inlined",
1154 "__cyg_profile_func_enter");
1155 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1156 CurFn->addFnAttr("instrument-function-entry-inlined",
1157 "__cyg_profile_func_enter_bare");
1158 }
1159
1160 // Since emitting the mcount call here impacts optimizations such as function
1161 // inlining, we just add an attribute to insert a mcount call in backend.
1162 // The attribute "counting-function" is set to mcount function name which is
1163 // architecture dependent.
1164 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1165 // Calls to fentry/mcount should not be generated if function has
1166 // the no_instrument_function attribute.
1167 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1168 if (CGM.getCodeGenOpts().CallFEntry)
1169 Fn->addFnAttr("fentry-call", "true");
1170 else {
1171 Fn->addFnAttr("instrument-function-entry-inlined",
1172 getTarget().getMCountName());
1173 }
1174 if (CGM.getCodeGenOpts().MNopMCount) {
1175 if (!CGM.getCodeGenOpts().CallFEntry)
1176 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1177 << "-mnop-mcount" << "-mfentry";
1178 Fn->addFnAttr("mnop-mcount");
1179 }
1180
1181 if (CGM.getCodeGenOpts().RecordMCount) {
1182 if (!CGM.getCodeGenOpts().CallFEntry)
1183 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1184 << "-mrecord-mcount" << "-mfentry";
1185 Fn->addFnAttr("mrecord-mcount");
1186 }
1187 }
1188 }
1189
1190 if (CGM.getCodeGenOpts().PackedStack) {
1191 if (getContext().getTargetInfo().getTriple().getArch() !=
1192 llvm::Triple::systemz)
1193 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1194 << "-mpacked-stack";
1195 Fn->addFnAttr("packed-stack");
1196 }
1197
1198 if (!CGM.getCodeGenOpts().ZOSPPA1Name)
1199 Fn->addFnAttr("zos-ppa1-name", "");
1200
1201 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1202 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1203 Fn->addFnAttr("warn-stack-size",
1204 std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1205
1206 if (RetTy->isVoidType()) {
1207 // Void type; nothing to return.
1209
1210 // Count the implicit return.
1211 if (!endsWithReturn(D))
1212 ++NumReturnExprs;
1213 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1214 // Indirect return; emit returned value directly into sret slot.
1215 // This reduces code size, and affects correctness in C++.
1216 auto AI = CurFn->arg_begin();
1217 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1218 ++AI;
1220 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1221 nullptr, nullptr, KnownNonNull);
1222 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1224 CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
1225 Builder.CreateStore(ReturnValue.emitRawPointer(*this),
1227 }
1228 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1229 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1230 // Load the sret pointer from the argument struct and return into that.
1231 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1232 llvm::Function::arg_iterator EI = CurFn->arg_end();
1233 --EI;
1234 llvm::Value *Addr = Builder.CreateStructGEP(
1235 CurFnInfo->getArgStruct(), &*EI, Idx);
1236 llvm::Type *Ty =
1237 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1239 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1241 CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
1242 } else {
1243 ReturnValue = CreateIRTempWithoutCast(RetTy, "retval");
1244
1245 // Tell the epilog emitter to autorelease the result. We do this
1246 // now so that various specialized functions can suppress it
1247 // during their IR-generation.
1248 if (getLangOpts().ObjCAutoRefCount &&
1249 !CurFnInfo->isReturnsRetained() &&
1250 RetTy->isObjCRetainableType())
1251 AutoreleaseResult = true;
1252 }
1253
1255
1256 PrologueCleanupDepth = EHStack.stable_begin();
1257
1258 // Emit OpenMP specific initialization of the device functions.
1259 if (getLangOpts().OpenMP && CurCodeDecl)
1260 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1261
1262 if (FD && getLangOpts().HLSL) {
1263 // Handle emitting HLSL entry functions.
1264 if (FD->hasAttr<HLSLShaderAttr>()) {
1265 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1266 }
1267 }
1268
1270
1271 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1272 MD && !MD->isStatic()) {
1273 bool IsInLambda =
1274 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1276 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1277 if (IsInLambda) {
1278 // We're in a lambda; figure out the captures.
1282 // If the lambda captures the object referred to by '*this' - either by
1283 // value or by reference, make sure CXXThisValue points to the correct
1284 // object.
1285
1286 // Get the lvalue for the field (which is a copy of the enclosing object
1287 // or contains the address of the enclosing object).
1289 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1290 // If the enclosing object was captured by value, just use its
1291 // address. Sign this pointer.
1292 CXXThisValue = ThisFieldLValue.getPointer(*this);
1293 } else {
1294 // Load the lvalue pointed to by the field, since '*this' was captured
1295 // by reference.
1296 CXXThisValue =
1297 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1298 }
1299 }
1300 for (auto *FD : MD->getParent()->fields()) {
1301 if (FD->hasCapturedVLAType()) {
1302 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1304 auto VAT = FD->getCapturedVLAType();
1305 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1306 }
1307 }
1308 } else if (MD->isImplicitObjectMemberFunction()) {
1309 // Not in a lambda; just use 'this' from the method.
1310 // FIXME: Should we generate a new load for each use of 'this'? The
1311 // fast register allocator would be happier...
1312 CXXThisValue = CXXABIThisValue;
1313 }
1314
1315 // Check the 'this' pointer once per function, if it's available.
1316 if (CXXABIThisValue) {
1317 SanitizerSet SkippedChecks;
1318 SkippedChecks.set(SanitizerKind::ObjectSize, true);
1319 QualType ThisTy = MD->getThisType();
1320
1321 // If this is the call operator of a lambda with no captures, it
1322 // may have a static invoker function, which may call this operator with
1323 // a null 'this' pointer.
1325 SkippedChecks.set(SanitizerKind::Null, true);
1326
1329 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1330 }
1331 }
1332
1333 // If any of the arguments have a variably modified type, make sure to
1334 // emit the type size, but only if the function is not naked. Naked functions
1335 // have no prolog to run this evaluation.
1336 if (!FD || !FD->hasAttr<NakedAttr>()) {
1337 for (const VarDecl *VD : Args) {
1338 // Dig out the type as written from ParmVarDecls; it's unclear whether
1339 // the standard (C99 6.9.1p10) requires this, but we're following the
1340 // precedent set by gcc.
1341 QualType Ty;
1342 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1343 Ty = PVD->getOriginalType();
1344 else
1345 Ty = VD->getType();
1346
1347 if (Ty->isVariablyModifiedType())
1349 }
1350 }
1351 // Emit a location at the end of the prologue.
1352 if (CGDebugInfo *DI = getDebugInfo())
1353 DI->EmitLocation(Builder, StartLoc);
1354 // TODO: Do we need to handle this in two places like we do with
1355 // target-features/target-cpu?
1356 if (CurFuncDecl)
1357 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1358 LargestVectorWidth = VecWidth->getVectorWidth();
1359
1360 if (CGM.shouldEmitConvergenceTokens())
1361 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1362}
1363
1367 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1369 else
1370 EmitStmt(Body);
1371}
1372
1373/// When instrumenting to collect profile data, the counts for some blocks
1374/// such as switch cases need to not include the fall-through counts, so
1375/// emit a branch around the instrumentation code. When not instrumenting,
1376/// this just calls EmitBlock().
1378 const Stmt *S) {
1379 llvm::BasicBlock *SkipCountBB = nullptr;
1380 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1381 // When instrumenting for profiling, the fallthrough to certain
1382 // statements needs to skip over the instrumentation code so that we
1383 // get an accurate count.
1384 SkipCountBB = createBasicBlock("skipcount");
1385 EmitBranch(SkipCountBB);
1386 }
1387 EmitBlock(BB);
1388 uint64_t CurrentCount = getCurrentProfileCount();
1391 if (SkipCountBB)
1392 EmitBlock(SkipCountBB);
1393}
1394
1395/// Tries to mark the given function nounwind based on the
1396/// non-existence of any throwing calls within it. We believe this is
1397/// lightweight enough to do at -O0.
1398static void TryMarkNoThrow(llvm::Function *F) {
1399 // LLVM treats 'nounwind' on a function as part of the type, so we
1400 // can't do this on functions that can be overwritten.
1401 if (F->isInterposable()) return;
1402
1403 for (llvm::BasicBlock &BB : *F)
1404 for (llvm::Instruction &I : BB)
1405 if (I.mayThrow())
1406 return;
1407
1408 F->setDoesNotThrow();
1409}
1410
1412 FunctionArgList &Args) {
1413 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1414 QualType ResTy = FD->getReturnType();
1415
1416 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1417 if (MD && MD->isImplicitObjectMemberFunction()) {
1418 if (CGM.getCXXABI().HasThisReturn(GD))
1419 ResTy = MD->getThisType();
1420 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1421 ResTy = CGM.getContext().VoidPtrTy;
1422 CGM.getCXXABI().buildThisParam(*this, Args);
1423 }
1424
1425 // The base version of an inheriting constructor whose constructed base is a
1426 // virtual base is not passed any arguments (because it doesn't actually call
1427 // the inherited constructor).
1428 bool PassedParams = true;
1429 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1430 if (auto Inherited = CD->getInheritedConstructor())
1431 PassedParams =
1432 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1433
1434 if (PassedParams) {
1435 for (auto *Param : FD->parameters()) {
1436 Args.push_back(Param);
1437 if (!Param->hasAttr<PassObjectSizeAttr>())
1438 continue;
1439
1441 getContext(), Param->getDeclContext(), Param->getLocation(),
1442 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1443 SizeArguments[Param] = Implicit;
1444 Args.push_back(Implicit);
1445 }
1446 }
1447
1448 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1449 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1450
1451 return ResTy;
1452}
1453
1454void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1455 const CGFunctionInfo &FnInfo) {
1456 assert(Fn && "generating code for null Function");
1457 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1458 CurGD = GD;
1459
1460 FunctionArgList Args;
1461 QualType ResTy = BuildFunctionArgList(GD, Args);
1462
1463 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
1464
1465 if (FD->isInlineBuiltinDeclaration()) {
1466 // When generating code for a builtin with an inline declaration, use a
1467 // mangled name to hold the actual body, while keeping an external
1468 // definition in case the function pointer is referenced somewhere.
1469 std::string FDInlineName = (Fn->getName() + ".inline").str();
1470 llvm::Module *M = Fn->getParent();
1471 llvm::Function *Clone = M->getFunction(FDInlineName);
1472 if (!Clone) {
1473 Clone = llvm::Function::Create(Fn->getFunctionType(),
1474 llvm::GlobalValue::InternalLinkage,
1475 Fn->getAddressSpace(), FDInlineName, M);
1476 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1477 }
1478 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1479 Fn = Clone;
1480 } else {
1481 // Detect the unusual situation where an inline version is shadowed by a
1482 // non-inline version. In that case we should pick the external one
1483 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1484 // to detect that situation before we reach codegen, so do some late
1485 // replacement.
1486 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1487 PD = PD->getPreviousDecl()) {
1488 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1489 std::string FDInlineName = (Fn->getName() + ".inline").str();
1490 llvm::Module *M = Fn->getParent();
1491 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1492 Clone->replaceAllUsesWith(Fn);
1493 Clone->eraseFromParent();
1494 }
1495 break;
1496 }
1497 }
1498 }
1499
1500 // Check if we should generate debug info for this function.
1501 if (FD->hasAttr<NoDebugAttr>()) {
1502 // Clear non-distinct debug info that was possibly attached to the function
1503 // due to an earlier declaration without the nodebug attribute
1504 Fn->setSubprogram(nullptr);
1505 // Disable debug info indefinitely for this function
1506 DebugInfo = nullptr;
1507 }
1508 // Finalize function debug info on exit.
1509 llvm::scope_exit Cleanup([this] {
1510 if (CGDebugInfo *DI = getDebugInfo())
1511 DI->completeFunction();
1512 });
1513
1514 // The function might not have a body if we're generating thunks for a
1515 // function declaration.
1516 SourceRange BodyRange;
1517 if (Stmt *Body = FD->getBody())
1518 BodyRange = Body->getSourceRange();
1519 else
1520 BodyRange = FD->getLocation();
1521 CurEHLocation = BodyRange.getEnd();
1522
1523 // Use the location of the start of the function to determine where
1524 // the function definition is located. By default use the location
1525 // of the declaration as the location for the subprogram. A function
1526 // may lack a declaration in the source code if it is created by code
1527 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1528 SourceLocation Loc = FD->getLocation();
1529
1530 // If this is a function specialization then use the pattern body
1531 // as the location for the function.
1532 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1533 if (SpecDecl->hasBody(SpecDecl))
1534 Loc = SpecDecl->getLocation();
1535
1536 Stmt *Body = FD->getBody();
1537
1538 if (Body) {
1539 // Coroutines always emit lifetime markers.
1540 if (isa<CoroutineBodyStmt>(Body))
1541 ShouldEmitLifetimeMarkers = true;
1542
1543 // Initialize helper which will detect jumps which can cause invalid
1544 // lifetime markers.
1545 if (ShouldEmitLifetimeMarkers)
1546 Bypasses.Init(CGM, Body);
1547 }
1548
1549 // Emit the standard function prologue.
1550 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1551
1552 // Save parameters for coroutine function.
1553 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1554 llvm::append_range(FnArgs, FD->parameters());
1555
1556 // Ensure that the function adheres to the forward progress guarantee, which
1557 // is required by certain optimizations.
1558 // In C++11 and up, the attribute will be removed if the body contains a
1559 // trivial empty loop.
1561 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1562
1563 // Generate the body of the function.
1564 PGO->assignRegionCounters(GD, CurFn);
1565 if (isa<CXXDestructorDecl>(FD))
1566 EmitDestructorBody(Args);
1567 else if (isa<CXXConstructorDecl>(FD))
1568 EmitConstructorBody(Args);
1569 else if (getLangOpts().CUDA &&
1570 !getLangOpts().CUDAIsDevice &&
1571 FD->hasAttr<CUDAGlobalAttr>())
1572 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1573 else if (isa<CXXMethodDecl>(FD) &&
1574 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1575 // The lambda static invoker function is special, because it forwards or
1576 // clones the body of the function call operator (but is actually static).
1578 } else if (isa<CXXMethodDecl>(FD) &&
1580 !FnInfo.isDelegateCall() &&
1581 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1582 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1583 // If emitting a lambda with static invoker on X86 Windows, change
1584 // the call operator body.
1585 // Make sure that this is a call operator with an inalloca arg and check
1586 // for delegate call to make sure this is the original call op and not the
1587 // new forwarding function for the static invoker.
1589 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1590 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1591 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1592 // Implicit copy-assignment gets the same special treatment as implicit
1593 // copy-constructors.
1595 } else if (DeviceKernelAttr::isOpenCLSpelling(
1596 FD->getAttr<DeviceKernelAttr>()) &&
1598 CallArgList CallArgs;
1599 for (unsigned i = 0; i < Args.size(); ++i) {
1600 Address ArgAddr = GetAddrOfLocalVar(Args[i]);
1601 QualType ArgQualType = Args[i]->getType();
1602 RValue ArgRValue = convertTempToRValue(ArgAddr, ArgQualType, Loc);
1603 CallArgs.add(ArgRValue, ArgQualType);
1604 }
1606 const FunctionType *FT = cast<FunctionType>(FD->getType());
1607 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1608 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
1609 CallArgs, FT, /*ChainCall=*/false, getCurrentFunctionDecl());
1610 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FnInfo);
1611 llvm::Constant *GDStubFunctionPointer =
1612 CGM.getRawFunctionPointer(GDStub, FTy);
1613 CGCallee GDStubCallee = CGCallee::forDirect(GDStubFunctionPointer, GDStub);
1614 EmitCall(FnInfo, GDStubCallee, ReturnValueSlot(), CallArgs, nullptr, false,
1615 Loc);
1616 } else if (Body) {
1617 EmitFunctionBody(Body);
1618 } else
1619 llvm_unreachable("no definition for emitted function");
1620
1621 // C++11 [stmt.return]p2:
1622 // Flowing off the end of a function [...] results in undefined behavior in
1623 // a value-returning function.
1624 // C11 6.9.1p12:
1625 // If the '}' that terminates a function is reached, and the value of the
1626 // function call is used by the caller, the behavior is undefined.
1628 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1629 bool ShouldEmitUnreachable =
1630 CGM.getCodeGenOpts().StrictReturn ||
1631 !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1632 if (SanOpts.has(SanitizerKind::Return)) {
1633 auto CheckOrdinal = SanitizerKind::SO_Return;
1634 auto CheckHandler = SanitizerHandler::MissingReturn;
1635 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
1636 llvm::Value *IsFalse = Builder.getFalse();
1637 EmitCheck(std::make_pair(IsFalse, CheckOrdinal), CheckHandler,
1639 } else if (ShouldEmitUnreachable) {
1640 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1641 EmitTrapCall(llvm::Intrinsic::trap);
1642 }
1643 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1644 Builder.CreateUnreachable();
1645 Builder.ClearInsertionPoint();
1646 }
1647 }
1648
1649 // Emit the standard function epilogue.
1650 FinishFunction(BodyRange.getEnd());
1651
1652 PGO->verifyCounterMap();
1653
1654 if (CurCodeDecl->hasAttr<PersonalityAttr>()) {
1655 StringRef Identifier =
1656 CurCodeDecl->getAttr<PersonalityAttr>()->getRoutine()->getName();
1657 llvm::FunctionCallee PersonalityRoutine =
1658 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
1659 Identifier, {}, /*local=*/true);
1660 Fn->setPersonalityFn(cast<llvm::Constant>(PersonalityRoutine.getCallee()));
1661 }
1662
1663 // If we haven't marked the function nothrow through other means, do
1664 // a quick pass now to see if we can.
1665 if (!CurFn->doesNotThrow())
1667}
1668
1669/// ContainsLabel - Return true if the statement contains a label in it. If
1670/// this statement is not executed normally, it not containing a label means
1671/// that we can just remove the code.
1672bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1673 // Null statement, not a label!
1674 if (!S) return false;
1675
1676 // If this is a label, we have to emit the code, consider something like:
1677 // if (0) { ... foo: bar(); } goto foo;
1678 //
1679 // TODO: If anyone cared, we could track __label__'s, since we know that you
1680 // can't jump to one from outside their declared region.
1681 if (isa<LabelStmt>(S))
1682 return true;
1683
1684 // If this is a case/default statement, and we haven't seen a switch, we have
1685 // to emit the code.
1686 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1687 return true;
1688
1689 // If this is a switch statement, we want to ignore cases below it.
1690 if (isa<SwitchStmt>(S))
1691 IgnoreCaseStmts = true;
1692
1693 // Scan subexpressions for verboten labels.
1694 for (const Stmt *SubStmt : S->children())
1695 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1696 return true;
1697
1698 return false;
1699}
1700
1701/// containsBreak - Return true if the statement contains a break out of it.
1702/// If the statement (recursively) contains a switch or loop with a break
1703/// inside of it, this is fine.
1705 // Null statement, not a label!
1706 if (!S) return false;
1707
1708 // If this is a switch or loop that defines its own break scope, then we can
1709 // include it and anything inside of it.
1710 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1711 isa<ForStmt>(S))
1712 return false;
1713
1714 if (isa<BreakStmt>(S))
1715 return true;
1716
1717 // Scan subexpressions for verboten breaks.
1718 for (const Stmt *SubStmt : S->children())
1719 if (containsBreak(SubStmt))
1720 return true;
1721
1722 return false;
1723}
1724
1726 if (!S) return false;
1727
1728 // Some statement kinds add a scope and thus never add a decl to the current
1729 // scope. Note, this list is longer than the list of statements that might
1730 // have an unscoped decl nested within them, but this way is conservatively
1731 // correct even if more statement kinds are added.
1732 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1736 return false;
1737
1738 if (isa<DeclStmt>(S))
1739 return true;
1740
1741 for (const Stmt *SubStmt : S->children())
1742 if (mightAddDeclToScope(SubStmt))
1743 return true;
1744
1745 return false;
1746}
1747
1748/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1749/// to a constant, or if it does but contains a label, return false. If it
1750/// constant folds return true and set the boolean result in Result.
1752 bool &ResultBool,
1753 bool AllowLabels) {
1754 // If MC/DC is enabled, disable folding so that we can instrument all
1755 // conditions to yield complete test vectors. We still keep track of
1756 // folded conditions during region mapping and visualization.
1757 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1758 CGM.getCodeGenOpts().MCDCCoverage)
1759 return false;
1760
1761 llvm::APSInt ResultInt;
1762 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1763 return false;
1764
1765 ResultBool = ResultInt.getBoolValue();
1766 return true;
1767}
1768
1769/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1770/// to a constant, or if it does but contains a label, return false. If it
1771/// constant folds return true and set the folded value.
1773 llvm::APSInt &ResultInt,
1774 bool AllowLabels) {
1775 // FIXME: Rename and handle conversion of other evaluatable things
1776 // to bool.
1778 if (!Cond->EvaluateAsInt(Result, getContext()))
1779 return false; // Not foldable, not integer or not fully evaluatable.
1780
1781 llvm::APSInt Int = Result.Val.getInt();
1782 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1783 return false; // Contains a label.
1784
1785 PGO->markStmtMaybeUsed(Cond);
1786 ResultInt = std::move(Int);
1787 return true;
1788}
1789
1790/// Strip parentheses and simplistic logical-NOT operators.
1792 while (true) {
1793 const Expr *SC = IgnoreExprNodes(
1796 if (C == SC)
1797 return SC;
1798 C = SC;
1799 }
1800}
1801
1802/// Determine whether the given condition is an instrumentable condition
1803/// (i.e. no "&&" or "||").
1805 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1806 return (!BOp || !BOp->isLogicalOp());
1807}
1808
1809/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1810/// increments a profile counter based on the semantics of the given logical
1811/// operator opcode. This is used to instrument branch condition coverage for
1812/// logical operators.
1814 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1815 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1816 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1817 // If not instrumenting, just emit a branch.
1818 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1819 if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1820 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1821
1822 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1823
1824 llvm::BasicBlock *ThenBlock = nullptr;
1825 llvm::BasicBlock *ElseBlock = nullptr;
1826 llvm::BasicBlock *NextBlock = nullptr;
1827
1828 // Create the block we'll use to increment the appropriate counter.
1829 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1830
1831 llvm::BasicBlock *SkipIncrBlock =
1832 (hasSkipCounter(CntrStmt) ? createBasicBlock("lop.rhsskip") : nullptr);
1833 llvm::BasicBlock *SkipNextBlock = nullptr;
1834
1835 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1836 // means we need to evaluate the condition and increment the counter on TRUE:
1837 //
1838 // if (Cond)
1839 // goto CounterIncrBlock;
1840 // else
1841 // goto FalseBlock;
1842 //
1843 // CounterIncrBlock:
1844 // Counter++;
1845 // goto TrueBlock;
1846
1847 if (LOp == BO_LAnd) {
1848 SkipNextBlock = FalseBlock;
1849 ThenBlock = CounterIncrBlock;
1850 ElseBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1851 NextBlock = TrueBlock;
1852 }
1853
1854 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1855 // we need to evaluate the condition and increment the counter on FALSE:
1856 //
1857 // if (Cond)
1858 // goto TrueBlock;
1859 // else
1860 // goto CounterIncrBlock;
1861 //
1862 // CounterIncrBlock:
1863 // Counter++;
1864 // goto FalseBlock;
1865
1866 else if (LOp == BO_LOr) {
1867 SkipNextBlock = TrueBlock;
1868 ThenBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1869 ElseBlock = CounterIncrBlock;
1870 NextBlock = FalseBlock;
1871 } else {
1872 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1873 }
1874
1875 // Emit Branch based on condition.
1876 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1877
1878 if (SkipIncrBlock) {
1879 EmitBlock(SkipIncrBlock);
1881 EmitBranch(SkipNextBlock);
1882 }
1883
1884 // Emit the block containing the counter increment(s).
1885 EmitBlock(CounterIncrBlock);
1886
1887 // Increment corresponding counter; if index not provided, use Cond as index.
1889
1890 // Go to the next block.
1891 EmitBranch(NextBlock);
1892}
1893
1894/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1895/// statement) to the specified blocks. Based on the condition, this might try
1896/// to simplify the codegen of the conditional based on the branch.
1897/// \param LH The value of the likelihood attribute on the True branch.
1898/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1899/// ConditionalOperator (ternary) through a recursive call for the operator's
1900/// LHS and RHS nodes.
1902 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1903 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp,
1904 const VarDecl *ConditionalDecl) {
1905 Cond = Cond->IgnoreParens();
1906
1907 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1908 bool HasSkip = hasSkipCounter(CondBOp);
1909
1910 // Handle X && Y in a condition.
1911 if (CondBOp->getOpcode() == BO_LAnd) {
1912 // If we have "1 && X", simplify the code. "0 && X" would have constant
1913 // folded if the case was simple enough.
1914 bool ConstantBool = false;
1915 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1916 ConstantBool) {
1917 // br(1 && X) -> br(X).
1918 incrementProfileCounter(CondBOp);
1919 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1920 FalseBlock, TrueCount, LH);
1921 return;
1922 }
1923
1924 // If we have "X && 1", simplify the code to use an uncond branch.
1925 // "X && 0" would have been constant folded to 0.
1926 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1927 ConstantBool) {
1928 // br(X && 1) -> br(X).
1929 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1930 FalseBlock, TrueCount, LH, CondBOp);
1931 return;
1932 }
1933
1934 // Emit the LHS as a conditional. If the LHS conditional is false, we
1935 // want to jump to the FalseBlock.
1936 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1937 llvm::BasicBlock *LHSFalse =
1938 (HasSkip ? createBasicBlock("land.lhsskip") : FalseBlock);
1939 // The counter tells us how often we evaluate RHS, and all of TrueCount
1940 // can be propagated to that branch.
1941 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1942
1943 ConditionalEvaluation eval(*this);
1944 {
1945 ApplyDebugLocation DL(*this, Cond);
1946 // Propagate the likelihood attribute like __builtin_expect
1947 // __builtin_expect(X && Y, 1) -> X and Y are likely
1948 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1949 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, LHSFalse, RHSCount,
1950 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1951 if (HasSkip) {
1952 EmitBlock(LHSFalse);
1954 EmitBranch(FalseBlock);
1955 }
1956 EmitBlock(LHSTrue);
1957 }
1958
1960 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1961
1962 // Any temporaries created here are conditional.
1963 eval.begin(*this);
1964 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1965 FalseBlock, TrueCount, LH);
1966 eval.end(*this);
1967 return;
1968 }
1969
1970 if (CondBOp->getOpcode() == BO_LOr) {
1971 // If we have "0 || X", simplify the code. "1 || X" would have constant
1972 // folded if the case was simple enough.
1973 bool ConstantBool = false;
1974 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1975 !ConstantBool) {
1976 // br(0 || X) -> br(X).
1977 incrementProfileCounter(CondBOp);
1978 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1979 FalseBlock, TrueCount, LH);
1980 return;
1981 }
1982
1983 // If we have "X || 0", simplify the code to use an uncond branch.
1984 // "X || 1" would have been constant folded to 1.
1985 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1986 !ConstantBool) {
1987 // br(X || 0) -> br(X).
1988 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1989 FalseBlock, TrueCount, LH, CondBOp);
1990 return;
1991 }
1992 // Emit the LHS as a conditional. If the LHS conditional is true, we
1993 // want to jump to the TrueBlock.
1994 llvm::BasicBlock *LHSTrue =
1995 (HasSkip ? createBasicBlock("lor.lhsskip") : TrueBlock);
1996 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1997 // We have the count for entry to the RHS and for the whole expression
1998 // being true, so we can divy up True count between the short circuit and
1999 // the RHS.
2000 uint64_t LHSCount =
2001 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
2002 uint64_t RHSCount = TrueCount - LHSCount;
2003
2004 ConditionalEvaluation eval(*this);
2005 {
2006 // Propagate the likelihood attribute like __builtin_expect
2007 // __builtin_expect(X || Y, 1) -> only Y is likely
2008 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
2009 ApplyDebugLocation DL(*this, Cond);
2010 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, LHSFalse, LHSCount,
2011 LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
2012 if (HasSkip) {
2013 EmitBlock(LHSTrue);
2015 EmitBranch(TrueBlock);
2016 }
2017 EmitBlock(LHSFalse);
2018 }
2019
2021 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
2022
2023 // Any temporaries created here are conditional.
2024 eval.begin(*this);
2025 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
2026 RHSCount, LH);
2027
2028 eval.end(*this);
2029 return;
2030 }
2031 }
2032
2033 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
2034 // br(!x, t, f) -> br(x, f, t)
2035 // Avoid doing this optimization when instrumenting a condition for MC/DC.
2036 // LNot is taken as part of the condition for simplicity, and changing its
2037 // sense negatively impacts test vector tracking.
2038 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
2039 CGM.getCodeGenOpts().MCDCCoverage &&
2041 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2042 // Negate the count.
2043 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
2044 // The values of the enum are chosen to make this negation possible.
2045 LH = static_cast<Stmt::Likelihood>(-LH);
2046 // Negate the condition and swap the destination blocks.
2047 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
2048 FalseCount, LH);
2049 }
2050 }
2051
2052 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
2053 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
2054 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
2055 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
2056
2057 // The ConditionalOperator itself has no likelihood information for its
2058 // true and false branches. This matches the behavior of __builtin_expect.
2059 ConditionalEvaluation cond(*this);
2060 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
2062
2063 // When computing PGO branch weights, we only know the overall count for
2064 // the true block. This code is essentially doing tail duplication of the
2065 // naive code-gen, introducing new edges for which counts are not
2066 // available. Divide the counts proportionally between the LHS and RHS of
2067 // the conditional operator.
2068 uint64_t LHSScaledTrueCount = 0;
2069 if (TrueCount) {
2070 double LHSRatio =
2071 getProfileCount(CondOp) / (double)getCurrentProfileCount();
2072 LHSScaledTrueCount = TrueCount * LHSRatio;
2073 }
2074
2075 cond.begin(*this);
2076 EmitBlock(LHSBlock);
2078 {
2079 ApplyDebugLocation DL(*this, Cond);
2080 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
2081 LHSScaledTrueCount, LH, CondOp);
2082 }
2083 cond.end(*this);
2084
2085 cond.begin(*this);
2086 EmitBlock(RHSBlock);
2088 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
2089 TrueCount - LHSScaledTrueCount, LH, CondOp);
2090 cond.end(*this);
2091
2092 return;
2093 }
2094
2095 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2096 // Conditional operator handling can give us a throw expression as a
2097 // condition for a case like:
2098 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2099 // Fold this to:
2100 // br(c, throw x, br(y, t, f))
2101 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
2102 return;
2103 }
2104
2105 // Emit the code with the fully general case.
2106 llvm::Value *CondV;
2107 {
2108 ApplyDebugLocation DL(*this, Cond);
2109 CondV = EvaluateExprAsBool(Cond);
2110 }
2111
2112 MaybeEmitDeferredVarDeclInit(ConditionalDecl);
2113
2114 // If not at the top of the logical operator nest, update MCDC temp with the
2115 // boolean result of the evaluated condition.
2116 {
2117 const Expr *MCDCBaseExpr = Cond;
2118 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2119 // expression, MC/DC tracks the result of the ternary, and this is tied to
2120 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2121 // this is the case, the ConditionalOperator expression is passed through
2122 // the ConditionalOp parameter and then used as the MCDC base expression.
2123 if (ConditionalOp)
2124 MCDCBaseExpr = ConditionalOp;
2125
2126 if (isMCDCBranchExpr(stripCond(MCDCBaseExpr)) &&
2128 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2129 }
2130
2131 llvm::MDNode *Weights = nullptr;
2132 llvm::MDNode *Unpredictable = nullptr;
2133
2134 // If the branch has a condition wrapped by __builtin_unpredictable,
2135 // create metadata that specifies that the branch is unpredictable.
2136 // Don't bother if not optimizing because that metadata would not be used.
2137 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2138 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2139 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2140 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2141 llvm::MDBuilder MDHelper(getLLVMContext());
2142 Unpredictable = MDHelper.createUnpredictable();
2143 }
2144 }
2145
2146 // If there is a Likelihood knowledge for the cond, lower it.
2147 // Note that if not optimizing this won't emit anything.
2148 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2149 if (CondV != NewCondV)
2150 CondV = NewCondV;
2151 else {
2152 // Otherwise, lower profile counts. Note that we do this even at -O0.
2153 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2154 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2155 }
2156
2157 llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, FalseBlock,
2158 Weights, Unpredictable);
2159 addInstToNewSourceAtom(BrInst, CondV);
2160
2161 switch (HLSLControlFlowAttr) {
2162 case HLSLControlFlowHintAttr::Microsoft_branch:
2163 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2164 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2165
2166 llvm::ConstantInt *BranchHintConstant =
2168 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2169 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2170 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2171
2173 {MDHelper.createString("hlsl.controlflow.hint"),
2174 MDHelper.createConstant(BranchHintConstant)});
2175 BrInst->setMetadata("hlsl.controlflow.hint",
2176 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2177 break;
2178 }
2179 // This is required to avoid warnings during compilation
2180 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2181 break;
2182 }
2183}
2184
2185llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
2186 unsigned Idx,
2187 const CallExpr *E) {
2188 llvm::Value *Arg = nullptr;
2189 if ((ICEArguments & (1 << Idx)) == 0) {
2190 Arg = EmitScalarExpr(E->getArg(Idx));
2191 } else {
2192 // If this is required to be a constant, constant fold it so that we
2193 // know that the generated intrinsic gets a ConstantInt.
2194 std::optional<llvm::APSInt> Result =
2196 assert(Result && "Expected argument to be a constant");
2197 Arg = llvm::ConstantInt::get(getLLVMContext(), *Result);
2198 }
2199 return Arg;
2200}
2201
2202/// ErrorUnsupported - Print out an error that codegen doesn't support the
2203/// specified stmt yet.
2204void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2205 CGM.ErrorUnsupported(S, Type);
2206}
2207
2208/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2209/// variable-length array whose elements have a non-zero bit-pattern.
2210///
2211/// \param baseType the inner-most element type of the array
2212/// \param src - a char* pointing to the bit-pattern for a single
2213/// base element of the array
2214/// \param sizeInChars - the total size of the VLA, in chars
2216 Address dest, Address src,
2217 llvm::Value *sizeInChars) {
2218 CGBuilderTy &Builder = CGF.Builder;
2219
2220 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2221 llvm::Value *baseSizeInChars
2222 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2223
2224 Address begin = dest.withElementType(CGF.Int8Ty);
2225 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2226 begin.emitRawPointer(CGF),
2227 sizeInChars, "vla.end");
2228
2229 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2230 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2231 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2232
2233 // Make a loop over the VLA. C99 guarantees that the VLA element
2234 // count must be nonzero.
2235 CGF.EmitBlock(loopBB);
2236
2237 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2238 cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2239
2240 CharUnits curAlign =
2241 dest.getAlignment().alignmentOfArrayElement(baseSize);
2242
2243 // memcpy the individual element bit-pattern.
2244 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2245 /*volatile*/ false);
2246
2247 // Go to the next element.
2248 llvm::Value *next =
2249 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2250
2251 // Leave if that's the end of the VLA.
2252 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2253 Builder.CreateCondBr(done, contBB, loopBB);
2254 cur->addIncoming(next, loopBB);
2255
2256 CGF.EmitBlock(contBB);
2257}
2258
2260 const PFPField &Field) {
2261 return EmitAddressOfPFPField(
2262 RecordPtr,
2263 Builder.CreateConstInBoundsByteGEP(RecordPtr.withElementType(Int8Ty),
2264 Field.Offset),
2265 Field.Field);
2266}
2267
2269 Address PtrPtr,
2270 const FieldDecl *Field) {
2271 llvm::Value *Disc;
2272 if (CGM.getContext().arePFPFieldsTriviallyCopyable(Field->getParent())) {
2273 uint64_t FieldSignature =
2274 llvm::getPointerAuthStableSipHash(CGM.getPFPFieldName(Field));
2275 Disc = llvm::ConstantInt::get(CGM.Int64Ty, FieldSignature);
2276 } else
2277 Disc = Builder.CreatePtrToInt(RecordPtr.getBasePointer(), CGM.Int64Ty);
2278
2279 llvm::GlobalValue *DS = CGM.getPFPDeactivationSymbol(Field);
2280 llvm::OperandBundleDef DSBundle("deactivation-symbol", DS);
2281 llvm::Value *Args[] = {PtrPtr.getBasePointer(), Disc, Builder.getTrue()};
2282 return Address(
2283 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::protected_field_ptr,
2284 PtrPtr.getType()),
2285 Args, DSBundle),
2286 VoidPtrTy, PtrPtr.getAlignment());
2287}
2288
2289void
2291 // Ignore empty classes in C++.
2292 if (getLangOpts().CPlusPlus)
2293 if (const auto *RD = Ty->getAsCXXRecordDecl(); RD && RD->isEmpty())
2294 return;
2295
2296 if (DestPtr.getElementType() != Int8Ty)
2297 DestPtr = DestPtr.withElementType(Int8Ty);
2298
2299 // Get size and alignment info for this aggregate.
2301
2302 llvm::Value *SizeVal;
2303 const VariableArrayType *vla;
2304
2305 // Don't bother emitting a zero-byte memset.
2306 if (size.isZero()) {
2307 // But note that getTypeInfo returns 0 for a VLA.
2308 if (const VariableArrayType *vlaType =
2309 dyn_cast_or_null<VariableArrayType>(
2310 getContext().getAsArrayType(Ty))) {
2311 auto VlaSize = getVLASize(vlaType);
2312 SizeVal = VlaSize.NumElts;
2313 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2314 if (!eltSize.isOne())
2315 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2316 vla = vlaType;
2317 } else {
2318 return;
2319 }
2320 } else {
2321 SizeVal = CGM.getSize(size);
2322 vla = nullptr;
2323 }
2324
2325 // If the type contains a pointer to data member we can't memset it to zero.
2326 // Instead, create a null constant and copy it to the destination.
2327 // TODO: there are other patterns besides zero that we can usefully memset,
2328 // like -1, which happens to be the pattern used by member-pointers.
2329 if (!CGM.getTypes().isZeroInitializable(Ty)) {
2330 // For a VLA, emit a single element, then splat that over the VLA.
2331 if (vla) Ty = getContext().getBaseElementType(vla);
2332
2333 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2334
2335 llvm::GlobalVariable *NullVariable =
2336 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2337 /*isConstant=*/true,
2338 llvm::GlobalVariable::PrivateLinkage,
2339 NullConstant, Twine());
2340 CharUnits NullAlign = DestPtr.getAlignment();
2341 NullVariable->setAlignment(NullAlign.getAsAlign());
2342 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2343
2344 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2345
2346 // Get and call the appropriate llvm.memcpy overload.
2347 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2348 } else {
2349 // Otherwise, just memset the whole thing to zero. This is legal
2350 // because in LLVM, all default initializers (other than the ones we just
2351 // handled above, and the case handled below) are guaranteed to have a bit
2352 // pattern of all zeros.
2353 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2354 }
2355
2356 // With the pointer field protection feature, null pointers do not have a bit
2357 // pattern of zero in memory, so we must initialize them separately.
2358 for (auto &Field : getContext().findPFPFields(Ty)) {
2359 auto addr = EmitAddressOfPFPField(DestPtr, Field);
2360 Builder.CreateStore(llvm::ConstantPointerNull::get(VoidPtrTy), addr);
2361 }
2362}
2363
2364llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2365 // Make sure that there is a block for the indirect goto.
2366 if (!IndirectBranch)
2368
2369 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2370
2371 // Make sure the indirect branch includes all of the address-taken blocks.
2372 IndirectBranch->addDestination(BB);
2373 return llvm::BlockAddress::get(CurFn->getType(), BB);
2374}
2375
2377 // If we already made the indirect branch for indirect goto, return its block.
2378 if (IndirectBranch) return IndirectBranch->getParent();
2379
2380 CGBuilderTy TmpBuilder(CGM, createBasicBlock("indirectgoto"));
2381
2382 // Create the PHI node that indirect gotos will add entries to.
2383 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2384 "indirect.goto.dest");
2385
2386 // Create the indirect branch instruction.
2387 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2388 return IndirectBranch->getParent();
2389}
2390
2391/// Computes the length of an array in elements, as well as the base
2392/// element type and a properly-typed first element pointer.
2393llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2394 QualType &baseType,
2395 Address &addr) {
2396 const ArrayType *arrayType = origArrayType;
2397
2398 // If it's a VLA, we have to load the stored size. Note that
2399 // this is the size of the VLA in bytes, not its size in elements.
2400 llvm::Value *numVLAElements = nullptr;
2403
2404 // Walk into all VLAs. This doesn't require changes to addr,
2405 // which has type T* where T is the first non-VLA element type.
2406 do {
2407 QualType elementType = arrayType->getElementType();
2408 arrayType = getContext().getAsArrayType(elementType);
2409
2410 // If we only have VLA components, 'addr' requires no adjustment.
2411 if (!arrayType) {
2412 baseType = elementType;
2413 return numVLAElements;
2414 }
2416
2417 // We get out here only if we find a constant array type
2418 // inside the VLA.
2419 }
2420
2421 // We have some number of constant-length arrays, so addr should
2422 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2423 // down to the first element of addr.
2425
2426 // GEP down to the array type.
2427 llvm::ConstantInt *zero = Builder.getInt32(0);
2428 gepIndices.push_back(zero);
2429
2430 uint64_t countFromCLAs = 1;
2431 QualType eltType;
2432
2433 llvm::ArrayType *llvmArrayType =
2434 dyn_cast<llvm::ArrayType>(addr.getElementType());
2435 while (llvmArrayType) {
2437 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2438 llvmArrayType->getNumElements());
2439
2440 gepIndices.push_back(zero);
2441 countFromCLAs *= llvmArrayType->getNumElements();
2442 eltType = arrayType->getElementType();
2443
2444 llvmArrayType =
2445 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2446 arrayType = getContext().getAsArrayType(arrayType->getElementType());
2447 assert((!llvmArrayType || arrayType) &&
2448 "LLVM and Clang types are out-of-synch");
2449 }
2450
2451 if (arrayType) {
2452 // From this point onwards, the Clang array type has been emitted
2453 // as some other type (probably a packed struct). Compute the array
2454 // size, and just emit the 'begin' expression as a bitcast.
2455 while (arrayType) {
2456 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2457 eltType = arrayType->getElementType();
2458 arrayType = getContext().getAsArrayType(eltType);
2459 }
2460
2461 llvm::Type *baseType = ConvertType(eltType);
2462 addr = addr.withElementType(baseType);
2463 } else {
2464 // Create the actual GEP.
2465 addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
2466 addr.emitRawPointer(*this),
2467 gepIndices, "array.begin"),
2468 ConvertTypeForMem(eltType), addr.getAlignment());
2469 }
2470
2471 baseType = eltType;
2472
2473 llvm::Value *numElements
2474 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2475
2476 // If we had any VLA dimensions, factor them in.
2477 if (numVLAElements)
2478 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2479
2480 return numElements;
2481}
2482
2485 assert(vla && "type was not a variable array type!");
2486 return getVLASize(vla);
2487}
2488
2491 // The number of elements so far; always size_t.
2492 llvm::Value *numElements = nullptr;
2493
2494 QualType elementType;
2495 do {
2496 elementType = type->getElementType();
2497 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2498 assert(vlaSize && "no size for VLA!");
2499 assert(vlaSize->getType() == SizeTy);
2500
2501 if (!numElements) {
2502 numElements = vlaSize;
2503 } else {
2504 // It's undefined behavior if this wraps around, so mark it that way.
2505 // FIXME: Teach -fsanitize=undefined to trap this.
2506 numElements = Builder.CreateNUWMul(numElements, vlaSize);
2507 }
2508 } while ((type = getContext().getAsVariableArrayType(elementType)));
2509
2510 return { numElements, elementType };
2511}
2512
2516 assert(vla && "type was not a variable array type!");
2517 return getVLAElements1D(vla);
2518}
2519
2522 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2523 assert(VlaSize && "no size for VLA!");
2524 assert(VlaSize->getType() == SizeTy);
2525 return { VlaSize, Vla->getElementType() };
2526}
2527
2529 assert(type->isVariablyModifiedType() &&
2530 "Must pass variably modified type to EmitVLASizes!");
2531
2533
2534 // We're going to walk down into the type and look for VLA
2535 // expressions.
2536 do {
2537 assert(type->isVariablyModifiedType());
2538
2539 const Type *ty = type.getTypePtr();
2540 switch (ty->getTypeClass()) {
2541
2542#define TYPE(Class, Base)
2543#define ABSTRACT_TYPE(Class, Base)
2544#define NON_CANONICAL_TYPE(Class, Base)
2545#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2546#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2547#include "clang/AST/TypeNodes.inc"
2548 llvm_unreachable("unexpected dependent type!");
2549
2550 // These types are never variably-modified.
2551 case Type::Builtin:
2552 case Type::Complex:
2553 case Type::Vector:
2554 case Type::ExtVector:
2555 case Type::ConstantMatrix:
2556 case Type::Record:
2557 case Type::Enum:
2558 case Type::Using:
2559 case Type::TemplateSpecialization:
2560 case Type::ObjCTypeParam:
2561 case Type::ObjCObject:
2562 case Type::ObjCInterface:
2563 case Type::ObjCObjectPointer:
2564 case Type::BitInt:
2565 case Type::HLSLInlineSpirv:
2566 case Type::PredefinedSugar:
2567 llvm_unreachable("type class is never variably-modified!");
2568
2569 case Type::Adjusted:
2570 type = cast<AdjustedType>(ty)->getAdjustedType();
2571 break;
2572
2573 case Type::Decayed:
2574 type = cast<DecayedType>(ty)->getPointeeType();
2575 break;
2576
2577 case Type::Pointer:
2578 type = cast<PointerType>(ty)->getPointeeType();
2579 break;
2580
2581 case Type::BlockPointer:
2582 type = cast<BlockPointerType>(ty)->getPointeeType();
2583 break;
2584
2585 case Type::LValueReference:
2586 case Type::RValueReference:
2587 type = cast<ReferenceType>(ty)->getPointeeType();
2588 break;
2589
2590 case Type::MemberPointer:
2591 type = cast<MemberPointerType>(ty)->getPointeeType();
2592 break;
2593
2594 case Type::ArrayParameter:
2595 case Type::ConstantArray:
2596 case Type::IncompleteArray:
2597 // Losing element qualification here is fine.
2598 type = cast<ArrayType>(ty)->getElementType();
2599 break;
2600
2601 case Type::VariableArray: {
2602 // Losing element qualification here is fine.
2604
2605 // Unknown size indication requires no size computation.
2606 // Otherwise, evaluate and record it.
2607 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2608 // It's possible that we might have emitted this already,
2609 // e.g. with a typedef and a pointer to it.
2610 llvm::Value *&entry = VLASizeMap[sizeExpr];
2611 if (!entry) {
2612 llvm::Value *size = EmitScalarExpr(sizeExpr);
2613
2614 // C11 6.7.6.2p5:
2615 // If the size is an expression that is not an integer constant
2616 // expression [...] each time it is evaluated it shall have a value
2617 // greater than zero.
2618 if (SanOpts.has(SanitizerKind::VLABound)) {
2619 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2620 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2621 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2622 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2623 clang::QualType SEType = sizeExpr->getType();
2624 llvm::Value *CheckCondition =
2625 SEType->isSignedIntegerType()
2626 ? Builder.CreateICmpSGT(size, Zero)
2627 : Builder.CreateICmpUGT(size, Zero);
2628 llvm::Constant *StaticArgs[] = {
2629 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2630 EmitCheckTypeDescriptor(SEType)};
2631 EmitCheck(std::make_pair(CheckCondition, CheckOrdinal),
2632 CheckHandler, StaticArgs, size);
2633 }
2634
2635 // Always zexting here would be wrong if it weren't
2636 // undefined behavior to have a negative bound.
2637 // FIXME: What about when size's type is larger than size_t?
2638 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2639 }
2640 }
2641 type = vat->getElementType();
2642 break;
2643 }
2644
2645 case Type::FunctionProto:
2646 case Type::FunctionNoProto:
2647 type = cast<FunctionType>(ty)->getReturnType();
2648 break;
2649
2650 case Type::Paren:
2651 case Type::TypeOf:
2652 case Type::UnaryTransform:
2653 case Type::Attributed:
2654 case Type::BTFTagAttributed:
2655 case Type::OverflowBehavior:
2656 case Type::HLSLAttributedResource:
2657 case Type::SubstTemplateTypeParm:
2658 case Type::MacroQualified:
2659 case Type::CountAttributed:
2660 case Type::LateParsedAttr:
2661 // Keep walking after single level desugaring.
2662 type = type.getSingleStepDesugaredType(getContext());
2663 break;
2664
2665 case Type::Typedef:
2666 case Type::Decltype:
2667 case Type::Auto:
2668 case Type::DeducedTemplateSpecialization:
2669 case Type::PackIndexing:
2670 // Stop walking: nothing to do.
2671 return;
2672
2673 case Type::TypeOfExpr:
2674 // Stop walking: emit typeof expression.
2675 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2676 return;
2677
2678 case Type::Atomic:
2679 type = cast<AtomicType>(ty)->getValueType();
2680 break;
2681
2682 case Type::Pipe:
2683 type = cast<PipeType>(ty)->getElementType();
2684 break;
2685 }
2686 } while (type->isVariablyModifiedType());
2687}
2688
2690 if (getContext().getBuiltinVaListType()->isArrayType())
2691 return EmitPointerWithAlignment(E);
2692 return EmitLValue(E).getAddress();
2693}
2694
2698
2702
2704 const APValue &Init) {
2705 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2706 if (CGDebugInfo *Dbg = getDebugInfo())
2707 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2708 Dbg->EmitGlobalVariable(E->getDecl(), Init);
2709}
2710
2713 // At the moment, the only aggressive peephole we do in IR gen
2714 // is trunc(zext) folding, but if we add more, we can easily
2715 // extend this protection.
2716
2717 if (!rvalue.isScalar()) return PeepholeProtection();
2718 llvm::Value *value = rvalue.getScalarVal();
2719 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2720
2721 // Just make an extra bitcast.
2722 assert(HaveInsertPoint());
2723 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2724 Builder.GetInsertBlock());
2725
2726 PeepholeProtection protection;
2727 protection.Inst = inst;
2728 return protection;
2729}
2730
2732 if (!protection.Inst) return;
2733
2734 // In theory, we could try to duplicate the peepholes now, but whatever.
2735 protection.Inst->eraseFromParent();
2736}
2737
2739 QualType Ty, SourceLocation Loc,
2740 SourceLocation AssumptionLoc,
2741 llvm::Value *Alignment,
2742 llvm::Value *OffsetValue) {
2743 if (Alignment->getType() != IntPtrTy)
2744 Alignment =
2745 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2746 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2747 OffsetValue =
2748 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2749 llvm::Value *TheCheck = nullptr;
2750 if (SanOpts.has(SanitizerKind::Alignment)) {
2751 llvm::Value *PtrIntValue =
2752 Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2753
2754 if (OffsetValue) {
2755 bool IsOffsetZero = false;
2756 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2757 IsOffsetZero = CI->isZero();
2758
2759 if (!IsOffsetZero)
2760 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2761 }
2762
2763 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2764 llvm::Value *Mask =
2765 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2766 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2767 TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2768 }
2769 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2770 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2771
2772 if (!SanOpts.has(SanitizerKind::Alignment))
2773 return;
2774 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2775 OffsetValue, TheCheck, Assumption);
2776}
2777
2779 const Expr *E,
2780 SourceLocation AssumptionLoc,
2781 llvm::Value *Alignment,
2782 llvm::Value *OffsetValue) {
2783 QualType Ty = E->getType();
2784 SourceLocation Loc = E->getExprLoc();
2785
2786 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2787 OffsetValue);
2788}
2789
2790llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2791 llvm::Value *AnnotatedVal,
2792 StringRef AnnotationStr,
2793 SourceLocation Location,
2794 const AnnotateAttr *Attr) {
2796 AnnotatedVal,
2797 CGM.EmitAnnotationString(AnnotationStr),
2798 CGM.EmitAnnotationUnit(Location),
2799 CGM.EmitAnnotationLineNo(Location),
2800 };
2801 if (Attr)
2802 Args.push_back(CGM.EmitAnnotationArgs(Attr));
2803 return Builder.CreateCall(AnnotationFn, Args);
2804}
2805
2806void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2807 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2808 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2809 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2810 {V->getType(), CGM.ConstGlobalsPtrTy}),
2811 V, I->getAnnotation(), D->getLocation(), I);
2812}
2813
2815 Address Addr) {
2816 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2817 llvm::Value *V = Addr.emitRawPointer(*this);
2818 llvm::Type *VTy = V->getType();
2819 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2820 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2821 llvm::PointerType *IntrinTy =
2822 llvm::PointerType::get(CGM.getLLVMContext(), AS);
2823 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2824 {IntrinTy, CGM.ConstGlobalsPtrTy});
2825
2826 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2827 // FIXME Always emit the cast inst so we can differentiate between
2828 // annotation on the first field of a struct and annotation on the struct
2829 // itself.
2830 if (VTy != IntrinTy)
2831 V = Builder.CreateBitCast(V, IntrinTy);
2832 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2833 V = Builder.CreateBitCast(V, VTy);
2834 }
2835
2836 return Address(V, Addr.getElementType(), Addr.getAlignment());
2837}
2838
2840
2842 : CGF(CGF) {
2843 assert(!CGF->IsSanitizerScope);
2844 CGF->IsSanitizerScope = true;
2845}
2846
2848 CGF->IsSanitizerScope = false;
2849}
2850
2851void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2852 const llvm::Twine &Name,
2853 llvm::BasicBlock::iterator InsertPt) const {
2854 LoopStack.InsertHelper(I);
2855 if (IsSanitizerScope)
2856 I->setNoSanitizeMetadata();
2857}
2858
2860 llvm::Instruction *I, const llvm::Twine &Name,
2861 llvm::BasicBlock::iterator InsertPt) const {
2862 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2863 if (CGF)
2864 CGF->InsertHelper(I, Name, InsertPt);
2865}
2866
2867// Emits an error if we don't have a valid set of target features for the
2868// called function.
2870 const FunctionDecl *TargetDecl) {
2871 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2872 CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
2873 getLangOpts(), E, FD, TargetDecl);
2874}
2875
2876// Emits an error if we don't have a valid set of target features for the
2877// called function.
2879 const FunctionDecl *TargetDecl) {
2880 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2881 CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
2882 getLangOpts(), Loc, FD, TargetDecl);
2883}
2884
2885void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2886 if (!CGM.getCodeGenOpts().SanitizeStats)
2887 return;
2888
2889 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2890 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2891 CGM.getSanStats().create(IRB, SSK);
2892}
2893
2895 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2896 const CGCalleeInfo &CI = Callee.getAbstractInfo();
2898 if (!FP)
2899 return;
2900
2901 StringRef Salt;
2902 if (const auto &Info = FP->getExtraAttributeInfo())
2903 Salt = Info.CFISalt;
2904
2905 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar(), Salt));
2906}
2907
2908llvm::Value *
2909CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2910 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(RO.Features);
2911}
2912
2913llvm::Value *
2914CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2915 llvm::Value *Condition = nullptr;
2916
2917 if (RO.Architecture) {
2918 StringRef Arch = *RO.Architecture;
2919 // If arch= specifies an x86-64 micro-architecture level, test the feature
2920 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2921 if (Arch.starts_with("x86-64"))
2922 Condition = EmitX86CpuSupports({Arch});
2923 else
2924 Condition = EmitX86CpuIs(Arch);
2925 }
2926
2927 if (!RO.Features.empty()) {
2928 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2929 Condition =
2930 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2931 }
2932 return Condition;
2933}
2934
2936 llvm::Function *Resolver,
2937 CGBuilderTy &Builder,
2938 llvm::Function *FuncToReturn,
2939 bool SupportsIFunc) {
2940 if (SupportsIFunc) {
2941 Builder.CreateRet(FuncToReturn);
2942 return;
2943 }
2944
2946 llvm::make_pointer_range(Resolver->args()));
2947
2948 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2949 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2950
2951 if (Resolver->getReturnType()->isVoidTy())
2952 Builder.CreateRetVoid();
2953 else
2954 Builder.CreateRet(Result);
2955}
2956
2958 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2959 llvm::SaveAndRestore<llvm::Function *> savedCurFn(CurFn, Resolver);
2960 llvm::Triple::ArchType ArchType =
2961 getContext().getTargetInfo().getTriple().getArch();
2962
2963 switch (ArchType) {
2964 case llvm::Triple::x86:
2965 case llvm::Triple::x86_64:
2966 EmitX86MultiVersionResolver(Resolver, Options);
2967 return;
2968 case llvm::Triple::aarch64:
2969 EmitAArch64MultiVersionResolver(Resolver, Options);
2970 return;
2971 case llvm::Triple::riscv32:
2972 case llvm::Triple::riscv64:
2973 case llvm::Triple::riscv32be:
2974 case llvm::Triple::riscv64be:
2975 EmitRISCVMultiVersionResolver(Resolver, Options);
2976 return;
2977 case llvm::Triple::ppc:
2978 case llvm::Triple::ppc64:
2979 if (getContext().getTargetInfo().getTriple().isOSAIX()) {
2980 EmitPPCAIXMultiVersionResolver(Resolver, Options);
2981 return;
2982 }
2983 [[fallthrough]];
2984 default:
2985 assert(false &&
2986 "Only implemented for x86, AArch64, RISC-V, and PowerPC AIX");
2987 }
2988}
2989
2990/**
2991 * define internal ptr @foo.resolver() {
2992 * entry:
2993 * %is_version_1 = __builtin_cpu_supports(version_1)
2994 * br i1 %1, label %if.version_1, label %if.else_2
2995 *
2996 * if.version_1:
2997 * ret ptr @foo.version_1
2998 *
2999 * if.else_2:
3000 * %is_version_2 = __builtin_cpu_supports(version_2)
3001 * ...
3002 * if.else: ; preds = %entry
3003 * ret ptr @foo.default
3004 * }
3005 */
3007 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3008
3009 // entry:
3010 llvm::BasicBlock *CurBlock = createBasicBlock("entry", Resolver);
3011
3013 for (const FMVResolverOption &RO : Options) {
3014 Builder.SetInsertPoint(CurBlock);
3015 // The 'default' or 'generic' case.
3016 if (!RO.Architecture && RO.Features.empty()) {
3017 // if.else:
3018 // ret ptr @foo.default
3019 assert(&RO == Options.end() - 1 &&
3020 "Default or Generic case must be last");
3021 Builder.CreateRet(RO.Function);
3022 return;
3023 }
3024 // if.else_n:
3025 // %is_version_n = __builtin_cpu_supports(version_n)
3026 // br i1 %is_version_n, label %if.version_n, label %if.else_n+1
3027 //
3028 // if.version_n:
3029 // ret ptr @foo_version_n
3030 assert(RO.Features.size() == 1 &&
3031 "for now one feature requirement per version");
3032
3033 assert(RO.Features[0].starts_with("cpu="));
3034 StringRef CPU = RO.Features[0].split("=").second.trim();
3035 StringRef Feature = llvm::StringSwitch<StringRef>(CPU)
3036 .Case("pwr7", "arch_2_06")
3037 .Case("pwr8", "arch_2_07")
3038 .Case("pwr9", "arch_3_00")
3039 .Case("pwr10", "arch_3_1")
3040 .Case("pwr11", "arch_3_1")
3041 .Default("error");
3042
3043 llvm::Value *Condition = EmitPPCBuiltinCpu(
3044 Builtin::BI__builtin_cpu_supports, Builder.getInt1Ty(), Feature);
3045
3046 llvm::BasicBlock *ThenBlock = createBasicBlock("if.version", Resolver);
3047 CurBlock = createBasicBlock("if.else", Resolver);
3048 Builder.CreateCondBr(Condition, ThenBlock, CurBlock);
3049
3050 Builder.SetInsertPoint(ThenBlock);
3051 Builder.CreateRet(RO.Function);
3052 }
3053
3054 llvm_unreachable("Default case missing");
3055}
3056
3058 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3059
3060 if (getContext().getTargetInfo().getTriple().getOS() !=
3061 llvm::Triple::OSType::Linux) {
3062 CGM.getDiags().Report(diag::err_os_unsupport_riscv_fmv);
3063 return;
3064 }
3065
3066 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3067 Builder.SetInsertPoint(CurBlock);
3069
3070 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3071 bool HasDefault = false;
3072 unsigned DefaultIndex = 0;
3073
3074 // Check the each candidate function.
3075 for (unsigned Index = 0; Index < Options.size(); Index++) {
3076
3077 if (Options[Index].Features.empty()) {
3078 HasDefault = true;
3079 DefaultIndex = Index;
3080 continue;
3081 }
3082
3083 Builder.SetInsertPoint(CurBlock);
3084
3085 // FeaturesCondition: The bitmask of the required extension has been
3086 // enabled by the runtime object.
3087 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
3088 // REQUIRED_BITMASK
3089 //
3090 // When condition is met, return this version of the function.
3091 // Otherwise, try the next version.
3092 //
3093 // if (FeaturesConditionVersion1)
3094 // return Version1;
3095 // else if (FeaturesConditionVersion2)
3096 // return Version2;
3097 // else if (FeaturesConditionVersion3)
3098 // return Version3;
3099 // ...
3100 // else
3101 // return DefaultVersion;
3102
3103 // TODO: Add a condition to check the length before accessing elements.
3104 // Without checking the length first, we may access an incorrect memory
3105 // address when using different versions.
3106 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
3107 llvm::SmallVector<std::string, 8> TargetAttrFeats;
3108
3109 for (StringRef Feat : Options[Index].Features) {
3110 std::vector<std::string> FeatStr =
3112
3113 assert(FeatStr.size() == 1 && "Feature string not delimited");
3114
3115 std::string &CurrFeat = FeatStr.front();
3116 if (CurrFeat[0] == '+')
3117 TargetAttrFeats.push_back(CurrFeat.substr(1));
3118 }
3119
3120 if (TargetAttrFeats.empty())
3121 continue;
3122
3123 for (std::string &Feat : TargetAttrFeats)
3124 CurrTargetAttrFeats.push_back(Feat);
3125
3126 Builder.SetInsertPoint(CurBlock);
3127 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(CurrTargetAttrFeats);
3128
3129 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3130 CGBuilderTy RetBuilder(CGM, RetBlock);
3131 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder,
3132 Options[Index].Function, SupportsIFunc);
3133 llvm::BasicBlock *ElseBlock = createBasicBlock("resolver_else", Resolver);
3134
3135 Builder.SetInsertPoint(CurBlock);
3136 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
3137
3138 CurBlock = ElseBlock;
3139 }
3140
3141 // Finally, emit the default one.
3142 if (HasDefault) {
3143 Builder.SetInsertPoint(CurBlock);
3145 CGM, Resolver, Builder, Options[DefaultIndex].Function, SupportsIFunc);
3146 return;
3147 }
3148
3149 // If no generic/default, emit an unreachable.
3150 Builder.SetInsertPoint(CurBlock);
3152}
3153
3155 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3156 assert(!Options.empty() && "No multiversion resolver options found");
3157 assert(Options.back().Features.size() == 0 && "Default case must be last");
3158 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3159 assert(SupportsIFunc &&
3160 "Multiversion resolver requires target IFUNC support");
3161 bool AArch64CpuInitialized = false;
3162 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3163
3164 for (const FMVResolverOption &RO : Options) {
3165 Builder.SetInsertPoint(CurBlock);
3166 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3167
3168 // The 'default' or 'all features enabled' case.
3169 if (!Condition) {
3170 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3171 SupportsIFunc);
3172 return;
3173 }
3174
3175 if (!AArch64CpuInitialized) {
3176 Builder.SetInsertPoint(CurBlock, CurBlock->begin());
3177 EmitAArch64CpuInit();
3178 AArch64CpuInitialized = true;
3179 Builder.SetInsertPoint(CurBlock);
3180 }
3181
3182 // Skip unreachable versions.
3183 if (RO.Function == nullptr)
3184 continue;
3185
3186 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3187 CGBuilderTy RetBuilder(CGM, RetBlock);
3188 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3189 SupportsIFunc);
3190 CurBlock = createBasicBlock("resolver_else", Resolver);
3191 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3192 }
3193
3194 // If no default, emit an unreachable.
3195 Builder.SetInsertPoint(CurBlock);
3197}
3198
3200 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3201
3202 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3203
3204 // Main function's basic block.
3205 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3206 Builder.SetInsertPoint(CurBlock);
3207 EmitX86CpuInit();
3208
3209 for (const FMVResolverOption &RO : Options) {
3210 Builder.SetInsertPoint(CurBlock);
3211 llvm::Value *Condition = FormX86ResolverCondition(RO);
3212
3213 // The 'default' or 'generic' case.
3214 if (!Condition) {
3215 assert(&RO == Options.end() - 1 &&
3216 "Default or Generic case must be last");
3217 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3218 SupportsIFunc);
3219 return;
3220 }
3221
3222 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3223 CGBuilderTy RetBuilder(CGM, RetBlock);
3224 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3225 SupportsIFunc);
3226 CurBlock = createBasicBlock("resolver_else", Resolver);
3227 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3228 }
3229
3230 // If no generic/default, emit an unreachable.
3231 Builder.SetInsertPoint(CurBlock);
3233}
3234
3235// Loc - where the diagnostic will point, where in the source code this
3236// alignment has failed.
3237// SecondaryLoc - if present (will be present if sufficiently different from
3238// Loc), the diagnostic will additionally point a "Note:" to this location.
3239// It should be the location where the __attribute__((assume_aligned))
3240// was written e.g.
3242 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
3243 SourceLocation SecondaryLoc, llvm::Value *Alignment,
3244 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3245 llvm::Instruction *Assumption) {
3246 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3247 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3248 llvm::Intrinsic::getOrInsertDeclaration(
3249 Builder.GetInsertBlock()->getParent()->getParent(),
3250 llvm::Intrinsic::assume) &&
3251 "Assumption should be a call to llvm.assume().");
3252 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
3253 "Assumption should be the last instruction of the basic block, "
3254 "since the basic block is still being generated.");
3255
3256 if (!SanOpts.has(SanitizerKind::Alignment))
3257 return;
3258
3259 // Don't check pointers to volatile data. The behavior here is implementation-
3260 // defined.
3262 return;
3263
3264 // We need to temorairly remove the assumption so we can insert the
3265 // sanitizer check before it, else the check will be dropped by optimizations.
3266 Assumption->removeFromParent();
3267
3268 {
3269 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3270 auto CheckHandler = SanitizerHandler::AlignmentAssumption;
3271 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3272
3273 if (!OffsetValue)
3274 OffsetValue = Builder.getInt1(false); // no offset.
3275
3276 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3277 EmitCheckSourceLocation(SecondaryLoc),
3279 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3280 EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3281 StaticData, DynamicData);
3282 }
3283
3284 // We are now in the (new, empty) "cont" basic block.
3285 // Reintroduce the assumption.
3286 Builder.Insert(Assumption);
3287 // FIXME: Assumption still has it's original basic block as it's Parent.
3288}
3289
3291 if (CGDebugInfo *DI = getDebugInfo())
3292 return DI->SourceLocToDebugLoc(Location);
3293
3294 return llvm::DebugLoc();
3295}
3296
3297llvm::Value *
3298CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3299 Stmt::Likelihood LH) {
3300 switch (LH) {
3301 case Stmt::LH_None:
3302 return Cond;
3303 case Stmt::LH_Likely:
3304 case Stmt::LH_Unlikely:
3305 // Don't generate llvm.expect on -O0 as the backend won't use it for
3306 // anything.
3307 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3308 return Cond;
3309 llvm::Type *CondTy = Cond->getType();
3310 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3311 llvm::Function *FnExpect =
3312 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3313 llvm::Value *ExpectedValueOfCond =
3314 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3315 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3316 Cond->getName() + ".expval");
3317 }
3318 llvm_unreachable("Unknown Likelihood");
3319}
3320
3321llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3322 unsigned NumElementsDst,
3323 const llvm::Twine &Name) {
3324 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3325 unsigned NumElementsSrc = SrcTy->getNumElements();
3326 if (NumElementsSrc == NumElementsDst)
3327 return SrcVec;
3328
3329 std::vector<int> ShuffleMask(NumElementsDst, -1);
3330 for (unsigned MaskIdx = 0;
3331 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3332 ShuffleMask[MaskIdx] = MaskIdx;
3333
3334 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3335}
3336
3338 const CGPointerAuthInfo &PointerAuth,
3340 if (!PointerAuth.isSigned())
3341 return;
3342
3343 auto *Key = Builder.getInt32(PointerAuth.getKey());
3344
3345 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3346 if (!Discriminator)
3347 Discriminator = Builder.getSize(0);
3348
3349 llvm::Value *Args[] = {Key, Discriminator};
3350 Bundles.emplace_back("ptrauth", Args);
3351}
3352
3354 const CGPointerAuthInfo &PointerAuth,
3355 llvm::Value *Pointer,
3356 unsigned IntrinsicID) {
3357 if (!PointerAuth)
3358 return Pointer;
3359
3360 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3361
3362 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3363 if (!Discriminator) {
3364 Discriminator = CGF.Builder.getSize(0);
3365 }
3366
3367 // Convert the pointer to intptr_t before signing it.
3368 auto OrigType = Pointer->getType();
3369 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3370
3371 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3372 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3373 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3374
3375 // Convert back to the original type.
3376 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3377 return Pointer;
3378}
3379
3380llvm::Value *
3382 llvm::Value *Pointer) {
3383 if (!PointerAuth.shouldSign())
3384 return Pointer;
3385 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3386 llvm::Intrinsic::ptrauth_sign);
3387}
3388
3389static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3390 const CGPointerAuthInfo &PointerAuth,
3391 llvm::Value *Pointer) {
3392 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3393
3394 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3395 // Convert the pointer to intptr_t before signing it.
3396 auto OrigType = Pointer->getType();
3398 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3399 return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3400}
3401
3402llvm::Value *
3404 llvm::Value *Pointer) {
3405 if (PointerAuth.shouldStrip()) {
3406 return EmitStrip(*this, PointerAuth, Pointer);
3407 }
3408 if (!PointerAuth.shouldAuth()) {
3409 return Pointer;
3410 }
3411
3412 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3413 llvm::Intrinsic::ptrauth_auth);
3414}
3415
3417 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3418 if (CGDebugInfo *DI = getDebugInfo())
3419 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3420}
3421
3423 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3424 if (CGDebugInfo *DI = getDebugInfo())
3425 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3426}
3427
3428void CodeGenFunction::addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
3429 llvm::Value *Backup) {
3430 if (CGDebugInfo *DI = getDebugInfo()) {
3432 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3433 }
3434}
3435
3437 QualType Ty) {
3438 for (auto &Field : getContext().findPFPFields(Ty)) {
3439 if (getContext().arePFPFieldsTriviallyCopyable(Field.Field->getParent()))
3440 continue;
3441 auto DestFieldPtr = EmitAddressOfPFPField(DestPtr, Field);
3442 auto SrcFieldPtr = EmitAddressOfPFPField(SrcPtr, Field);
3443 Builder.CreateStore(Builder.CreateLoad(SrcFieldPtr), DestFieldPtr);
3444 }
3445}
static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset, std::vector< PFPField > &Fields, bool IncludeVBases)
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static llvm::Value * EmitPointerAuthCommon(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer, unsigned IntrinsicID)
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, llvm::Function *Resolver, CGBuilderTy &Builder, llvm::Function *FuncToReturn, bool SupportsIFunc)
static llvm::Value * EmitStrip(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer)
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, Address dest, Address src, llvm::Value *sizeInChars)
emitNonZeroVLAInit - Emit the "zero" initialization of a variable-length array whose elements have a ...
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
static LValue makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType, bool MightBeSigned, CodeGenFunction &CGF, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
static void TryMarkNoThrow(llvm::Function *F)
Tries to mark the given function nounwind based on the non-existence of any throwing calls within it.
static llvm::Constant * getPrologueSignature(CodeGenModule &CGM, const FunctionDecl *FD)
Return the UBSan prologue signature for FD if one is available.
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Result
Implement __builtin_bit_cast and related operations.
static StringRef getTriple(const Command &Job)
Defines the Objective-C statement AST node classes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool hasAnyFunctionEffects() const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
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.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:965
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3813
QualType getElementType() const
Definition TypeBase.h:3825
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4215
BinaryOperatorKind Opcode
Definition Expr.h:4087
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2726
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2292
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2859
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1027
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1792
bool isCapturelessLambda() const
Definition DeclCXX.h:1073
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1195
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
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
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
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
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const override
This forwards to CodeGenFunction::InsertHelper.
llvm::ConstantInt * getSize(CharUnits N)
Definition CGBuilder.h:109
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition CGCXXABI.h:158
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
Abstract information about a function or function prototype.
Definition CGCall.h:43
const FunctionProtoType * getCalleeFunctionProtoType() const
Definition CGCall.h:59
All available information about a concrete callee.
Definition CGCall.h:66
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:140
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
CGFunctionInfo - Class to encapsulate the information about a function definition.
llvm::Value * getDiscriminator() const
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:277
void add(RValue rvalue, QualType type)
Definition CGCall.h:305
CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures)
An object to manage conditionally-evaluated expressions.
An object which temporarily prevents a value from being destroyed by aggressive peephole optimization...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitRISCVMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
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.
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID, bool EnsureInsertPoint=true)
Emit a call to trap or debugtrap.
Definition CGExpr.cpp:4716
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitAArch64MultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
llvm::Value * EmitScalarOrConstFoldImmArg(unsigned ICEArguments, unsigned Idx, const CallExpr *E)
SanitizerSet SanOpts
Sanitizers enabled for this function.
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void EmitPPCAIXMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
define internal ptr @foo.resolver() { entry: is_version_1 = __builtin_cpu_supports(version_1) br i1 %...
bool ShouldSkipSanitizerInstrumentation()
ShouldSkipSanitizerInstrumentation - Return true if the current function should not be instrumented w...
llvm::Value * EmitPPCBuiltinCpu(unsigned BuiltinID, llvm::Type *ReturnType, StringRef CPUStr)
Definition PPC.cpp:73
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
llvm::Value * EmitRISCVCpuSupports(const CallExpr *E)
Definition RISCV.cpp:976
llvm::Value * EmitRISCVCpuInit()
Definition RISCV.cpp:966
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
Add KeyInstruction and an optional Backup instruction to a new atom group (See ApplyAtomGroup for mor...
PeepholeProtection protectFromPeepholes(RValue rvalue)
protectFromPeepholes - Protect a value that we're intending to store to the side, but which will prob...
void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD)
Definition CGClass.cpp:3086
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
Definition CGStmt.cpp:708
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
SmallVector< llvm::ConvergenceControlInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void unprotectFromPeepholes(PeepholeProtection protection)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:7394
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4151
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
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.
const LangOptions & getLangOpts() const
void addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom)
See CGDebugInfo::addInstToSpecificSourceAtom.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
Definition CGClass.cpp:781
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T)
Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known to be unsigned.
@ TCK_ConstructorCall
Checking the 'this' pointer for a constructor call.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
bool hasSkipCounter(const Stmt *S) const
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void EmitFunctionBody(const Stmt *Body)
JumpDest ReturnBlock
ReturnBlock - Unified return block.
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:4041
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:185
const TargetInfo & getTarget() const
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location, const AnnotateAttr *Attr)
Emit an annotation call (intrinsic).
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition CGStmt.cpp:583
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, std::initializer_list< llvm::Value ** > ValuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
void maybeCreateMCDCCondBitmap()
Allocate a temp value on the stack that MCDC can use to track condition results.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:261
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2539
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:192
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
llvm::Value * EmitPointerAuthSign(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
Annotate the function with an attribute that disables TSan checking at runtime.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:242
void EmitPointerAuthOperandBundle(const CGPointerAuthInfo &Info, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4299
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
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...
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
Definition CGClass.cpp:1413
void EmitX86MultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
bool ShouldInstrumentFunction()
ShouldInstrumentFunction - Return true if the current function should be instrumented with __cyg_prof...
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue, llvm::Value *TheCheck, llvm::Instruction *Assumption)
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5666
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount=0, Stmt::Likelihood LH=Stmt::LH_None, const Expr *CntrIdx=nullptr)
EmitBranchToCounterBlock - Emit a conditional branch to a new block that increments a profile counter...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
bool isMCDCBranchExpr(const Expr *E) const
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Definition CGCall.cpp:3473
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void SetFastMathFlags(FPOptions FPFeatures)
Set the codegen fast-math flags.
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
Address EmitVAListRef(const Expr *E)
void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD)
Definition CGClass.cpp:3143
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope,...
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
Definition CGStmt.cpp:58
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
uint64_t getCurrentProfileCount()
Get the profiler's current count.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Definition CGExpr.cpp:5850
void emitPFPPostCopyUpdates(Address DestPtr, Address SrcPtr, QualType Ty)
Copy all PFP fields from SrcPtr to DestPtr while updating signatures, assuming that DestPtr was alrea...
Address EmitZOSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_zos_va_list; this is always the address of the expression,...
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
Definition CGClass.cpp:1532
HLSLControlFlowHintAttr::Spelling HLSLControlFlowAttr
HLSL Branch attribute.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc, uint64_t RetKeyInstructionsSourceAtom)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
Definition CGCall.cpp:4370
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1618
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:674
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
llvm::BasicBlock * GetIndirectGotoBlock()
EHScopeStack::stable_iterator PrologueCleanupDepth
PrologueCleanupDepth - The cleanup depth enclosing all the cleanups associated with the parameters.
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
const FunctionDecl * getCurrentFunctionDecl() const
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCallAndMakeUnreachable()
Emit a call to '@llvm.trap()' and clear the current insert point.
Definition CGExpr.cpp:4742
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
const CGFunctionInfo * CurFnInfo
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
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:1734
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
bool checkIfFunctionMustProgress()
Returns true if a function must make progress, which means the mustprogress attribute can be added.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
bool isMCDCDecisionExpr(const Expr *E) const
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
void MaybeEmitDeferredVarDeclInit(const VarDecl *var)
Definition CGDecl.cpp:2096
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
When instrumenting to collect profile data, the counts for some blocks such as switch cases need to n...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:654
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
This class organizes the cross-function state that is used while generating LLVM code.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
Per-function PGO state.
Definition CodeGenPGO.h:29
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
Definition CGCall.cpp:411
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition CGValue.h:373
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:384
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information,...
Definition TargetInfo.h:274
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
ConditionalOperator - The ?
Definition Expr.h:4435
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
ValueDecl * getDecl()
Definition Expr.h:1358
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
bool hasAttr() const
Definition DeclBase.h:585
This represents one expression.
Definition Expr.h:113
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4025
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
ExtVectorType - Extended vector type.
Definition TypeBase.h:4358
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
Represents a function declaration or definition.
Definition Decl.h:2059
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3266
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:3040
bool usesSEHTry() const
Indicates the function uses __try.
Definition Decl.h:2645
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4303
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3269
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3417
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition Decl.cpp:3568
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2555
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3410
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4169
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5398
QualType desugar() const
Definition TypeBase.h:5979
FunctionTypeExtraAttributeInfo getExtraAttributeInfo() const
Return the extra attribute information.
Definition TypeBase.h:5887
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
CXXCtorType getCtorType() const
Definition GlobalDecl.h:117
KernelReferenceKind getKernelReferenceKind() const
Definition GlobalDecl.h:142
const Decl * getDecl() const
Definition GlobalDecl.h:115
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5667
Represents the declaration of a label.
Definition Decl.h:525
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
@ FPE_MayTrap
Transformations do not cause new exceptions but may hide some.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
RoundingMode getDefaultRoundingMode() const
Represents a parameter to a function.
Definition Decl.h:1820
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
@ Forbid
Profiling is forbidden using the noprofile attribute.
Definition ProfileList.h:37
@ Skip
Profiling is skipped using the skipprofile attribute.
Definition ProfileList.h:35
@ Allow
Profiling is allowed.
Definition ProfileList.h:33
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8512
field_range fields() const
Definition Decl.h:4663
Encodes a location in the source.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1505
Likelihood
The likelihood of a branch being taken.
Definition Stmt.h:1448
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
Definition Stmt.h:1449
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
Definition Stmt.h:1450
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1452
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts, ArmStreamingKind Mode, llvm::StringMap< bool > *FeatureMap=nullptr) const
Returns target-specific min and max values VScale_Range.
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool isVoidType() const
Definition TypeBase.h:9037
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2388
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
bool isObjCRetainableType() const
Definition Type.cpp:5591
bool isFunctionNoProtoType() const
Definition TypeBase.h:2664
bool isCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8711
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4057
Expr * getSizeExpr() const
Definition TypeBase.h:4071
QualType getElementType() const
Definition TypeBase.h:4280
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const CallExpr *E, const FunctionDecl *Caller, const FunctionDecl *TargetDecl)
Check that a call to a target-specific builtin has the required target features enabled in the caller...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
CGBuilderInserter CGBuilderInserterTy
Definition CGBuilder.h:47
constexpr XRayInstrMask Typed
Definition XRayInstr.h:42
constexpr XRayInstrMask FunctionExit
Definition XRayInstr.h:40
constexpr XRayInstrMask FunctionEntry
Definition XRayInstr.h:39
constexpr XRayInstrMask Custom
Definition XRayInstr.h:41
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreBuiltinExpectSingleStep(Expr *E)
Definition IgnoreExpr.h:135
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
Expr * IgnoreImplicitCastsSingleStep(Expr *E)
Definition IgnoreExpr.h:38
Expr * IgnoreUOpLNotSingleStep(Expr *E)
Definition IgnoreExpr.h:127
Expr * IgnoreParensSingleStep(Expr *E)
Definition IgnoreExpr.h:157
llvm::fp::ExceptionBehavior ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind)
U cast(CodeGen::Address addr)
Definition Address.h:327
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition Decl.cpp:6171
@ Other
Other implicit parameter.
Definition Decl.h:1775
@ EST_None
no exception specification
@ Implicit
An implicit conversion.
Definition Sema.h:434
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
This structure provides a set of types that are commonly used during IR emission.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5135
std::vector< std::string > Features
Definition TargetInfo.h:60
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174