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"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/StringExtras.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)
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 // Annotate C++ special member functions so that CopyProfPass can instrument
1057 // them, provided the object is at least as large as the size threshold.
1058 if (CGM.getCodeGenOpts().CopyProf) {
1059 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1060 StringRef Attr;
1061 if (const auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
1062 if (!CD->isMoveConstructor())
1063 Attr =
1064 CD->isCopyConstructor() ? "copyprof-copy-ctor" : "copyprof-ctor";
1065 } else if (isa<CXXDestructorDecl>(MD)) {
1066 Attr = "copyprof-dtor";
1067 } else if (MD->isCopyAssignmentOperator()) {
1068 Attr = "copyprof-copy-assign-op";
1069 }
1070 if (!Attr.empty()) {
1071 // Finally, add the object size in bytes to the annotation.
1072 // A special member function always has an implicit object parameter, so
1073 // its type is guaranteed to be complete here.
1076 if (ObjSize.getQuantity() >=
1077 CGM.getCodeGenOpts().CopyProfStaticSizeThreshold)
1078 Fn->addFnAttr(Attr, llvm::utostr(ObjSize.getQuantity()));
1079 }
1080 }
1081 }
1082
1083 // If we're in C++ mode and the function name is "main", it is guaranteed
1084 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1085 // used within a program").
1086 //
1087 // OpenCL C 2.0 v2.2-11 s6.9.i:
1088 // Recursion is not supported.
1089 //
1090 // HLSL
1091 // Recursion is not supported.
1092 //
1093 // SYCL v1.2.1 s3.10:
1094 // kernels cannot include RTTI information, exception classes,
1095 // recursive code, virtual functions or make use of C++ libraries that
1096 // are not compiled for the device.
1097 if (FD &&
1098 ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
1099 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
1100 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1101 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1102
1103 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1104 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1105 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1106 Builder.setDefaultConstrainedRounding(RM);
1107 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1108 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1109 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1110 RM != llvm::RoundingMode::NearestTiesToEven))) {
1111 Builder.setIsFPConstrained(true);
1112 Fn->addFnAttr(llvm::Attribute::StrictFP);
1113 }
1114
1115 // If a custom alignment is used, force realigning to this alignment on
1116 // any main function which certainly will need it.
1117 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1118 CGM.getCodeGenOpts().StackAlignment))
1119 Fn->addFnAttr("stackrealign");
1120
1121 // "main" doesn't need to zero out call-used registers.
1122 if (FD && FD->isMain())
1123 Fn->removeFnAttr("zero-call-used-regs");
1124
1125 // Add vscale_range attribute if appropriate.
1126 llvm::StringMap<bool> FeatureMap;
1127 auto IsArmStreaming = TargetInfo::ArmStreamingKind::NotStreaming;
1128 if (FD) {
1129 getContext().getFunctionFeatureMap(FeatureMap, FD);
1130 if (const auto *T = FD->getType()->getAs<FunctionProtoType>())
1131 if (T->getAArch64SMEAttributes() &
1134
1135 if (IsArmStreamingFunction(FD, true))
1137 }
1138 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
1139 getContext().getTargetInfo().getVScaleRange(getLangOpts(), IsArmStreaming,
1140 &FeatureMap);
1141 if (VScaleRange) {
1142 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1143 getLLVMContext(), VScaleRange->first, VScaleRange->second));
1144 }
1145
1146 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1147
1148 // Create a marker to make it easy to insert allocas into the entryblock
1149 // later. Don't create this with the builder, because we don't want it
1150 // folded.
1151 llvm::Value *Poison = llvm::PoisonValue::get(Int32Ty);
1152 AllocaInsertPt = new llvm::BitCastInst(Poison, Int32Ty, "allocapt", EntryBB);
1153
1155
1156 Builder.SetInsertPoint(EntryBB);
1157
1158 // If we're checking the return value, allocate space for a pointer to a
1159 // precise source location of the checked return statement.
1160 if (requiresReturnValueCheck()) {
1161 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1162 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1163 ReturnLocation);
1164 }
1165
1166 // Emit subprogram debug descriptor.
1167 if (CGDebugInfo *DI = getDebugInfo()) {
1168 // Reconstruct the type from the argument list so that implicit parameters,
1169 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1170 // convention.
1171 DI->emitFunctionStart(GD, Loc, StartLoc,
1172 DI->getFunctionType(FD, RetTy, Args), CurFn,
1174 }
1175
1177 if (CGM.getCodeGenOpts().InstrumentFunctions)
1178 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1179 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1180 CurFn->addFnAttr("instrument-function-entry-inlined",
1181 "__cyg_profile_func_enter");
1182 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1183 CurFn->addFnAttr("instrument-function-entry-inlined",
1184 "__cyg_profile_func_enter_bare");
1185 }
1186
1187 // Since emitting the mcount call here impacts optimizations such as function
1188 // inlining, we just add an attribute to insert a mcount call in backend.
1189 // The attribute "counting-function" is set to mcount function name which is
1190 // architecture dependent.
1191 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1192 // Calls to fentry/mcount should not be generated if function has
1193 // the no_instrument_function attribute.
1194 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1195 if (CGM.getCodeGenOpts().CallFEntry)
1196 Fn->addFnAttr("fentry-call", "true");
1197 else {
1198 Fn->addFnAttr("instrument-function-entry-inlined",
1199 getTarget().getMCountName());
1200 }
1201 if (CGM.getCodeGenOpts().MNopMCount) {
1202 if (!CGM.getCodeGenOpts().CallFEntry)
1203 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1204 << "-mnop-mcount" << "-mfentry";
1205 Fn->addFnAttr("mnop-mcount");
1206 }
1207
1208 if (CGM.getCodeGenOpts().RecordMCount) {
1209 if (!CGM.getCodeGenOpts().CallFEntry)
1210 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1211 << "-mrecord-mcount" << "-mfentry";
1212 Fn->addFnAttr("mrecord-mcount");
1213 }
1214 }
1215 }
1216
1217 if (CGM.getCodeGenOpts().PackedStack) {
1218 if (getContext().getTargetInfo().getTriple().getArch() !=
1219 llvm::Triple::systemz)
1220 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1221 << "-mpacked-stack";
1222 Fn->addFnAttr("packed-stack");
1223 }
1224
1225 if (!CGM.getCodeGenOpts().ZOSPPA1Name)
1226 Fn->addFnAttr("zos-ppa1-name", "");
1227 else if (getContext().getTargetInfo().getTriple().isOSzOS() && FD &&
1228 FD->hasAttr<AsmLabelAttr>()) {
1229 std::string SrcName = CGM.getMangledNameIgnoringAsmLabel(GD, FD);
1230 Fn->addFnAttr("zos-ppa1-name", SrcName);
1231 }
1232
1233 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1234 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1235 Fn->addFnAttr("warn-stack-size",
1236 std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1237
1238 if (RetTy->isVoidType()) {
1239 // Void type; nothing to return.
1241
1242 // Count the implicit return.
1243 if (!endsWithReturn(D))
1244 ++NumReturnExprs;
1245 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1246 // Indirect return; emit returned value directly into sret slot.
1247 // This reduces code size, and affects correctness in C++.
1248 auto AI = CurFn->arg_begin();
1249 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1250 ++AI;
1252 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1253 nullptr, nullptr, KnownNonNull);
1254 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1256 CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
1257 Builder.CreateStore(ReturnValue.emitRawPointer(*this),
1259 }
1260 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1261 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1262 // Load the sret pointer from the argument struct and return into that.
1263 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1264 llvm::Function::arg_iterator EI = CurFn->arg_end();
1265 --EI;
1266 llvm::Value *Addr = Builder.CreateStructGEP(
1267 CurFnInfo->getArgStruct(), &*EI, Idx);
1268 llvm::Type *Ty =
1269 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1271 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1273 CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
1274 } else {
1275 ReturnValue = CreateIRTempWithoutCast(RetTy, "retval");
1276
1277 // Tell the epilog emitter to autorelease the result. We do this
1278 // now so that various specialized functions can suppress it
1279 // during their IR-generation.
1280 if (getLangOpts().ObjCAutoRefCount &&
1281 !CurFnInfo->isReturnsRetained() &&
1282 RetTy->isObjCRetainableType())
1283 AutoreleaseResult = true;
1284 }
1285
1287
1288 PrologueCleanupDepth = EHStack.stable_begin();
1289
1290 // Emit OpenMP specific initialization of the device functions.
1291 if (getLangOpts().OpenMP && CurCodeDecl)
1292 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1293
1294 if (FD && getLangOpts().HLSL) {
1295 // Handle emitting HLSL entry functions.
1296 if (FD->hasAttr<HLSLShaderAttr>()) {
1297 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1298 }
1299 }
1300
1302
1303 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1304 MD && !MD->isStatic()) {
1305 bool IsInLambda =
1306 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1308 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1309 if (IsInLambda) {
1310 // We're in a lambda; figure out the captures.
1314 // If the lambda captures the object referred to by '*this' - either by
1315 // value or by reference, make sure CXXThisValue points to the correct
1316 // object.
1317
1318 // Get the lvalue for the field (which is a copy of the enclosing object
1319 // or contains the address of the enclosing object).
1321 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1322 // If the enclosing object was captured by value, just use its
1323 // address. Sign this pointer.
1324 CXXThisValue = ThisFieldLValue.getPointer(*this);
1325 } else {
1326 // Load the lvalue pointed to by the field, since '*this' was captured
1327 // by reference.
1328 CXXThisValue =
1329 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1330 }
1331 }
1332 for (auto *FD : MD->getParent()->fields()) {
1333 if (FD->hasCapturedVLAType()) {
1334 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1336 auto VAT = FD->getCapturedVLAType();
1337 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1338 }
1339 }
1340 } else if (MD->isImplicitObjectMemberFunction()) {
1341 // Not in a lambda; just use 'this' from the method.
1342 // FIXME: Should we generate a new load for each use of 'this'? The
1343 // fast register allocator would be happier...
1344 CXXThisValue = CXXABIThisValue;
1345 }
1346
1347 // Check the 'this' pointer once per function, if it's available.
1348 if (CXXABIThisValue) {
1349 SanitizerSet SkippedChecks;
1350 SkippedChecks.set(SanitizerKind::ObjectSize, true);
1351 QualType ThisTy = MD->getThisType();
1352
1353 // If this is the call operator of a lambda with no captures, it
1354 // may have a static invoker function, which may call this operator with
1355 // a null 'this' pointer.
1357 SkippedChecks.set(SanitizerKind::Null, true);
1358
1361 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1362 }
1363 }
1364
1365 // If any of the arguments have a variably modified type, make sure to
1366 // emit the type size, but only if the function is not naked. Naked functions
1367 // have no prolog to run this evaluation.
1368 if (!FD || !FD->hasAttr<NakedAttr>()) {
1369 for (const VarDecl *VD : Args) {
1370 // Dig out the type as written from ParmVarDecls; it's unclear whether
1371 // the standard (C99 6.9.1p10) requires this, but we're following the
1372 // precedent set by gcc.
1373 QualType Ty;
1374 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1375 Ty = PVD->getOriginalType();
1376 else
1377 Ty = VD->getType();
1378
1379 if (Ty->isVariablyModifiedType())
1381 }
1382 }
1383 // Emit a location at the end of the prologue.
1384 if (CGDebugInfo *DI = getDebugInfo())
1385 DI->EmitLocation(Builder, StartLoc);
1386 // TODO: Do we need to handle this in two places like we do with
1387 // target-features/target-cpu?
1388 if (CurFuncDecl)
1389 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1390 LargestVectorWidth = VecWidth->getVectorWidth();
1391
1392 if (CGM.shouldEmitConvergenceTokens())
1393 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1394}
1395
1399 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1401 else
1402 EmitStmt(Body);
1403}
1404
1405/// When instrumenting to collect profile data, the counts for some blocks
1406/// such as switch cases need to not include the fall-through counts, so
1407/// emit a branch around the instrumentation code. When not instrumenting,
1408/// this just calls EmitBlock().
1410 const Stmt *S) {
1411 llvm::BasicBlock *SkipCountBB = nullptr;
1412 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1413 // When instrumenting for profiling, the fallthrough to certain
1414 // statements needs to skip over the instrumentation code so that we
1415 // get an accurate count.
1416 SkipCountBB = createBasicBlock("skipcount");
1417 EmitBranch(SkipCountBB);
1418 }
1419 EmitBlock(BB);
1420 uint64_t CurrentCount = getCurrentProfileCount();
1423 if (SkipCountBB)
1424 EmitBlock(SkipCountBB);
1425}
1426
1427/// Tries to mark the given function nounwind based on the
1428/// non-existence of any throwing calls within it. We believe this is
1429/// lightweight enough to do at -O0.
1430static void TryMarkNoThrow(llvm::Function *F) {
1431 // LLVM treats 'nounwind' on a function as part of the type, so we
1432 // can't do this on functions that can be overwritten.
1433 if (F->isInterposable()) return;
1434
1435 for (llvm::BasicBlock &BB : *F)
1436 for (llvm::Instruction &I : BB)
1437 if (I.mayThrow())
1438 return;
1439
1440 F->setDoesNotThrow();
1441}
1442
1444 FunctionArgList &Args) {
1445 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1446 QualType ResTy = FD->getReturnType();
1447
1448 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1449 if (MD && MD->isImplicitObjectMemberFunction()) {
1450 if (CGM.getCXXABI().HasThisReturn(GD))
1451 ResTy = MD->getThisType();
1452 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1453 ResTy = CGM.getContext().VoidPtrTy;
1454 CGM.getCXXABI().buildThisParam(*this, Args);
1455 }
1456
1457 // The base version of an inheriting constructor whose constructed base is a
1458 // virtual base is not passed any arguments (because it doesn't actually call
1459 // the inherited constructor).
1460 bool PassedParams = true;
1461 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1462 if (auto Inherited = CD->getInheritedConstructor())
1463 PassedParams =
1464 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1465
1466 if (PassedParams) {
1467 for (auto *Param : FD->parameters()) {
1468 Args.push_back(Param);
1469 if (!Param->hasAttr<PassObjectSizeAttr>())
1470 continue;
1471
1473 getContext(), Param->getDeclContext(), Param->getLocation(),
1474 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1475 SizeArguments[Param] = Implicit;
1476 Args.push_back(Implicit);
1477 }
1478 }
1479
1480 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1481 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1482
1483 return ResTy;
1484}
1485
1486void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1487 const CGFunctionInfo &FnInfo) {
1488 assert(Fn && "generating code for null Function");
1489 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1490 CurGD = GD;
1491
1492 FunctionArgList Args;
1493 QualType ResTy = BuildFunctionArgList(GD, Args);
1494
1495 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
1496
1497 if (FD->isInlineBuiltinDeclaration()) {
1498 // When generating code for a builtin with an inline declaration, use a
1499 // mangled name to hold the actual body, while keeping an external
1500 // definition in case the function pointer is referenced somewhere.
1501 std::string FDInlineName = (Fn->getName() + ".inline").str();
1502 llvm::Module *M = Fn->getParent();
1503 llvm::Function *Clone = M->getFunction(FDInlineName);
1504 if (!Clone) {
1505 Clone = llvm::Function::Create(Fn->getFunctionType(),
1506 llvm::GlobalValue::InternalLinkage,
1507 Fn->getAddressSpace(), FDInlineName, M);
1508 Clone->setCallingConv(Fn->getCallingConv());
1509 Clone->setAttributes(Fn->getAttributes());
1510 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1511 }
1512 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1513 Fn = Clone;
1514 } else {
1515 // Detect the unusual situation where an inline version is shadowed by a
1516 // non-inline version. In that case we should pick the external one
1517 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1518 // to detect that situation before we reach codegen, so do some late
1519 // replacement.
1520 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1521 PD = PD->getPreviousDecl()) {
1522 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1523 std::string FDInlineName = (Fn->getName() + ".inline").str();
1524 llvm::Module *M = Fn->getParent();
1525 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1526 Clone->replaceAllUsesWith(Fn);
1527 Clone->eraseFromParent();
1528 }
1529 break;
1530 }
1531 }
1532 }
1533
1534 // Check if we should generate debug info for this function.
1535 if (FD->hasAttr<NoDebugAttr>()) {
1536 // Clear non-distinct debug info that was possibly attached to the function
1537 // due to an earlier declaration without the nodebug attribute
1538 Fn->setSubprogram(nullptr);
1539 // Disable debug info indefinitely for this function
1540 DebugInfo = nullptr;
1541 }
1542 // Finalize function debug info on exit.
1543 llvm::scope_exit Cleanup([this] {
1544 if (CGDebugInfo *DI = getDebugInfo())
1545 DI->completeFunction();
1546 });
1547
1548 // The function might not have a body if we're generating thunks for a
1549 // function declaration.
1550 SourceRange BodyRange;
1551 if (Stmt *Body = FD->getBody())
1552 BodyRange = Body->getSourceRange();
1553 else
1554 BodyRange = FD->getLocation();
1555 CurEHLocation = BodyRange.getEnd();
1556
1557 // Use the location of the start of the function to determine where
1558 // the function definition is located. By default use the location
1559 // of the declaration as the location for the subprogram. A function
1560 // may lack a declaration in the source code if it is created by code
1561 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1562 SourceLocation Loc = FD->getLocation();
1563
1564 // If this is a function specialization then use the pattern body
1565 // as the location for the function.
1566 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1567 if (SpecDecl->hasBody(SpecDecl))
1568 Loc = SpecDecl->getLocation();
1569
1570 Stmt *Body = FD->getBody();
1571
1572 if (Body) {
1573 // Coroutines always emit lifetime markers.
1574 if (isa<CoroutineBodyStmt>(Body))
1575 ShouldEmitLifetimeMarkers = true;
1576
1577 // Detect jumps that invalidate lifetime markers or bypass auto-var-init.
1578 bool NeedsBypassDetection =
1579 ShouldEmitLifetimeMarkers ||
1580 (CGM.getLangOpts().getTrivialAutoVarInit() !=
1582 if (NeedsBypassDetection)
1583 Bypasses.Init(CGM, Body);
1584 }
1585
1586 // Emit the standard function prologue.
1587 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1588
1589 // Save parameters for coroutine function.
1590 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1591 llvm::append_range(FnArgs, FD->parameters());
1592
1593 // Ensure that the function adheres to the forward progress guarantee, which
1594 // is required by certain optimizations.
1595 // In C++11 and up, the attribute will be removed if the body contains a
1596 // trivial empty loop.
1598 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1599
1600 // Generate the body of the function.
1601 PGO->assignRegionCounters(GD, CurFn);
1602 if (isa<CXXDestructorDecl>(FD))
1603 EmitDestructorBody(Args);
1604 else if (isa<CXXConstructorDecl>(FD))
1605 EmitConstructorBody(Args);
1606 else if (getLangOpts().CUDA &&
1607 !getLangOpts().CUDAIsDevice &&
1608 FD->hasAttr<CUDAGlobalAttr>())
1609 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1610 else if (isa<CXXMethodDecl>(FD) &&
1611 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1612 // The lambda static invoker function is special, because it forwards or
1613 // clones the body of the function call operator (but is actually static).
1615 } else if (isa<CXXMethodDecl>(FD) &&
1617 !FnInfo.isDelegateCall() &&
1618 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1619 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1620 // If emitting a lambda with static invoker on X86 Windows, change
1621 // the call operator body.
1622 // Make sure that this is a call operator with an inalloca arg and check
1623 // for delegate call to make sure this is the original call op and not the
1624 // new forwarding function for the static invoker.
1626 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1627 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1628 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1629 // Implicit copy-assignment gets the same special treatment as implicit
1630 // copy-constructors.
1632 } else if (DeviceKernelAttr::isOpenCLSpelling(
1633 FD->getAttr<DeviceKernelAttr>()) &&
1635 CallArgList CallArgs;
1636 for (unsigned i = 0; i < Args.size(); ++i) {
1637 Address ArgAddr = GetAddrOfLocalVar(Args[i]);
1638 QualType ArgQualType = Args[i]->getType();
1639 RValue ArgRValue = convertTempToRValue(ArgAddr, ArgQualType, Loc);
1640 CallArgs.add(ArgRValue, ArgQualType);
1641 }
1643 const FunctionType *FT = cast<FunctionType>(FD->getType());
1644 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1645 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
1646 CallArgs, FT, /*ChainCall=*/false, getCurrentFunctionDecl());
1647 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FnInfo);
1648 llvm::Constant *GDStubFunctionPointer =
1649 CGM.getRawFunctionPointer(GDStub, FTy);
1650 CGCallee GDStubCallee = CGCallee::forDirect(GDStubFunctionPointer, GDStub);
1651 EmitCall(FnInfo, GDStubCallee, ReturnValueSlot(), CallArgs, nullptr, false,
1652 Loc);
1653 } else if (Body) {
1654 EmitFunctionBody(Body);
1655 } else
1656 llvm_unreachable("no definition for emitted function");
1657
1658 // C++11 [stmt.return]p2:
1659 // Flowing off the end of a function [...] results in undefined behavior in
1660 // a value-returning function.
1661 // C11 6.9.1p12:
1662 // If the '}' that terminates a function is reached, and the value of the
1663 // function call is used by the caller, the behavior is undefined.
1665 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1666 bool ShouldEmitUnreachable =
1667 CGM.getCodeGenOpts().StrictReturn ||
1668 !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1669 if (SanOpts.has(SanitizerKind::Return)) {
1670 auto CheckOrdinal = SanitizerKind::SO_Return;
1671 auto CheckHandler = SanitizerHandler::MissingReturn;
1672 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
1673 llvm::Value *IsFalse = Builder.getFalse();
1674 EmitCheck(std::make_pair(IsFalse, CheckOrdinal), CheckHandler,
1676 } else if (ShouldEmitUnreachable) {
1677 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1678 EmitTrapCall(llvm::Intrinsic::trap);
1679 }
1680 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1681 Builder.CreateUnreachable();
1682 Builder.ClearInsertionPoint();
1683 }
1684 }
1685
1686 // Emit the standard function epilogue.
1687 FinishFunction(BodyRange.getEnd());
1688
1689 PGO->verifyCounterMap();
1690
1691 if (CurCodeDecl->hasAttr<PersonalityAttr>()) {
1692 StringRef Identifier =
1693 CurCodeDecl->getAttr<PersonalityAttr>()->getRoutine()->getName();
1694 llvm::FunctionCallee PersonalityRoutine =
1695 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
1696 Identifier, {}, /*local=*/true);
1697 Fn->setPersonalityFn(cast<llvm::Constant>(PersonalityRoutine.getCallee()));
1698 }
1699
1700 // If we haven't marked the function nothrow through other means, do
1701 // a quick pass now to see if we can.
1702 if (!CurFn->doesNotThrow())
1704}
1705
1706/// ContainsLabel - Return true if the statement contains a label in it. If
1707/// this statement is not executed normally, it not containing a label means
1708/// that we can just remove the code.
1709bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1710 // Null statement, not a label!
1711 if (!S) return false;
1712
1713 // If this is a label, we have to emit the code, consider something like:
1714 // if (0) { ... foo: bar(); } goto foo;
1715 //
1716 // TODO: If anyone cared, we could track __label__'s, since we know that you
1717 // can't jump to one from outside their declared region.
1718 if (isa<LabelStmt>(S))
1719 return true;
1720
1721 // If this is a case/default statement, and we haven't seen a switch, we have
1722 // to emit the code.
1723 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1724 return true;
1725
1726 // If this is a switch statement, we want to ignore cases below it.
1727 if (isa<SwitchStmt>(S))
1728 IgnoreCaseStmts = true;
1729
1730 // Scan subexpressions for verboten labels.
1731 for (const Stmt *SubStmt : S->children())
1732 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1733 return true;
1734
1735 return false;
1736}
1737
1738/// containsBreak - Return true if the statement contains a break out of it.
1739/// If the statement (recursively) contains a switch or loop with a break
1740/// inside of it, this is fine.
1742 // Null statement, not a label!
1743 if (!S) return false;
1744
1745 // If this is a switch or loop that defines its own break scope, then we can
1746 // include it and anything inside of it.
1747 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1748 isa<ForStmt>(S))
1749 return false;
1750
1751 if (isa<BreakStmt>(S))
1752 return true;
1753
1754 // Scan subexpressions for verboten breaks.
1755 for (const Stmt *SubStmt : S->children())
1756 if (containsBreak(SubStmt))
1757 return true;
1758
1759 return false;
1760}
1761
1763 if (!S) return false;
1764
1765 // Some statement kinds add a scope and thus never add a decl to the current
1766 // scope. Note, this list is longer than the list of statements that might
1767 // have an unscoped decl nested within them, but this way is conservatively
1768 // correct even if more statement kinds are added.
1769 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1773 return false;
1774
1775 if (isa<DeclStmt>(S))
1776 return true;
1777
1778 for (const Stmt *SubStmt : S->children())
1779 if (mightAddDeclToScope(SubStmt))
1780 return true;
1781
1782 return false;
1783}
1784
1785/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1786/// to a constant, or if it does but contains a label, return false. If it
1787/// constant folds return true and set the boolean result in Result.
1789 bool &ResultBool,
1790 bool AllowLabels) {
1791 // If MC/DC is enabled, disable folding so that we can instrument all
1792 // conditions to yield complete test vectors. We still keep track of
1793 // folded conditions during region mapping and visualization.
1794 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1795 CGM.getCodeGenOpts().MCDCCoverage)
1796 return false;
1797
1798 llvm::APSInt ResultInt;
1799 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1800 return false;
1801
1802 ResultBool = ResultInt.getBoolValue();
1803 return true;
1804}
1805
1806/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1807/// to a constant, or if it does but contains a label, return false. If it
1808/// constant folds return true and set the folded value.
1810 llvm::APSInt &ResultInt,
1811 bool AllowLabels) {
1812 // FIXME: Rename and handle conversion of other evaluatable things
1813 // to bool.
1815 if (!Cond->EvaluateAsInt(Result, getContext()))
1816 return false; // Not foldable, not integer or not fully evaluatable.
1817
1818 llvm::APSInt Int = Result.Val.getInt();
1819 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1820 return false; // Contains a label.
1821
1822 PGO->markStmtMaybeUsed(Cond);
1823 ResultInt = std::move(Int);
1824 return true;
1825}
1826
1827/// Strip parentheses and simplistic logical-NOT operators.
1829 while (true) {
1830 const Expr *SC = IgnoreExprNodes(
1833 if (C == SC)
1834 return SC;
1835 C = SC;
1836 }
1837}
1838
1839/// Determine whether the given condition is an instrumentable condition
1840/// (i.e. no "&&" or "||").
1842 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1843 return (!BOp || !BOp->isLogicalOp());
1844}
1845
1846/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1847/// increments a profile counter based on the semantics of the given logical
1848/// operator opcode. This is used to instrument branch condition coverage for
1849/// logical operators.
1851 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1852 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1853 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1854 // If not instrumenting, just emit a branch.
1855 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1856 if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1857 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1858
1859 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1860
1861 llvm::BasicBlock *ThenBlock = nullptr;
1862 llvm::BasicBlock *ElseBlock = nullptr;
1863 llvm::BasicBlock *NextBlock = nullptr;
1864
1865 // Create the block we'll use to increment the appropriate counter.
1866 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1867
1868 llvm::BasicBlock *SkipIncrBlock =
1869 (hasSkipCounter(CntrStmt) ? createBasicBlock("lop.rhsskip") : nullptr);
1870 llvm::BasicBlock *SkipNextBlock = nullptr;
1871
1872 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1873 // means we need to evaluate the condition and increment the counter on TRUE:
1874 //
1875 // if (Cond)
1876 // goto CounterIncrBlock;
1877 // else
1878 // goto FalseBlock;
1879 //
1880 // CounterIncrBlock:
1881 // Counter++;
1882 // goto TrueBlock;
1883
1884 if (LOp == BO_LAnd) {
1885 SkipNextBlock = FalseBlock;
1886 ThenBlock = CounterIncrBlock;
1887 ElseBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1888 NextBlock = TrueBlock;
1889 }
1890
1891 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1892 // we need to evaluate the condition and increment the counter on FALSE:
1893 //
1894 // if (Cond)
1895 // goto TrueBlock;
1896 // else
1897 // goto CounterIncrBlock;
1898 //
1899 // CounterIncrBlock:
1900 // Counter++;
1901 // goto FalseBlock;
1902
1903 else if (LOp == BO_LOr) {
1904 SkipNextBlock = TrueBlock;
1905 ThenBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1906 ElseBlock = CounterIncrBlock;
1907 NextBlock = FalseBlock;
1908 } else {
1909 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1910 }
1911
1912 // Emit Branch based on condition.
1913 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1914
1915 if (SkipIncrBlock) {
1916 EmitBlock(SkipIncrBlock);
1918 EmitBranch(SkipNextBlock);
1919 }
1920
1921 // Emit the block containing the counter increment(s).
1922 EmitBlock(CounterIncrBlock);
1923
1924 // Increment corresponding counter; if index not provided, use Cond as index.
1926
1927 // Go to the next block.
1928 EmitBranch(NextBlock);
1929}
1930
1931/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1932/// statement) to the specified blocks. Based on the condition, this might try
1933/// to simplify the codegen of the conditional based on the branch.
1934/// \param LH The value of the likelihood attribute on the True branch.
1935/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1936/// ConditionalOperator (ternary) through a recursive call for the operator's
1937/// LHS and RHS nodes.
1939 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1940 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp,
1941 const VarDecl *ConditionalDecl) {
1942 Cond = Cond->IgnoreParens();
1943
1944 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1945 bool HasSkip = hasSkipCounter(CondBOp);
1946
1947 // Handle X && Y in a condition.
1948 if (CondBOp->getOpcode() == BO_LAnd) {
1949 // If we have "1 && X", simplify the code. "0 && X" would have constant
1950 // folded if the case was simple enough.
1951 bool ConstantBool = false;
1952 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1953 ConstantBool) {
1954 // br(1 && X) -> br(X).
1955 incrementProfileCounter(CondBOp);
1956 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1957 FalseBlock, TrueCount, LH);
1958 return;
1959 }
1960
1961 // If we have "X && 1", simplify the code to use an uncond branch.
1962 // "X && 0" would have been constant folded to 0.
1963 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1964 ConstantBool) {
1965 // br(X && 1) -> br(X).
1966 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1967 FalseBlock, TrueCount, LH, CondBOp);
1968 return;
1969 }
1970
1971 // Emit the LHS as a conditional. If the LHS conditional is false, we
1972 // want to jump to the FalseBlock.
1973 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1974 llvm::BasicBlock *LHSFalse =
1975 (HasSkip ? createBasicBlock("land.lhsskip") : FalseBlock);
1976 // The counter tells us how often we evaluate RHS, and all of TrueCount
1977 // can be propagated to that branch.
1978 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1979
1980 ConditionalEvaluation eval(*this);
1981 {
1982 ApplyDebugLocation DL(*this, Cond);
1983 // Propagate the likelihood attribute like __builtin_expect
1984 // __builtin_expect(X && Y, 1) -> X and Y are likely
1985 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1986 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, LHSFalse, RHSCount,
1987 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1988 if (HasSkip) {
1989 EmitBlock(LHSFalse);
1991 EmitBranch(FalseBlock);
1992 }
1993 EmitBlock(LHSTrue);
1994 }
1995
1997 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1998
1999 // Any temporaries created here are conditional.
2000 eval.begin(*this);
2001 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
2002 FalseBlock, TrueCount, LH);
2003 eval.end(*this);
2004 return;
2005 }
2006
2007 if (CondBOp->getOpcode() == BO_LOr) {
2008 // If we have "0 || X", simplify the code. "1 || X" would have constant
2009 // folded if the case was simple enough.
2010 bool ConstantBool = false;
2011 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
2012 !ConstantBool) {
2013 // br(0 || X) -> br(X).
2014 incrementProfileCounter(CondBOp);
2015 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
2016 FalseBlock, TrueCount, LH);
2017 return;
2018 }
2019
2020 // If we have "X || 0", simplify the code to use an uncond branch.
2021 // "X || 1" would have been constant folded to 1.
2022 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
2023 !ConstantBool) {
2024 // br(X || 0) -> br(X).
2025 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
2026 FalseBlock, TrueCount, LH, CondBOp);
2027 return;
2028 }
2029 // Emit the LHS as a conditional. If the LHS conditional is true, we
2030 // want to jump to the TrueBlock.
2031 llvm::BasicBlock *LHSTrue =
2032 (HasSkip ? createBasicBlock("lor.lhsskip") : TrueBlock);
2033 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
2034 // We have the count for entry to the RHS and for the whole expression
2035 // being true, so we can divy up True count between the short circuit and
2036 // the RHS.
2037 uint64_t LHSCount =
2038 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
2039 uint64_t RHSCount = TrueCount - LHSCount;
2040
2041 ConditionalEvaluation eval(*this);
2042 {
2043 // Propagate the likelihood attribute like __builtin_expect
2044 // __builtin_expect(X || Y, 1) -> only Y is likely
2045 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
2046 ApplyDebugLocation DL(*this, Cond);
2047 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, LHSFalse, LHSCount,
2048 LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
2049 if (HasSkip) {
2050 EmitBlock(LHSTrue);
2052 EmitBranch(TrueBlock);
2053 }
2054 EmitBlock(LHSFalse);
2055 }
2056
2058 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
2059
2060 // Any temporaries created here are conditional.
2061 eval.begin(*this);
2062 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
2063 RHSCount, LH);
2064
2065 eval.end(*this);
2066 return;
2067 }
2068 }
2069
2070 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
2071 // br(!x, t, f) -> br(x, f, t)
2072 // Avoid doing this optimization when instrumenting a condition for MC/DC.
2073 // LNot is taken as part of the condition for simplicity, and changing its
2074 // sense negatively impacts test vector tracking.
2075 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
2076 CGM.getCodeGenOpts().MCDCCoverage &&
2078 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2079 // Negate the count.
2080 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
2081 // The values of the enum are chosen to make this negation possible.
2082 LH = static_cast<Stmt::Likelihood>(-LH);
2083 // Negate the condition and swap the destination blocks.
2084 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
2085 FalseCount, LH);
2086 }
2087 }
2088
2089 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
2090 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
2091 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
2092 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
2093
2094 // The ConditionalOperator itself has no likelihood information for its
2095 // true and false branches. This matches the behavior of __builtin_expect.
2096 ConditionalEvaluation cond(*this);
2097 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
2099
2100 // When computing PGO branch weights, we only know the overall count for
2101 // the true block. This code is essentially doing tail duplication of the
2102 // naive code-gen, introducing new edges for which counts are not
2103 // available. Divide the counts proportionally between the LHS and RHS of
2104 // the conditional operator.
2105 uint64_t LHSScaledTrueCount = 0;
2106 if (TrueCount) {
2107 double LHSRatio =
2108 getProfileCount(CondOp) / (double)getCurrentProfileCount();
2109 LHSScaledTrueCount = TrueCount * LHSRatio;
2110 }
2111
2112 cond.begin(*this);
2113 EmitBlock(LHSBlock);
2115 {
2116 ApplyDebugLocation DL(*this, Cond);
2117 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
2118 LHSScaledTrueCount, LH, CondOp);
2119 }
2120 cond.end(*this);
2121
2122 cond.begin(*this);
2123 EmitBlock(RHSBlock);
2125 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
2126 TrueCount - LHSScaledTrueCount, LH, CondOp);
2127 cond.end(*this);
2128
2129 return;
2130 }
2131
2132 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2133 // Conditional operator handling can give us a throw expression as a
2134 // condition for a case like:
2135 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2136 // Fold this to:
2137 // br(c, throw x, br(y, t, f))
2138 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
2139 return;
2140 }
2141
2142 // Emit the code with the fully general case.
2143 llvm::Value *CondV;
2144 {
2145 ApplyDebugLocation DL(*this, Cond);
2146 CondV = EvaluateExprAsBool(Cond);
2147 }
2148
2149 MaybeEmitDeferredVarDeclInit(ConditionalDecl);
2150
2151 // If not at the top of the logical operator nest, update MCDC temp with the
2152 // boolean result of the evaluated condition.
2153 {
2154 const Expr *MCDCBaseExpr = Cond;
2155 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2156 // expression, MC/DC tracks the result of the ternary, and this is tied to
2157 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2158 // this is the case, the ConditionalOperator expression is passed through
2159 // the ConditionalOp parameter and then used as the MCDC base expression.
2160 if (ConditionalOp)
2161 MCDCBaseExpr = ConditionalOp;
2162
2163 if (isMCDCBranchExpr(stripCond(MCDCBaseExpr)) &&
2165 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2166 }
2167
2168 llvm::MDNode *Weights = nullptr;
2169 llvm::MDNode *Unpredictable = nullptr;
2170
2171 // If the branch has a condition wrapped by __builtin_unpredictable,
2172 // create metadata that specifies that the branch is unpredictable.
2173 // Don't bother if not optimizing because that metadata would not be used.
2174 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2175 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2176 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2177 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2178 llvm::MDBuilder MDHelper(getLLVMContext());
2179 Unpredictable = MDHelper.createUnpredictable();
2180 }
2181 }
2182
2183 // If there is a Likelihood knowledge for the cond, lower it.
2184 // Note that if not optimizing this won't emit anything.
2185 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2186 if (CondV != NewCondV)
2187 CondV = NewCondV;
2188 else {
2189 // Otherwise, lower profile counts. Note that we do this even at -O0.
2190 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2191 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2192 }
2193
2194 llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, FalseBlock,
2195 Weights, Unpredictable);
2196 addInstToNewSourceAtom(BrInst, CondV);
2197
2198 switch (HLSLControlFlowAttr) {
2199 case HLSLControlFlowHintAttr::Microsoft_branch:
2200 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2201 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2202
2203 llvm::ConstantInt *BranchHintConstant =
2205 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2206 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2207 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2208
2210 {MDHelper.createString("hlsl.controlflow.hint"),
2211 MDHelper.createConstant(BranchHintConstant)});
2212 BrInst->setMetadata("hlsl.controlflow.hint",
2213 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2214 break;
2215 }
2216 // This is required to avoid warnings during compilation
2217 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2218 break;
2219 }
2220}
2221
2222llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
2223 unsigned Idx,
2224 const CallExpr *E) {
2225 llvm::Value *Arg = nullptr;
2226 if ((ICEArguments & (1 << Idx)) == 0) {
2227 Arg = EmitScalarExpr(E->getArg(Idx));
2228 } else {
2229 // If this is required to be a constant, constant fold it so that we
2230 // know that the generated intrinsic gets a ConstantInt.
2231 std::optional<llvm::APSInt> Result =
2233 assert(Result && "Expected argument to be a constant");
2234 Arg = llvm::ConstantInt::get(getLLVMContext(), *Result);
2235 }
2236 return Arg;
2237}
2238
2239/// ErrorUnsupported - Print out an error that codegen doesn't support the
2240/// specified stmt yet.
2241void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2242 CGM.ErrorUnsupported(S, Type);
2243}
2244
2245/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2246/// variable-length array whose elements have a non-zero bit-pattern.
2247///
2248/// \param baseType the inner-most element type of the array
2249/// \param src - a char* pointing to the bit-pattern for a single
2250/// base element of the array
2251/// \param sizeInChars - the total size of the VLA, in chars
2253 Address dest, Address src,
2254 llvm::Value *sizeInChars) {
2255 CGBuilderTy &Builder = CGF.Builder;
2256
2257 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2258 llvm::Value *baseSizeInChars
2259 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2260
2261 Address begin = dest.withElementType(CGF.Int8Ty);
2262 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2263 begin.emitRawPointer(CGF),
2264 sizeInChars, "vla.end");
2265
2266 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2267 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2268 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2269
2270 // Make a loop over the VLA. C99 guarantees that the VLA element
2271 // count must be nonzero.
2272 CGF.EmitBlock(loopBB);
2273
2274 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2275 cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2276
2277 CharUnits curAlign =
2278 dest.getAlignment().alignmentOfArrayElement(baseSize);
2279
2280 // memcpy the individual element bit-pattern.
2281 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2282 /*volatile*/ false);
2283
2284 // Go to the next element.
2285 llvm::Value *next =
2286 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2287
2288 // Leave if that's the end of the VLA.
2289 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2290 Builder.CreateCondBr(done, contBB, loopBB);
2291 cur->addIncoming(next, loopBB);
2292
2293 CGF.EmitBlock(contBB);
2294}
2295
2297 const PFPField &Field) {
2298 return EmitAddressOfPFPField(
2299 RecordPtr,
2300 Builder.CreateConstInBoundsByteGEP(RecordPtr.withElementType(Int8Ty),
2301 Field.Offset),
2302 Field.Field);
2303}
2304
2306 Address PtrPtr,
2307 const FieldDecl *Field) {
2308 llvm::Value *Disc;
2309 if (CGM.getContext().arePFPFieldsTriviallyCopyable(Field->getParent())) {
2310 uint64_t FieldSignature =
2311 llvm::getPointerAuthStableSipHash(CGM.getPFPFieldName(Field));
2312 Disc = llvm::ConstantInt::get(CGM.Int64Ty, FieldSignature);
2313 } else
2314 Disc = Builder.CreatePtrToInt(RecordPtr.getBasePointer(), CGM.Int64Ty);
2315
2316 llvm::GlobalValue *DS = CGM.getPFPDeactivationSymbol(Field);
2317 llvm::OperandBundleDef DSBundle("deactivation-symbol", DS);
2318 llvm::Value *Args[] = {PtrPtr.getBasePointer(), Disc, Builder.getTrue()};
2319 return Address(
2320 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::protected_field_ptr,
2321 PtrPtr.getType()),
2322 Args, DSBundle),
2323 VoidPtrTy, PtrPtr.getAlignment());
2324}
2325
2326void
2328 // Ignore empty classes in C++.
2329 if (getLangOpts().CPlusPlus)
2330 if (const auto *RD = Ty->getAsCXXRecordDecl(); RD && RD->isEmpty())
2331 return;
2332
2333 if (DestPtr.getElementType() != Int8Ty)
2334 DestPtr = DestPtr.withElementType(Int8Ty);
2335
2336 // Get size and alignment info for this aggregate.
2338
2339 llvm::Value *SizeVal;
2340 const VariableArrayType *vla;
2341
2342 // Don't bother emitting a zero-byte memset.
2343 if (size.isZero()) {
2344 // But note that getTypeInfo returns 0 for a VLA.
2345 if (const VariableArrayType *vlaType =
2346 dyn_cast_or_null<VariableArrayType>(
2347 getContext().getAsArrayType(Ty))) {
2348 auto VlaSize = getVLASize(vlaType);
2349 SizeVal = VlaSize.NumElts;
2350 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2351 if (!eltSize.isOne())
2352 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2353 vla = vlaType;
2354 } else {
2355 return;
2356 }
2357 } else {
2358 SizeVal = CGM.getSize(size);
2359 vla = nullptr;
2360 }
2361
2362 // If the type contains a pointer to data member we can't memset it to zero.
2363 // Instead, create a null constant and copy it to the destination.
2364 // TODO: there are other patterns besides zero that we can usefully memset,
2365 // like -1, which happens to be the pattern used by member-pointers.
2366 if (!CGM.getTypes().isZeroInitializable(Ty)) {
2367 // For a VLA, emit a single element, then splat that over the VLA.
2368 if (vla) Ty = getContext().getBaseElementType(vla);
2369
2370 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2371
2372 llvm::GlobalVariable *NullVariable =
2373 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2374 /*isConstant=*/true,
2375 llvm::GlobalVariable::PrivateLinkage,
2376 NullConstant, Twine());
2377 CharUnits NullAlign = DestPtr.getAlignment();
2378 NullVariable->setAlignment(NullAlign.getAsAlign());
2379 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2380
2381 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2382
2383 // Get and call the appropriate llvm.memcpy overload.
2384 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2385 } else {
2386 // Otherwise, just memset the whole thing to zero. This is legal
2387 // because in LLVM, all default initializers (other than the ones we just
2388 // handled above, and the case handled below) are guaranteed to have a bit
2389 // pattern of all zeros.
2390 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2391 }
2392
2393 // With the pointer field protection feature, null pointers do not have a bit
2394 // pattern of zero in memory, so we must initialize them separately.
2395 for (auto &Field : getContext().findPFPFields(Ty)) {
2396 auto addr = EmitAddressOfPFPField(DestPtr, Field);
2397 Builder.CreateStore(llvm::ConstantPointerNull::get(VoidPtrTy), addr);
2398 }
2399}
2400
2401llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2402 // Make sure that there is a block for the indirect goto.
2403 if (!IndirectBranch)
2405
2406 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2407
2408 // Make sure the indirect branch includes all of the address-taken blocks.
2409 IndirectBranch->addDestination(BB);
2410 return llvm::BlockAddress::get(CurFn->getType(), BB);
2411}
2412
2414 // If we already made the indirect branch for indirect goto, return its block.
2415 if (IndirectBranch) return IndirectBranch->getParent();
2416
2417 CGBuilderTy TmpBuilder(CGM, createBasicBlock("indirectgoto"));
2418
2419 // Create the PHI node that indirect gotos will add entries to.
2420 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2421 "indirect.goto.dest");
2422
2423 // Create the indirect branch instruction.
2424 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2425 return IndirectBranch->getParent();
2426}
2427
2428/// Computes the length of an array in elements, as well as the base
2429/// element type and a properly-typed first element pointer.
2430llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2431 QualType &baseType,
2432 Address &addr) {
2433 const ArrayType *arrayType = origArrayType;
2434
2435 // If it's a VLA, we have to load the stored size. Note that
2436 // this is the size of the VLA in bytes, not its size in elements.
2437 llvm::Value *numVLAElements = nullptr;
2440
2441 // Walk into all VLAs. This doesn't require changes to addr,
2442 // which has type T* where T is the first non-VLA element type.
2443 do {
2444 QualType elementType = arrayType->getElementType();
2445 arrayType = getContext().getAsArrayType(elementType);
2446
2447 // If we only have VLA components, 'addr' requires no adjustment.
2448 if (!arrayType) {
2449 baseType = elementType;
2450 return numVLAElements;
2451 }
2453
2454 // We get out here only if we find a constant array type
2455 // inside the VLA.
2456 }
2457
2458 // We have some number of constant-length arrays, so addr should
2459 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2460 // down to the first element of addr.
2462
2463 // GEP down to the array type.
2464 llvm::ConstantInt *zero = Builder.getInt32(0);
2465 gepIndices.push_back(zero);
2466
2467 uint64_t countFromCLAs = 1;
2468 QualType eltType;
2469
2470 llvm::ArrayType *llvmArrayType =
2471 dyn_cast<llvm::ArrayType>(addr.getElementType());
2472 while (llvmArrayType) {
2474 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2475 llvmArrayType->getNumElements());
2476
2477 gepIndices.push_back(zero);
2478 countFromCLAs *= llvmArrayType->getNumElements();
2479 eltType = arrayType->getElementType();
2480
2481 llvmArrayType =
2482 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2483 arrayType = getContext().getAsArrayType(arrayType->getElementType());
2484 assert((!llvmArrayType || arrayType) &&
2485 "LLVM and Clang types are out-of-synch");
2486 }
2487
2488 if (arrayType) {
2489 // From this point onwards, the Clang array type has been emitted
2490 // as some other type (probably a packed struct). Compute the array
2491 // size, and just emit the 'begin' expression as a bitcast.
2492 while (arrayType) {
2493 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2494 eltType = arrayType->getElementType();
2495 arrayType = getContext().getAsArrayType(eltType);
2496 }
2497
2498 llvm::Type *baseType = ConvertType(eltType);
2499 addr = addr.withElementType(baseType);
2500 } else {
2501 // Create the actual GEP.
2502 addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
2503 addr.emitRawPointer(*this),
2504 gepIndices, "array.begin"),
2505 ConvertTypeForMem(eltType), addr.getAlignment());
2506 }
2507
2508 baseType = eltType;
2509
2510 llvm::Value *numElements
2511 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2512
2513 // If we had any VLA dimensions, factor them in.
2514 if (numVLAElements)
2515 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2516
2517 return numElements;
2518}
2519
2522 assert(vla && "type was not a variable array type!");
2523 return getVLASize(vla);
2524}
2525
2528 // The number of elements so far; always size_t.
2529 llvm::Value *numElements = nullptr;
2530
2531 QualType elementType;
2532 do {
2533 elementType = type->getElementType();
2534 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2535 assert(vlaSize && "no size for VLA!");
2536 assert(vlaSize->getType() == SizeTy);
2537
2538 if (!numElements) {
2539 numElements = vlaSize;
2540 } else {
2541 // It's undefined behavior if this wraps around, so mark it that way.
2542 // FIXME: Teach -fsanitize=undefined to trap this.
2543 numElements = Builder.CreateNUWMul(numElements, vlaSize);
2544 }
2545 } while ((type = getContext().getAsVariableArrayType(elementType)));
2546
2547 return { numElements, elementType };
2548}
2549
2553 assert(vla && "type was not a variable array type!");
2554 return getVLAElements1D(vla);
2555}
2556
2559 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2560 assert(VlaSize && "no size for VLA!");
2561 assert(VlaSize->getType() == SizeTy);
2562 return { VlaSize, Vla->getElementType() };
2563}
2564
2566 assert(type->isVariablyModifiedType() &&
2567 "Must pass variably modified type to EmitVLASizes!");
2568
2570
2571 // We're going to walk down into the type and look for VLA
2572 // expressions.
2573 do {
2574 assert(type->isVariablyModifiedType());
2575
2576 const Type *ty = type.getTypePtr();
2577 switch (ty->getTypeClass()) {
2578
2579#define TYPE(Class, Base)
2580#define ABSTRACT_TYPE(Class, Base)
2581#define NON_CANONICAL_TYPE(Class, Base)
2582#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2583#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2584#include "clang/AST/TypeNodes.inc"
2585 llvm_unreachable("unexpected dependent type!");
2586
2587 // These types are never variably-modified.
2588 case Type::Builtin:
2589 case Type::Complex:
2590 case Type::Vector:
2591 case Type::ExtVector:
2592 case Type::ConstantMatrix:
2593 case Type::Record:
2594 case Type::Enum:
2595 case Type::Using:
2596 case Type::TemplateSpecialization:
2597 case Type::ObjCTypeParam:
2598 case Type::ObjCObject:
2599 case Type::ObjCInterface:
2600 case Type::ObjCObjectPointer:
2601 case Type::BitInt:
2602 case Type::HLSLInlineSpirv:
2603 case Type::PredefinedSugar:
2604 llvm_unreachable("type class is never variably-modified!");
2605
2606 case Type::Adjusted:
2607 type = cast<AdjustedType>(ty)->getAdjustedType();
2608 break;
2609
2610 case Type::Decayed:
2611 type = cast<DecayedType>(ty)->getPointeeType();
2612 break;
2613
2614 case Type::Pointer:
2615 type = cast<PointerType>(ty)->getPointeeType();
2616 break;
2617
2618 case Type::BlockPointer:
2619 type = cast<BlockPointerType>(ty)->getPointeeType();
2620 break;
2621
2622 case Type::LValueReference:
2623 case Type::RValueReference:
2624 type = cast<ReferenceType>(ty)->getPointeeType();
2625 break;
2626
2627 case Type::MemberPointer:
2628 type = cast<MemberPointerType>(ty)->getPointeeType();
2629 break;
2630
2631 case Type::ArrayParameter:
2632 case Type::ConstantArray:
2633 case Type::IncompleteArray:
2634 // Losing element qualification here is fine.
2635 type = cast<ArrayType>(ty)->getElementType();
2636 break;
2637
2638 case Type::VariableArray: {
2639 // Losing element qualification here is fine.
2641
2642 // Unknown size indication requires no size computation.
2643 // Otherwise, evaluate and record it.
2644 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2645 // It's possible that we might have emitted this already,
2646 // e.g. with a typedef and a pointer to it.
2647 llvm::Value *&entry = VLASizeMap[sizeExpr];
2648 if (!entry) {
2649 llvm::Value *size = EmitScalarExpr(sizeExpr);
2650
2651 // C11 6.7.6.2p5:
2652 // If the size is an expression that is not an integer constant
2653 // expression [...] each time it is evaluated it shall have a value
2654 // greater than zero.
2655 if (SanOpts.has(SanitizerKind::VLABound)) {
2656 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2657 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2658 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2659 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2660 clang::QualType SEType = sizeExpr->getType();
2661 llvm::Value *CheckCondition =
2662 SEType->isSignedIntegerType()
2663 ? Builder.CreateICmpSGT(size, Zero)
2664 : Builder.CreateICmpUGT(size, Zero);
2665 llvm::Constant *StaticArgs[] = {
2666 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2667 EmitCheckTypeDescriptor(SEType)};
2668 EmitCheck(std::make_pair(CheckCondition, CheckOrdinal),
2669 CheckHandler, StaticArgs, size);
2670 }
2671
2672 // Always zexting here would be wrong if it weren't
2673 // undefined behavior to have a negative bound.
2674 // FIXME: What about when size's type is larger than size_t?
2675 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2676 }
2677 }
2678 type = vat->getElementType();
2679 break;
2680 }
2681
2682 case Type::FunctionProto:
2683 case Type::FunctionNoProto:
2684 type = cast<FunctionType>(ty)->getReturnType();
2685 break;
2686
2687 case Type::Paren:
2688 case Type::TypeOf:
2689 case Type::UnaryTransform:
2690 case Type::Attributed:
2691 case Type::BTFTagAttributed:
2692 case Type::OverflowBehavior:
2693 case Type::HLSLAttributedResource:
2694 case Type::SubstTemplateTypeParm:
2695 case Type::MacroQualified:
2696 case Type::CountAttributed:
2697 case Type::LateParsedAttr:
2698 // Keep walking after single level desugaring.
2699 type = type.getSingleStepDesugaredType(getContext());
2700 break;
2701
2702 case Type::Typedef:
2703 case Type::Decltype:
2704 case Type::Auto:
2705 case Type::DeducedTemplateSpecialization:
2706 case Type::PackIndexing:
2707 // Stop walking: nothing to do.
2708 return;
2709
2710 case Type::TypeOfExpr:
2711 // Stop walking: emit typeof expression.
2712 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2713 return;
2714
2715 case Type::Atomic:
2716 type = cast<AtomicType>(ty)->getValueType();
2717 break;
2718
2719 case Type::Pipe:
2720 type = cast<PipeType>(ty)->getElementType();
2721 break;
2722 }
2723 } while (type->isVariablyModifiedType());
2724}
2725
2727 if (getContext().getBuiltinVaListType()->isArrayType())
2728 return EmitPointerWithAlignment(E);
2729 return EmitLValue(E).getAddress();
2730}
2731
2735
2739
2741 const APValue &Init) {
2742 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2743 if (CGDebugInfo *Dbg = getDebugInfo())
2744 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2745 Dbg->EmitGlobalVariable(E->getDecl(), Init);
2746}
2747
2750 // At the moment, the only aggressive peephole we do in IR gen
2751 // is trunc(zext) folding, but if we add more, we can easily
2752 // extend this protection.
2753
2754 if (!rvalue.isScalar()) return PeepholeProtection();
2755 llvm::Value *value = rvalue.getScalarVal();
2756 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2757
2758 // Just make an extra bitcast.
2759 assert(HaveInsertPoint());
2760 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2761 Builder.GetInsertBlock());
2762
2763 PeepholeProtection protection;
2764 protection.Inst = inst;
2765 return protection;
2766}
2767
2769 if (!protection.Inst) return;
2770
2771 // In theory, we could try to duplicate the peepholes now, but whatever.
2772 protection.Inst->eraseFromParent();
2773}
2774
2776 QualType Ty, SourceLocation Loc,
2777 SourceLocation AssumptionLoc,
2778 llvm::Value *Alignment,
2779 llvm::Value *OffsetValue) {
2780 if (Alignment->getType() != IntPtrTy)
2781 Alignment =
2782 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2783 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2784 OffsetValue =
2785 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2786 llvm::Value *TheCheck = nullptr;
2787 if (SanOpts.has(SanitizerKind::Alignment)) {
2788 llvm::Value *PtrIntValue =
2789 Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2790
2791 if (OffsetValue) {
2792 bool IsOffsetZero = false;
2793 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2794 IsOffsetZero = CI->isZero();
2795
2796 if (!IsOffsetZero)
2797 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2798 }
2799
2800 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2801 llvm::Value *Mask =
2802 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2803 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2804 TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2805 }
2806 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2807 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2808
2809 if (!SanOpts.has(SanitizerKind::Alignment))
2810 return;
2811 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2812 OffsetValue, TheCheck, Assumption);
2813}
2814
2816 const Expr *E,
2817 SourceLocation AssumptionLoc,
2818 llvm::Value *Alignment,
2819 llvm::Value *OffsetValue) {
2820 QualType Ty = E->getType();
2821 SourceLocation Loc = E->getExprLoc();
2822
2823 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2824 OffsetValue);
2825}
2826
2827llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2828 llvm::Value *AnnotatedVal,
2829 StringRef AnnotationStr,
2830 SourceLocation Location,
2831 const AnnotateAttr *Attr) {
2833 AnnotatedVal,
2834 CGM.EmitAnnotationString(AnnotationStr),
2835 CGM.EmitAnnotationUnit(Location),
2836 CGM.EmitAnnotationLineNo(Location),
2837 };
2838 if (Attr)
2839 Args.push_back(CGM.EmitAnnotationArgs(Attr));
2840 return Builder.CreateCall(AnnotationFn, Args);
2841}
2842
2843void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2844 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2845 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2846 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2847 {V->getType(), CGM.ConstGlobalsPtrTy}),
2848 V, I->getAnnotation(), D->getLocation(), I);
2849}
2850
2852 Address Addr) {
2853 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2854 llvm::Value *V = Addr.emitRawPointer(*this);
2855 llvm::Type *VTy = V->getType();
2856 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2857 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2858 llvm::PointerType *IntrinTy =
2859 llvm::PointerType::get(CGM.getLLVMContext(), AS);
2860 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2861 {IntrinTy, CGM.ConstGlobalsPtrTy});
2862
2863 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2864 // FIXME Always emit the cast inst so we can differentiate between
2865 // annotation on the first field of a struct and annotation on the struct
2866 // itself.
2867 if (VTy != IntrinTy)
2868 V = Builder.CreateBitCast(V, IntrinTy);
2869 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2870 V = Builder.CreateBitCast(V, VTy);
2871 }
2872
2873 return Address(V, Addr.getElementType(), Addr.getAlignment());
2874}
2875
2877
2879 : CGF(CGF) {
2880 assert(!CGF->IsSanitizerScope);
2881 CGF->IsSanitizerScope = true;
2882}
2883
2885 CGF->IsSanitizerScope = false;
2886}
2887
2888void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2889 const llvm::Twine &Name,
2890 llvm::BasicBlock::iterator InsertPt) const {
2891 LoopStack.InsertHelper(I);
2892 if (IsSanitizerScope)
2893 I->setNoSanitizeMetadata();
2894}
2895
2897 llvm::Instruction *I, const llvm::Twine &Name,
2898 llvm::BasicBlock::iterator InsertPt) const {
2899 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2900 if (CGF)
2901 CGF->InsertHelper(I, Name, InsertPt);
2902}
2903
2904// Emits an error if we don't have a valid set of target features for the
2905// called function.
2907 const FunctionDecl *TargetDecl) {
2908 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2909 CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
2910 getLangOpts(), E, FD, TargetDecl);
2911}
2912
2913// Emits an error if we don't have a valid set of target features for the
2914// called function.
2916 const FunctionDecl *TargetDecl) {
2917 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2918 CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
2919 getLangOpts(), Loc, FD, TargetDecl);
2920}
2921
2922void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2923 if (!CGM.getCodeGenOpts().SanitizeStats)
2924 return;
2925
2926 llvm::IRBuilder<> IRB(Builder.GetInsertPoint());
2927 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2928 CGM.getSanStats().create(IRB, SSK);
2929}
2930
2932 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2933 const CGCalleeInfo &CI = Callee.getAbstractInfo();
2935 if (!FP)
2936 return;
2937
2938 StringRef Salt;
2939 if (const auto &Info = FP->getExtraAttributeInfo())
2940 Salt = Info.CFISalt;
2941
2942 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar(), Salt));
2943}
2944
2945llvm::Value *
2946CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2947 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(RO.Features);
2948}
2949
2950llvm::Value *
2951CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2952 llvm::Value *Condition = nullptr;
2953
2954 if (RO.Architecture) {
2955 StringRef Arch = *RO.Architecture;
2956 // If arch= specifies an x86-64 micro-architecture level, test the feature
2957 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2958 if (Arch.starts_with("x86-64"))
2959 Condition = EmitX86CpuSupports({Arch});
2960 else
2961 Condition = EmitX86CpuIs(Arch);
2962 }
2963
2964 if (!RO.Features.empty()) {
2965 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2966 Condition =
2967 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2968 }
2969 return Condition;
2970}
2971
2973 llvm::Function *Resolver,
2974 CGBuilderTy &Builder,
2975 llvm::Function *FuncToReturn,
2976 bool SupportsIFunc) {
2977 if (SupportsIFunc) {
2978 Builder.CreateRet(FuncToReturn);
2979 return;
2980 }
2981
2983 llvm::make_pointer_range(Resolver->args()));
2984
2985 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2986 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2987
2988 if (Resolver->getReturnType()->isVoidTy())
2989 Builder.CreateRetVoid();
2990 else
2991 Builder.CreateRet(Result);
2992}
2993
2995 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2996 llvm::SaveAndRestore<llvm::Function *> savedCurFn(CurFn, Resolver);
2997 llvm::Triple::ArchType ArchType =
2998 getContext().getTargetInfo().getTriple().getArch();
2999
3000 switch (ArchType) {
3001 case llvm::Triple::x86:
3002 case llvm::Triple::x86_64:
3003 EmitX86MultiVersionResolver(Resolver, Options);
3004 return;
3005 case llvm::Triple::aarch64:
3006 EmitAArch64MultiVersionResolver(Resolver, Options);
3007 return;
3008 case llvm::Triple::riscv32:
3009 case llvm::Triple::riscv64:
3010 case llvm::Triple::riscv32be:
3011 case llvm::Triple::riscv64be:
3012 EmitRISCVMultiVersionResolver(Resolver, Options);
3013 return;
3014 case llvm::Triple::ppc:
3015 case llvm::Triple::ppc64:
3016 if (getContext().getTargetInfo().getTriple().isOSAIX()) {
3017 EmitPPCAIXMultiVersionResolver(Resolver, Options);
3018 return;
3019 }
3020 [[fallthrough]];
3021 default:
3022 assert(false &&
3023 "Only implemented for x86, AArch64, RISC-V, and PowerPC AIX");
3024 }
3025}
3026
3027/**
3028 * define internal ptr @foo.resolver() {
3029 * entry:
3030 * %is_version_1 = __builtin_cpu_supports(version_1)
3031 * br i1 %1, label %if.version_1, label %if.else_2
3032 *
3033 * if.version_1:
3034 * ret ptr @foo.version_1
3035 *
3036 * if.else_2:
3037 * %is_version_2 = __builtin_cpu_supports(version_2)
3038 * ...
3039 * if.else: ; preds = %entry
3040 * ret ptr @foo.default
3041 * }
3042 */
3044 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3045
3046 // entry:
3047 llvm::BasicBlock *CurBlock = createBasicBlock("entry", Resolver);
3048
3050 for (const FMVResolverOption &RO : Options) {
3051 Builder.SetInsertPoint(CurBlock);
3052 // The 'default' or 'generic' case.
3053 if (!RO.Architecture && RO.Features.empty()) {
3054 // if.else:
3055 // ret ptr @foo.default
3056 assert(&RO == Options.end() - 1 &&
3057 "Default or Generic case must be last");
3058 Builder.CreateRet(RO.Function);
3059 return;
3060 }
3061 // if.else_n:
3062 // %is_version_n = __builtin_cpu_supports(version_n)
3063 // br i1 %is_version_n, label %if.version_n, label %if.else_n+1
3064 //
3065 // if.version_n:
3066 // ret ptr @foo_version_n
3067 assert(RO.Features.size() == 1 &&
3068 "for now one feature requirement per version");
3069
3070 StringRef FeatureStr = RO.Features[0];
3071 StringRef BuiltinCpuSupportsArg;
3072 bool IsNegated = false;
3073
3074 if (FeatureStr.starts_with("cpu=")) {
3075 // CPU specification - map to ISA level
3076 StringRef CPU = FeatureStr.split("=").second.trim();
3077 BuiltinCpuSupportsArg = llvm::StringSwitch<StringRef>(CPU)
3078#define PPC_AIX_CLONES_CPU(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _) \
3079 .Case(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3080#include "llvm/TargetParser/PPCTargetParser.def"
3081 .Default("error");
3082 } else {
3083 // Feature strings arrive here already normalized:
3084 // - Positive features: just the name (e.g., "altivec")
3085 // - Negated features: "no-" prefix (e.g., "no-altivec")
3086 if (FeatureStr.starts_with("no-")) {
3087 IsNegated = true;
3088 FeatureStr = FeatureStr.drop_front(3);
3089 }
3090
3091 // Map feature names to __builtin_cpu_supports() strings
3092 BuiltinCpuSupportsArg =
3093 llvm::StringSwitch<StringRef>(FeatureStr)
3094#define PPC_AIX_CLONES_FEATURE(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _, \
3095 __) \
3096 .Case(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3097#include "llvm/TargetParser/PPCTargetParser.def"
3098 // Features without runtime checks return empty string
3099 .Default("");
3100
3101 // All features in target_clones must have runtime detection
3102 assert(!BuiltinCpuSupportsArg.empty() &&
3103 "Feature without runtime detection should have been rejected in "
3104 "Sema");
3105 }
3106
3107 assert(getContext().getTargetInfo().validateCpuSupports(
3108 BuiltinCpuSupportsArg));
3109
3110 llvm::Value *Condition =
3111 EmitPPCBuiltinCpu(Builtin::BI__builtin_cpu_supports,
3112 Builder.getInt1Ty(), BuiltinCpuSupportsArg);
3113
3114 // Negate the condition if this is a negated feature
3115 if (IsNegated) {
3116 Condition = Builder.CreateNot(Condition, "neg");
3117 }
3118
3119 llvm::BasicBlock *ThenBlock = createBasicBlock("if.version", Resolver);
3120 CurBlock = createBasicBlock("if.else", Resolver);
3121 Builder.CreateCondBr(Condition, ThenBlock, CurBlock);
3122
3123 Builder.SetInsertPoint(ThenBlock);
3124 Builder.CreateRet(RO.Function);
3125 }
3126
3127 llvm_unreachable("Default case missing");
3128}
3129
3131 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3132
3133 if (getContext().getTargetInfo().getTriple().getOS() !=
3134 llvm::Triple::OSType::Linux) {
3135 CGM.getDiags().Report(diag::err_os_unsupport_riscv_fmv);
3136 return;
3137 }
3138
3139 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3140 Builder.SetInsertPoint(CurBlock);
3142
3143 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3144 bool HasDefault = false;
3145 unsigned DefaultIndex = 0;
3146
3147 // Check the each candidate function.
3148 for (unsigned Index = 0; Index < Options.size(); Index++) {
3149
3150 if (Options[Index].Features.empty()) {
3151 HasDefault = true;
3152 DefaultIndex = Index;
3153 continue;
3154 }
3155
3156 Builder.SetInsertPoint(CurBlock);
3157
3158 // FeaturesCondition: The bitmask of the required extension has been
3159 // enabled by the runtime object.
3160 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
3161 // REQUIRED_BITMASK
3162 //
3163 // When condition is met, return this version of the function.
3164 // Otherwise, try the next version.
3165 //
3166 // if (FeaturesConditionVersion1)
3167 // return Version1;
3168 // else if (FeaturesConditionVersion2)
3169 // return Version2;
3170 // else if (FeaturesConditionVersion3)
3171 // return Version3;
3172 // ...
3173 // else
3174 // return DefaultVersion;
3175
3176 // TODO: Add a condition to check the length before accessing elements.
3177 // Without checking the length first, we may access an incorrect memory
3178 // address when using different versions.
3179 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
3180 llvm::SmallVector<std::string, 8> TargetAttrFeats;
3181
3182 for (StringRef Feat : Options[Index].Features) {
3183 std::vector<std::string> FeatStr =
3185
3186 assert(FeatStr.size() == 1 && "Feature string not delimited");
3187
3188 std::string &CurrFeat = FeatStr.front();
3189 if (CurrFeat[0] == '+')
3190 TargetAttrFeats.push_back(CurrFeat.substr(1));
3191 }
3192
3193 if (TargetAttrFeats.empty())
3194 continue;
3195
3196 for (std::string &Feat : TargetAttrFeats)
3197 CurrTargetAttrFeats.push_back(Feat);
3198
3199 Builder.SetInsertPoint(CurBlock);
3200 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(CurrTargetAttrFeats);
3201
3202 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3203 CGBuilderTy RetBuilder(CGM, RetBlock);
3204 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder,
3205 Options[Index].Function, SupportsIFunc);
3206 llvm::BasicBlock *ElseBlock = createBasicBlock("resolver_else", Resolver);
3207
3208 Builder.SetInsertPoint(CurBlock);
3209 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
3210
3211 CurBlock = ElseBlock;
3212 }
3213
3214 // Finally, emit the default one.
3215 if (HasDefault) {
3216 Builder.SetInsertPoint(CurBlock);
3218 CGM, Resolver, Builder, Options[DefaultIndex].Function, SupportsIFunc);
3219 return;
3220 }
3221
3222 // If no generic/default, emit an unreachable.
3223 Builder.SetInsertPoint(CurBlock);
3225}
3226
3228 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3229 assert(!Options.empty() && "No multiversion resolver options found");
3230 assert(Options.back().Features.size() == 0 && "Default case must be last");
3231 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3232 assert(SupportsIFunc &&
3233 "Multiversion resolver requires target IFUNC support");
3234 bool AArch64CpuInitialized = false;
3235 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3236
3237 for (const FMVResolverOption &RO : Options) {
3238 // Skip unreachable versions.
3239 if (RO.Function == nullptr)
3240 continue;
3241
3242 Builder.SetInsertPoint(CurBlock);
3243 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3244
3245 // The 'default' or 'all features enabled' case.
3246 if (!Condition) {
3247 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3248 SupportsIFunc);
3249 return;
3250 }
3251
3252 if (!AArch64CpuInitialized) {
3253 Builder.SetInsertPoint(CurBlock->begin());
3254 EmitAArch64CpuInit();
3255 AArch64CpuInitialized = true;
3256 Builder.SetInsertPoint(CurBlock);
3257 }
3258
3259 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3260 CGBuilderTy RetBuilder(CGM, RetBlock);
3261 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3262 SupportsIFunc);
3263 CurBlock = createBasicBlock("resolver_else", Resolver);
3264 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3265 }
3266
3267 // If no default, emit an unreachable.
3268 Builder.SetInsertPoint(CurBlock);
3270}
3271
3273 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3274
3275 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3276
3277 // Main function's basic block.
3278 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3279 Builder.SetInsertPoint(CurBlock);
3280 EmitX86CpuInit();
3281
3282 for (const FMVResolverOption &RO : Options) {
3283 Builder.SetInsertPoint(CurBlock);
3284 llvm::Value *Condition = FormX86ResolverCondition(RO);
3285
3286 // The 'default' or 'generic' case.
3287 if (!Condition) {
3288 assert(&RO == Options.end() - 1 &&
3289 "Default or Generic case must be last");
3290 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3291 SupportsIFunc);
3292 return;
3293 }
3294
3295 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3296 CGBuilderTy RetBuilder(CGM, RetBlock);
3297 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3298 SupportsIFunc);
3299 CurBlock = createBasicBlock("resolver_else", Resolver);
3300 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3301 }
3302
3303 // If no generic/default, emit an unreachable.
3304 Builder.SetInsertPoint(CurBlock);
3306}
3307
3308// Loc - where the diagnostic will point, where in the source code this
3309// alignment has failed.
3310// SecondaryLoc - if present (will be present if sufficiently different from
3311// Loc), the diagnostic will additionally point a "Note:" to this location.
3312// It should be the location where the __attribute__((assume_aligned))
3313// was written e.g.
3315 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
3316 SourceLocation SecondaryLoc, llvm::Value *Alignment,
3317 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3318 llvm::Instruction *Assumption) {
3319 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3320 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3321 llvm::Intrinsic::getOrInsertDeclaration(Builder.getModule(),
3322 llvm::Intrinsic::assume) &&
3323 "Assumption should be a call to llvm.assume().");
3324 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
3325 "Assumption should be the last instruction of the basic block, "
3326 "since the basic block is still being generated.");
3327
3328 if (!SanOpts.has(SanitizerKind::Alignment))
3329 return;
3330
3331 // Don't check pointers to volatile data. The behavior here is implementation-
3332 // defined.
3334 return;
3335
3336 // We need to temorairly remove the assumption so we can insert the
3337 // sanitizer check before it, else the check will be dropped by optimizations.
3338 Assumption->removeFromParent();
3339
3340 {
3341 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3342 auto CheckHandler = SanitizerHandler::AlignmentAssumption;
3343 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3344
3345 if (!OffsetValue)
3346 OffsetValue = Builder.getInt1(false); // no offset.
3347
3348 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3349 EmitCheckSourceLocation(SecondaryLoc),
3351 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3352 EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3353 StaticData, DynamicData);
3354 }
3355
3356 // We are now in the (new, empty) "cont" basic block.
3357 // Reintroduce the assumption.
3358 Builder.Insert(Assumption);
3359 // FIXME: Assumption still has it's original basic block as it's Parent.
3360}
3361
3363 if (CGDebugInfo *DI = getDebugInfo())
3364 return DI->SourceLocToDebugLoc(Location);
3365
3366 return llvm::DebugLoc();
3367}
3368
3369llvm::Value *
3370CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3371 Stmt::Likelihood LH) {
3372 switch (LH) {
3373 case Stmt::LH_None:
3374 return Cond;
3375 case Stmt::LH_Likely:
3376 case Stmt::LH_Unlikely:
3377 // Don't generate llvm.expect on -O0 as the backend won't use it for
3378 // anything.
3379 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3380 return Cond;
3381 llvm::Type *CondTy = Cond->getType();
3382 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3383 llvm::Function *FnExpect =
3384 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3385 llvm::Value *ExpectedValueOfCond =
3386 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3387 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3388 Cond->getName() + ".expval");
3389 }
3390 llvm_unreachable("Unknown Likelihood");
3391}
3392
3393llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3394 unsigned NumElementsDst,
3395 const llvm::Twine &Name) {
3396 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3397 unsigned NumElementsSrc = SrcTy->getNumElements();
3398 if (NumElementsSrc == NumElementsDst)
3399 return SrcVec;
3400
3401 std::vector<int> ShuffleMask(NumElementsDst, -1);
3402 for (unsigned MaskIdx = 0;
3403 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3404 ShuffleMask[MaskIdx] = MaskIdx;
3405
3406 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3407}
3408
3410 const CGPointerAuthInfo &PointerAuth,
3412 if (!PointerAuth.isSigned())
3413 return;
3414
3415 auto *Key = Builder.getInt32(PointerAuth.getKey());
3416
3417 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3418 if (!Discriminator)
3419 Discriminator = Builder.getSize(0);
3420
3421 llvm::Value *Args[] = {Key, Discriminator};
3422 Bundles.emplace_back("ptrauth", Args);
3423}
3424
3426 const CGPointerAuthInfo &PointerAuth,
3427 llvm::Value *Pointer,
3428 unsigned IntrinsicID) {
3429 if (!PointerAuth)
3430 return Pointer;
3431
3432 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3433
3434 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3435 if (!Discriminator) {
3436 Discriminator = CGF.Builder.getSize(0);
3437 }
3438
3439 // Convert the pointer to intptr_t before signing it.
3440 auto OrigType = Pointer->getType();
3441 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3442
3443 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3444 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3445 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3446
3447 // Convert back to the original type.
3448 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3449 return Pointer;
3450}
3451
3452llvm::Value *
3454 llvm::Value *Pointer) {
3455 if (!PointerAuth.shouldSign())
3456 return Pointer;
3457 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3458 llvm::Intrinsic::ptrauth_sign);
3459}
3460
3461static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3462 const CGPointerAuthInfo &PointerAuth,
3463 llvm::Value *Pointer) {
3464 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3465
3466 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3467 // Convert the pointer to intptr_t before signing it.
3468 auto OrigType = Pointer->getType();
3470 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3471 return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3472}
3473
3474llvm::Value *
3476 llvm::Value *Pointer) {
3477 if (PointerAuth.shouldStrip()) {
3478 return EmitStrip(*this, PointerAuth, Pointer);
3479 }
3480 if (!PointerAuth.shouldAuth()) {
3481 return Pointer;
3482 }
3483
3484 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3485 llvm::Intrinsic::ptrauth_auth);
3486}
3487
3489 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3490 if (CGDebugInfo *DI = getDebugInfo())
3491 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3492}
3493
3495 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3496 if (CGDebugInfo *DI = getDebugInfo())
3497 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3498}
3499
3500void CodeGenFunction::addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
3501 llvm::Value *Backup) {
3502 if (CGDebugInfo *DI = getDebugInfo()) {
3504 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3505 }
3506}
3507
3509 QualType Ty) {
3510 for (auto &Field : getContext().findPFPFields(Ty)) {
3511 if (getContext().arePFPFieldsTriviallyCopyable(Field.Field->getParent()))
3512 continue;
3513 auto DestFieldPtr = EmitAddressOfPFPField(DestPtr, Field);
3514 auto SrcFieldPtr = EmitAddressOfPFPField(SrcPtr, Field);
3515 Builder.CreateStore(Builder.CreateLoad(SrcFieldPtr), DestFieldPtr);
3516 }
3517}
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:158
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:971
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
BinaryOperatorKind Opcode
Definition Expr.h:4112
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:2293
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2859
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2317
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
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:1074
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1213
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:184
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
@ 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
This forwards to CodeGenFunction::InsertHelper.
llvm::ConstantInt * getSize(CharUnits N)
Definition CGBuilder.h:111
@ 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:4726
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:709
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:7370
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:4161
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:4051
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:187
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:584
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:263
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2549
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:194
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:244
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:4309
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:5691
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:3492
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:59
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:5867
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:4389
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:1661
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:675
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:4752
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:1777
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:2156
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:655
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:4460
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:583
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:569
SourceLocation getLocation() const
Definition DeclBase.h:449
bool hasAttr() const
Definition DeclBase.h:587
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4031
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
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:3109
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3311
Represents a function declaration or definition.
Definition Decl.h:2071
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3817
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:3056
bool usesSEHTry() const
Indicates the function uses __try.
Definition Decl.h:2657
QualType getReturnType() const
Definition Decl.h:2992
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
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:4321
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3285
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3430
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition Decl.cpp:3581
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2567
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3423
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2524
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4187
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:5416
QualType desugar() const
Definition TypeBase.h:5997
FunctionTypeExtraAttributeInfo getExtraAttributeInfo() const
Return the extra attribute information.
Definition TypeBase.h:5905
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
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:5692
Represents the declaration of a label.
Definition Decl.h:526
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:1832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
@ 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:8530
field_range fields() const
Definition Decl.h:4679
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:9068
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
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:885
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isObjCRetainableType() const
Definition Type.cpp:5611
bool isFunctionNoProtoType() const
Definition TypeBase.h:2664
bool isCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8729
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
QualType getElementType() const
Definition TypeBase.h:4287
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:352
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:6196
@ Other
Other implicit parameter.
Definition Decl.h:1787
@ 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:667
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5153
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