[Github] Label lldb-dap PRs (#125139)
[llvm-project.git] / clang / lib / CodeGen / CodeGenFunction.cpp
blob08165e0b28406a0c1f6534852629294677874ff2
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.
11 //===----------------------------------------------------------------------===//
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"
24 #include "clang/AST/ASTContext.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"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/StmtObjC.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/CodeGenOptions.h"
34 #include "clang/Basic/TargetBuiltins.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/CodeGen/CGFunctionInfo.h"
37 #include "clang/Frontend/FrontendDiagnostic.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/Dominators.h"
42 #include "llvm/IR/FPEnv.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/MDBuilder.h"
47 #include "llvm/Support/CRC.h"
48 #include "llvm/Support/xxhash.h"
49 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
50 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
51 #include <optional>
53 using namespace clang;
54 using namespace CodeGen;
56 namespace llvm {
57 extern cl::opt<bool> EnableSingleByteCoverage;
58 } // namespace llvm
60 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
61 /// markers.
62 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
63 const LangOptions &LangOpts) {
64 if (CGOpts.DisableLifetimeMarkers)
65 return false;
67 // Sanitizers may use markers.
68 if (CGOpts.SanitizeAddressUseAfterScope ||
69 LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
70 LangOpts.Sanitize.has(SanitizerKind::Memory))
71 return true;
73 // For now, only in optimized builds.
74 return CGOpts.OptimizationLevel != 0;
77 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
78 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
79 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
80 CGBuilderInserterTy(this)),
81 SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
82 DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
83 ShouldEmitLifetimeMarkers(
84 shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
85 if (!suppressNewContext)
86 CGM.getCXXABI().getMangleContext().startNewFunction();
87 EHStack.setCGF(this);
89 SetFastMathFlags(CurFPFeatures);
92 CodeGenFunction::~CodeGenFunction() {
93 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
94 assert(DeferredDeactivationCleanupStack.empty() &&
95 "missed to deactivate a cleanup");
97 if (getLangOpts().OpenMP && CurFn)
98 CGM.getOpenMPRuntime().functionFinished(*this);
100 // If we have an OpenMPIRBuilder we want to finalize functions (incl.
101 // outlining etc) at some point. Doing it once the function codegen is done
102 // seems to be a reasonable spot. We do it here, as opposed to the deletion
103 // time of the CodeGenModule, because we have to ensure the IR has not yet
104 // been "emitted" to the outside, thus, modifications are still sensible.
105 if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
106 CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
109 // Map the LangOption for exception behavior into
110 // the corresponding enum in the IR.
111 llvm::fp::ExceptionBehavior
112 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
114 switch (Kind) {
115 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
116 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
117 case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
118 default:
119 llvm_unreachable("Unsupported FP Exception Behavior");
123 void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
124 llvm::FastMathFlags FMF;
125 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
126 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
127 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
128 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
129 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
130 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
131 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
132 Builder.setFastMathFlags(FMF);
135 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
136 const Expr *E)
137 : CGF(CGF) {
138 ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
141 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
142 FPOptions FPFeatures)
143 : CGF(CGF) {
144 ConstructorHelper(FPFeatures);
147 void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
148 OldFPFeatures = CGF.CurFPFeatures;
149 CGF.CurFPFeatures = FPFeatures;
151 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
152 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
154 if (OldFPFeatures == FPFeatures)
155 return;
157 FMFGuard.emplace(CGF.Builder);
159 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
160 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
161 auto NewExceptionBehavior =
162 ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
163 FPFeatures.getExceptionMode()));
164 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
166 CGF.SetFastMathFlags(FPFeatures);
168 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
169 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
170 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
171 (NewExceptionBehavior == llvm::fp::ebIgnore &&
172 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
173 "FPConstrained should be enabled on entire function");
175 auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
176 auto OldValue =
177 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
178 auto NewValue = OldValue & Value;
179 if (OldValue != NewValue)
180 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
182 mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
183 mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
184 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
185 mergeFnAttrValue(
186 "unsafe-fp-math",
187 FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() &&
188 FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() &&
189 FPFeatures.allowFPContractAcrossStatement());
192 CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
193 CGF.CurFPFeatures = OldFPFeatures;
194 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
195 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
198 static LValue
199 makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType,
200 bool MightBeSigned, CodeGenFunction &CGF,
201 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
202 LValueBaseInfo BaseInfo;
203 TBAAAccessInfo TBAAInfo;
204 CharUnits Alignment =
205 CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType);
206 Address Addr =
207 MightBeSigned
208 ? CGF.makeNaturalAddressForPointer(V, T, Alignment, false, nullptr,
209 nullptr, IsKnownNonNull)
210 : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull);
211 return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
214 LValue
215 CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T,
216 KnownNonNull_t IsKnownNonNull) {
217 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
218 /*MightBeSigned*/ true, *this,
219 IsKnownNonNull);
222 LValue
223 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
224 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
225 /*MightBeSigned*/ true, *this);
228 LValue CodeGenFunction::MakeNaturalAlignRawAddrLValue(llvm::Value *V,
229 QualType T) {
230 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
231 /*MightBeSigned*/ false, *this);
234 LValue CodeGenFunction::MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V,
235 QualType T) {
236 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
237 /*MightBeSigned*/ false, *this);
240 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
241 return CGM.getTypes().ConvertTypeForMem(T);
244 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
245 return CGM.getTypes().ConvertType(T);
248 llvm::Type *CodeGenFunction::convertTypeForLoadStore(QualType ASTTy,
249 llvm::Type *LLVMTy) {
250 return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
253 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
254 type = type.getCanonicalType();
255 while (true) {
256 switch (type->getTypeClass()) {
257 #define TYPE(name, parent)
258 #define ABSTRACT_TYPE(name, parent)
259 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
260 #define DEPENDENT_TYPE(name, parent) case Type::name:
261 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
262 #include "clang/AST/TypeNodes.inc"
263 llvm_unreachable("non-canonical or dependent type in IR-generation");
265 case Type::Auto:
266 case Type::DeducedTemplateSpecialization:
267 llvm_unreachable("undeduced type in IR-generation");
269 // Various scalar types.
270 case Type::Builtin:
271 case Type::Pointer:
272 case Type::BlockPointer:
273 case Type::LValueReference:
274 case Type::RValueReference:
275 case Type::MemberPointer:
276 case Type::Vector:
277 case Type::ExtVector:
278 case Type::ConstantMatrix:
279 case Type::FunctionProto:
280 case Type::FunctionNoProto:
281 case Type::Enum:
282 case Type::ObjCObjectPointer:
283 case Type::Pipe:
284 case Type::BitInt:
285 case Type::HLSLAttributedResource:
286 return TEK_Scalar;
288 // Complexes.
289 case Type::Complex:
290 return TEK_Complex;
292 // Arrays, records, and Objective-C objects.
293 case Type::ConstantArray:
294 case Type::IncompleteArray:
295 case Type::VariableArray:
296 case Type::Record:
297 case Type::ObjCObject:
298 case Type::ObjCInterface:
299 case Type::ArrayParameter:
300 return TEK_Aggregate;
302 // We operate on atomic values according to their underlying type.
303 case Type::Atomic:
304 type = cast<AtomicType>(type)->getValueType();
305 continue;
307 llvm_unreachable("unknown type kind!");
311 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
312 // For cleanliness, we try to avoid emitting the return block for
313 // simple cases.
314 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
316 if (CurBB) {
317 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
319 // We have a valid insert point, reuse it if it is empty or there are no
320 // explicit jumps to the return block.
321 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
322 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
323 delete ReturnBlock.getBlock();
324 ReturnBlock = JumpDest();
325 } else
326 EmitBlock(ReturnBlock.getBlock());
327 return llvm::DebugLoc();
330 // Otherwise, if the return block is the target of a single direct
331 // branch then we can just put the code in that block instead. This
332 // cleans up functions which started with a unified return block.
333 if (ReturnBlock.getBlock()->hasOneUse()) {
334 llvm::BranchInst *BI =
335 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
336 if (BI && BI->isUnconditional() &&
337 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
338 // Record/return the DebugLoc of the simple 'return' expression to be used
339 // later by the actual 'ret' instruction.
340 llvm::DebugLoc Loc = BI->getDebugLoc();
341 Builder.SetInsertPoint(BI->getParent());
342 BI->eraseFromParent();
343 delete ReturnBlock.getBlock();
344 ReturnBlock = JumpDest();
345 return Loc;
349 // FIXME: We are at an unreachable point, there is no reason to emit the block
350 // unless it has uses. However, we still need a place to put the debug
351 // region.end for now.
353 EmitBlock(ReturnBlock.getBlock());
354 return llvm::DebugLoc();
357 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
358 if (!BB) return;
359 if (!BB->use_empty()) {
360 CGF.CurFn->insert(CGF.CurFn->end(), BB);
361 return;
363 delete BB;
366 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
367 assert(BreakContinueStack.empty() &&
368 "mismatched push/pop in break/continue stack!");
369 assert(LifetimeExtendedCleanupStack.empty() &&
370 "mismatched push/pop of cleanups in EHStack!");
371 assert(DeferredDeactivationCleanupStack.empty() &&
372 "mismatched activate/deactivate of cleanups!");
374 if (CGM.shouldEmitConvergenceTokens()) {
375 ConvergenceTokenStack.pop_back();
376 assert(ConvergenceTokenStack.empty() &&
377 "mismatched push/pop in convergence stack!");
380 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
381 && NumSimpleReturnExprs == NumReturnExprs
382 && ReturnBlock.getBlock()->use_empty();
383 // Usually the return expression is evaluated before the cleanup
384 // code. If the function contains only a simple return statement,
385 // such as a constant, the location before the cleanup code becomes
386 // the last useful breakpoint in the function, because the simple
387 // return expression will be evaluated after the cleanup code. To be
388 // safe, set the debug location for cleanup code to the location of
389 // the return statement. Otherwise the cleanup code should be at the
390 // end of the function's lexical scope.
392 // If there are multiple branches to the return block, the branch
393 // instructions will get the location of the return statements and
394 // all will be fine.
395 if (CGDebugInfo *DI = getDebugInfo()) {
396 if (OnlySimpleReturnStmts)
397 DI->EmitLocation(Builder, LastStopPoint);
398 else
399 DI->EmitLocation(Builder, EndLoc);
402 // Pop any cleanups that might have been associated with the
403 // parameters. Do this in whatever block we're currently in; it's
404 // important to do this before we enter the return block or return
405 // edges will be *really* confused.
406 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
407 bool HasOnlyNoopCleanups =
408 HasCleanups && EHStack.containsOnlyNoopCleanups(PrologueCleanupDepth);
409 bool EmitRetDbgLoc = !HasCleanups || HasOnlyNoopCleanups;
411 std::optional<ApplyDebugLocation> OAL;
412 if (HasCleanups) {
413 // Make sure the line table doesn't jump back into the body for
414 // the ret after it's been at EndLoc.
415 if (CGDebugInfo *DI = getDebugInfo()) {
416 if (OnlySimpleReturnStmts)
417 DI->EmitLocation(Builder, EndLoc);
418 else
419 // We may not have a valid end location. Try to apply it anyway, and
420 // fall back to an artificial location if needed.
421 OAL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
424 PopCleanupBlocks(PrologueCleanupDepth);
427 // Emit function epilog (to return).
428 llvm::DebugLoc Loc = EmitReturnBlock();
430 if (ShouldInstrumentFunction()) {
431 if (CGM.getCodeGenOpts().InstrumentFunctions)
432 CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
433 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
434 CurFn->addFnAttr("instrument-function-exit-inlined",
435 "__cyg_profile_func_exit");
438 // Emit debug descriptor for function end.
439 if (CGDebugInfo *DI = getDebugInfo())
440 DI->EmitFunctionEnd(Builder, CurFn);
442 // Reset the debug location to that of the simple 'return' expression, if any
443 // rather than that of the end of the function's scope '}'.
444 ApplyDebugLocation AL(*this, Loc);
445 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
446 EmitEndEHSpec(CurCodeDecl);
448 assert(EHStack.empty() &&
449 "did not remove all scopes from cleanup stack!");
451 // If someone did an indirect goto, emit the indirect goto block at the end of
452 // the function.
453 if (IndirectBranch) {
454 EmitBlock(IndirectBranch->getParent());
455 Builder.ClearInsertionPoint();
458 // If some of our locals escaped, insert a call to llvm.localescape in the
459 // entry block.
460 if (!EscapedLocals.empty()) {
461 // Invert the map from local to index into a simple vector. There should be
462 // no holes.
463 SmallVector<llvm::Value *, 4> EscapeArgs;
464 EscapeArgs.resize(EscapedLocals.size());
465 for (auto &Pair : EscapedLocals)
466 EscapeArgs[Pair.second] = Pair.first;
467 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getOrInsertDeclaration(
468 &CGM.getModule(), llvm::Intrinsic::localescape);
469 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
472 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
473 llvm::Instruction *Ptr = AllocaInsertPt;
474 AllocaInsertPt = nullptr;
475 Ptr->eraseFromParent();
477 // PostAllocaInsertPt, if created, was lazily created when it was required,
478 // remove it now since it was just created for our own convenience.
479 if (PostAllocaInsertPt) {
480 llvm::Instruction *PostPtr = PostAllocaInsertPt;
481 PostAllocaInsertPt = nullptr;
482 PostPtr->eraseFromParent();
485 // If someone took the address of a label but never did an indirect goto, we
486 // made a zero entry PHI node, which is illegal, zap it now.
487 if (IndirectBranch) {
488 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
489 if (PN->getNumIncomingValues() == 0) {
490 PN->replaceAllUsesWith(llvm::PoisonValue::get(PN->getType()));
491 PN->eraseFromParent();
495 EmitIfUsed(*this, EHResumeBlock);
496 EmitIfUsed(*this, TerminateLandingPad);
497 EmitIfUsed(*this, TerminateHandler);
498 EmitIfUsed(*this, UnreachableBlock);
500 for (const auto &FuncletAndParent : TerminateFunclets)
501 EmitIfUsed(*this, FuncletAndParent.second);
503 if (CGM.getCodeGenOpts().EmitDeclMetadata)
504 EmitDeclMetadata();
506 for (const auto &R : DeferredReplacements) {
507 if (llvm::Value *Old = R.first) {
508 Old->replaceAllUsesWith(R.second);
509 cast<llvm::Instruction>(Old)->eraseFromParent();
512 DeferredReplacements.clear();
514 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
515 // PHIs if the current function is a coroutine. We don't do it for all
516 // functions as it may result in slight increase in numbers of instructions
517 // if compiled with no optimizations. We do it for coroutine as the lifetime
518 // of CleanupDestSlot alloca make correct coroutine frame building very
519 // difficult.
520 if (NormalCleanupDest.isValid() && isCoroutine()) {
521 llvm::DominatorTree DT(*CurFn);
522 llvm::PromoteMemToReg(
523 cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
524 NormalCleanupDest = Address::invalid();
527 // Scan function arguments for vector width.
528 for (llvm::Argument &A : CurFn->args())
529 if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
530 LargestVectorWidth =
531 std::max((uint64_t)LargestVectorWidth,
532 VT->getPrimitiveSizeInBits().getKnownMinValue());
534 // Update vector width based on return type.
535 if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
536 LargestVectorWidth =
537 std::max((uint64_t)LargestVectorWidth,
538 VT->getPrimitiveSizeInBits().getKnownMinValue());
540 if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
541 LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
543 // Add the min-legal-vector-width attribute. This contains the max width from:
544 // 1. min-vector-width attribute used in the source program.
545 // 2. Any builtins used that have a vector width specified.
546 // 3. Values passed in and out of inline assembly.
547 // 4. Width of vector arguments and return types for this function.
548 // 5. Width of vector arguments and return types for functions called by this
549 // function.
550 if (getContext().getTargetInfo().getTriple().isX86())
551 CurFn->addFnAttr("min-legal-vector-width",
552 llvm::utostr(LargestVectorWidth));
554 // If we generated an unreachable return block, delete it now.
555 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
556 Builder.ClearInsertionPoint();
557 ReturnBlock.getBlock()->eraseFromParent();
559 if (ReturnValue.isValid()) {
560 auto *RetAlloca =
561 dyn_cast<llvm::AllocaInst>(ReturnValue.emitRawPointer(*this));
562 if (RetAlloca && RetAlloca->use_empty()) {
563 RetAlloca->eraseFromParent();
564 ReturnValue = Address::invalid();
569 /// ShouldInstrumentFunction - Return true if the current function should be
570 /// instrumented with __cyg_profile_func_* calls
571 bool CodeGenFunction::ShouldInstrumentFunction() {
572 if (!CGM.getCodeGenOpts().InstrumentFunctions &&
573 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
574 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
575 return false;
576 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
577 return false;
578 return true;
581 bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
582 if (!CurFuncDecl)
583 return false;
584 return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
587 /// ShouldXRayInstrument - Return true if the current function should be
588 /// instrumented with XRay nop sleds.
589 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
590 return CGM.getCodeGenOpts().XRayInstrumentFunctions;
593 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
594 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
595 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
596 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
597 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
598 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
599 XRayInstrKind::Custom);
602 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
603 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
604 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
605 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
606 XRayInstrKind::Typed);
609 llvm::ConstantInt *
610 CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const {
611 // Remove any (C++17) exception specifications, to allow calling e.g. a
612 // noexcept function through a non-noexcept pointer.
613 if (!Ty->isFunctionNoProtoType())
614 Ty = getContext().getFunctionTypeWithExceptionSpec(Ty, EST_None);
615 std::string Mangled;
616 llvm::raw_string_ostream Out(Mangled);
617 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out, false);
618 return llvm::ConstantInt::get(
619 CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled)));
622 void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
623 llvm::Function *Fn) {
624 if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
625 return;
627 llvm::LLVMContext &Context = getLLVMContext();
629 CGM.GenKernelArgMetadata(Fn, FD, this);
631 if (!(getLangOpts().OpenCL ||
632 (getLangOpts().CUDA &&
633 getContext().getTargetInfo().getTriple().isSPIRV())))
634 return;
636 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
637 QualType HintQTy = A->getTypeHint();
638 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
639 bool IsSignedInteger =
640 HintQTy->isSignedIntegerType() ||
641 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
642 llvm::Metadata *AttrMDArgs[] = {
643 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
644 CGM.getTypes().ConvertType(A->getTypeHint()))),
645 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
646 llvm::IntegerType::get(Context, 32),
647 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
648 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
651 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
652 llvm::Metadata *AttrMDArgs[] = {
653 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
654 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
655 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
656 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
659 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
660 llvm::Metadata *AttrMDArgs[] = {
661 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
662 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
663 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
664 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
667 if (const OpenCLIntelReqdSubGroupSizeAttr *A =
668 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
669 llvm::Metadata *AttrMDArgs[] = {
670 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
671 Fn->setMetadata("intel_reqd_sub_group_size",
672 llvm::MDNode::get(Context, AttrMDArgs));
676 /// Determine whether the function F ends with a return stmt.
677 static bool endsWithReturn(const Decl* F) {
678 const Stmt *Body = nullptr;
679 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
680 Body = FD->getBody();
681 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
682 Body = OMD->getBody();
684 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
685 auto LastStmt = CS->body_rbegin();
686 if (LastStmt != CS->body_rend())
687 return isa<ReturnStmt>(*LastStmt);
689 return false;
692 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
693 if (SanOpts.has(SanitizerKind::Thread)) {
694 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
695 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
699 /// Check if the return value of this function requires sanitization.
700 bool CodeGenFunction::requiresReturnValueCheck() const {
701 return requiresReturnValueNullabilityCheck() ||
702 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
703 CurCodeDecl->getAttr<ReturnsNonNullAttr>());
706 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
707 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
708 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
709 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
710 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
711 return false;
713 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
714 return false;
716 if (MD->getNumParams() == 2) {
717 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
718 if (!PT || !PT->isVoidPointerType() ||
719 !PT->getPointeeType().isConstQualified())
720 return false;
723 return true;
726 bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
727 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
728 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
731 bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
732 return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
733 getTarget().getCXXABI().isMicrosoft() &&
734 llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) {
735 return isInAllocaArgument(CGM.getCXXABI(), P->getType());
739 /// Return the UBSan prologue signature for \p FD if one is available.
740 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
741 const FunctionDecl *FD) {
742 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
743 if (!MD->isStatic())
744 return nullptr;
745 return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
748 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
749 llvm::Function *Fn,
750 const CGFunctionInfo &FnInfo,
751 const FunctionArgList &Args,
752 SourceLocation Loc,
753 SourceLocation StartLoc) {
754 assert(!CurFn &&
755 "Do not use a CodeGenFunction object for more than one function");
757 const Decl *D = GD.getDecl();
759 DidCallStackSave = false;
760 CurCodeDecl = D;
761 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
762 if (FD && FD->usesSEHTry())
763 CurSEHParent = GD;
764 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
765 FnRetTy = RetTy;
766 CurFn = Fn;
767 CurFnInfo = &FnInfo;
768 assert(CurFn->isDeclaration() && "Function already has body?");
770 // If this function is ignored for any of the enabled sanitizers,
771 // disable the sanitizer for the function.
772 do {
773 #define SANITIZER(NAME, ID) \
774 if (SanOpts.empty()) \
775 break; \
776 if (SanOpts.has(SanitizerKind::ID)) \
777 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
778 SanOpts.set(SanitizerKind::ID, false);
780 #include "clang/Basic/Sanitizers.def"
781 #undef SANITIZER
782 } while (false);
784 if (D) {
785 const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
786 SanitizerMask no_sanitize_mask;
787 bool NoSanitizeCoverage = false;
789 for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
790 no_sanitize_mask |= Attr->getMask();
791 // SanitizeCoverage is not handled by SanOpts.
792 if (Attr->hasCoverage())
793 NoSanitizeCoverage = true;
796 // Apply the no_sanitize* attributes to SanOpts.
797 SanOpts.Mask &= ~no_sanitize_mask;
798 if (no_sanitize_mask & SanitizerKind::Address)
799 SanOpts.set(SanitizerKind::KernelAddress, false);
800 if (no_sanitize_mask & SanitizerKind::KernelAddress)
801 SanOpts.set(SanitizerKind::Address, false);
802 if (no_sanitize_mask & SanitizerKind::HWAddress)
803 SanOpts.set(SanitizerKind::KernelHWAddress, false);
804 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
805 SanOpts.set(SanitizerKind::HWAddress, false);
807 if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
808 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
810 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
811 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
813 // Some passes need the non-negated no_sanitize attribute. Pass them on.
814 if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
815 if (no_sanitize_mask & SanitizerKind::Thread)
816 Fn->addFnAttr("no_sanitize_thread");
820 if (ShouldSkipSanitizerInstrumentation()) {
821 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
822 } else {
823 // Apply sanitizer attributes to the function.
824 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
825 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
826 if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
827 SanitizerKind::KernelHWAddress))
828 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
829 if (SanOpts.has(SanitizerKind::MemtagStack))
830 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
831 if (SanOpts.has(SanitizerKind::Thread))
832 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
833 if (SanOpts.has(SanitizerKind::Type))
834 Fn->addFnAttr(llvm::Attribute::SanitizeType);
835 if (SanOpts.has(SanitizerKind::NumericalStability))
836 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
837 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
838 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
840 if (SanOpts.has(SanitizerKind::SafeStack))
841 Fn->addFnAttr(llvm::Attribute::SafeStack);
842 if (SanOpts.has(SanitizerKind::ShadowCallStack))
843 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
845 if (SanOpts.has(SanitizerKind::Realtime))
846 if (FD && FD->getASTContext().hasAnyFunctionEffects())
847 for (const FunctionEffectWithCondition &Fe : FD->getFunctionEffects()) {
848 if (Fe.Effect.kind() == FunctionEffect::Kind::NonBlocking)
849 Fn->addFnAttr(llvm::Attribute::SanitizeRealtime);
850 else if (Fe.Effect.kind() == FunctionEffect::Kind::Blocking)
851 Fn->addFnAttr(llvm::Attribute::SanitizeRealtimeBlocking);
854 // Apply fuzzing attribute to the function.
855 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
856 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
858 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
859 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
860 if (SanOpts.has(SanitizerKind::Thread)) {
861 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
862 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
863 if (OMD->getMethodFamily() == OMF_dealloc ||
864 OMD->getMethodFamily() == OMF_initialize ||
865 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
866 markAsIgnoreThreadCheckingAtRuntime(Fn);
871 // Ignore unrelated casts in STL allocate() since the allocator must cast
872 // from void* to T* before object initialization completes. Don't match on the
873 // namespace because not all allocators are in std::
874 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
875 if (matchesStlAllocatorFn(D, getContext()))
876 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
879 // Ignore null checks in coroutine functions since the coroutines passes
880 // are not aware of how to move the extra UBSan instructions across the split
881 // coroutine boundaries.
882 if (D && SanOpts.has(SanitizerKind::Null))
883 if (FD && FD->getBody() &&
884 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
885 SanOpts.Mask &= ~SanitizerKind::Null;
887 // Add pointer authentication attributes.
888 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
889 if (CodeGenOpts.PointerAuth.ReturnAddresses)
890 Fn->addFnAttr("ptrauth-returns");
891 if (CodeGenOpts.PointerAuth.FunctionPointers)
892 Fn->addFnAttr("ptrauth-calls");
893 if (CodeGenOpts.PointerAuth.AuthTraps)
894 Fn->addFnAttr("ptrauth-auth-traps");
895 if (CodeGenOpts.PointerAuth.IndirectGotos)
896 Fn->addFnAttr("ptrauth-indirect-gotos");
897 if (CodeGenOpts.PointerAuth.AArch64JumpTableHardening)
898 Fn->addFnAttr("aarch64-jump-table-hardening");
900 // Apply xray attributes to the function (as a string, for now)
901 bool AlwaysXRayAttr = false;
902 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
903 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
904 XRayInstrKind::FunctionEntry) ||
905 CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
906 XRayInstrKind::FunctionExit)) {
907 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
908 Fn->addFnAttr("function-instrument", "xray-always");
909 AlwaysXRayAttr = true;
911 if (XRayAttr->neverXRayInstrument())
912 Fn->addFnAttr("function-instrument", "xray-never");
913 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
914 if (ShouldXRayInstrumentFunction())
915 Fn->addFnAttr("xray-log-args",
916 llvm::utostr(LogArgs->getArgumentCount()));
918 } else {
919 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
920 Fn->addFnAttr(
921 "xray-instruction-threshold",
922 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
925 if (ShouldXRayInstrumentFunction()) {
926 if (CGM.getCodeGenOpts().XRayIgnoreLoops)
927 Fn->addFnAttr("xray-ignore-loops");
929 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
930 XRayInstrKind::FunctionExit))
931 Fn->addFnAttr("xray-skip-exit");
933 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
934 XRayInstrKind::FunctionEntry))
935 Fn->addFnAttr("xray-skip-entry");
937 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
938 if (FuncGroups > 1) {
939 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
940 CurFn->getName().bytes_end());
941 auto Group = crc32(FuncName) % FuncGroups;
942 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
943 !AlwaysXRayAttr)
944 Fn->addFnAttr("function-instrument", "xray-never");
948 if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone) {
949 switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
950 case ProfileList::Skip:
951 Fn->addFnAttr(llvm::Attribute::SkipProfile);
952 break;
953 case ProfileList::Forbid:
954 Fn->addFnAttr(llvm::Attribute::NoProfile);
955 break;
956 case ProfileList::Allow:
957 break;
961 unsigned Count, Offset;
962 if (const auto *Attr =
963 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
964 Count = Attr->getCount();
965 Offset = Attr->getOffset();
966 } else {
967 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
968 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
970 if (Count && Offset <= Count) {
971 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
972 if (Offset)
973 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
975 // Instruct that functions for COFF/CodeView targets should start with a
976 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
977 // backends as they don't need it -- instructions on these architectures are
978 // always atomically patchable at runtime.
979 if (CGM.getCodeGenOpts().HotPatch &&
980 getContext().getTargetInfo().getTriple().isX86() &&
981 getContext().getTargetInfo().getTriple().getEnvironment() !=
982 llvm::Triple::CODE16)
983 Fn->addFnAttr("patchable-function", "prologue-short-redirect");
985 // Add no-jump-tables value.
986 if (CGM.getCodeGenOpts().NoUseJumpTables)
987 Fn->addFnAttr("no-jump-tables", "true");
989 // Add no-inline-line-tables value.
990 if (CGM.getCodeGenOpts().NoInlineLineTables)
991 Fn->addFnAttr("no-inline-line-tables");
993 // Add profile-sample-accurate value.
994 if (CGM.getCodeGenOpts().ProfileSampleAccurate)
995 Fn->addFnAttr("profile-sample-accurate");
997 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
998 Fn->addFnAttr("use-sample-profile");
1000 if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
1001 Fn->addFnAttr("cfi-canonical-jump-table");
1003 if (D && D->hasAttr<NoProfileFunctionAttr>())
1004 Fn->addFnAttr(llvm::Attribute::NoProfile);
1006 if (D && D->hasAttr<HybridPatchableAttr>())
1007 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
1009 if (D) {
1010 // Function attributes take precedence over command line flags.
1011 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1012 switch (A->getThunkType()) {
1013 case FunctionReturnThunksAttr::Kind::Keep:
1014 break;
1015 case FunctionReturnThunksAttr::Kind::Extern:
1016 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1017 break;
1019 } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1020 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1023 if (FD && (getLangOpts().OpenCL ||
1024 (getLangOpts().CUDA &&
1025 getContext().getTargetInfo().getTriple().isSPIRV()) ||
1026 ((getLangOpts().HIP || getLangOpts().OffloadViaLLVM) &&
1027 getLangOpts().CUDAIsDevice))) {
1028 // Add metadata for a kernel function.
1029 EmitKernelMetadata(FD, Fn);
1032 if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
1033 Fn->setMetadata("clspv_libclc_builtin",
1034 llvm::MDNode::get(getLLVMContext(), {}));
1037 // If we are checking function types, emit a function type signature as
1038 // prologue data.
1039 if (FD && SanOpts.has(SanitizerKind::Function)) {
1040 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1041 llvm::LLVMContext &Ctx = Fn->getContext();
1042 llvm::MDBuilder MDB(Ctx);
1043 Fn->setMetadata(
1044 llvm::LLVMContext::MD_func_sanitize,
1045 MDB.createRTTIPointerPrologue(
1046 PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
1050 // If we're checking nullability, we need to know whether we can check the
1051 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1052 if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1053 auto Nullability = FnRetTy->getNullability();
1054 if (Nullability && *Nullability == NullabilityKind::NonNull &&
1055 !FnRetTy->isRecordType()) {
1056 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1057 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1058 RetValNullabilityPrecondition =
1059 llvm::ConstantInt::getTrue(getLLVMContext());
1063 // If we're in C++ mode and the function name is "main", it is guaranteed
1064 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1065 // used within a program").
1067 // OpenCL C 2.0 v2.2-11 s6.9.i:
1068 // Recursion is not supported.
1070 // HLSL
1071 // Recursion is not supported.
1073 // SYCL v1.2.1 s3.10:
1074 // kernels cannot include RTTI information, exception classes,
1075 // recursive code, virtual functions or make use of C++ libraries that
1076 // are not compiled for the device.
1077 if (FD &&
1078 ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
1079 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
1080 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1081 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1083 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1084 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1085 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1086 Builder.setDefaultConstrainedRounding(RM);
1087 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1088 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1089 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1090 RM != llvm::RoundingMode::NearestTiesToEven))) {
1091 Builder.setIsFPConstrained(true);
1092 Fn->addFnAttr(llvm::Attribute::StrictFP);
1095 // If a custom alignment is used, force realigning to this alignment on
1096 // any main function which certainly will need it.
1097 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1098 CGM.getCodeGenOpts().StackAlignment))
1099 Fn->addFnAttr("stackrealign");
1101 // "main" doesn't need to zero out call-used registers.
1102 if (FD && FD->isMain())
1103 Fn->removeFnAttr("zero-call-used-regs");
1105 // Add vscale_range attribute if appropriate.
1106 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
1107 getContext().getTargetInfo().getVScaleRange(
1108 getLangOpts(), FD ? IsArmStreamingFunction(FD, true) : false);
1109 if (VScaleRange) {
1110 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1111 getLLVMContext(), VScaleRange->first, VScaleRange->second));
1114 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1116 // Create a marker to make it easy to insert allocas into the entryblock
1117 // later. Don't create this with the builder, because we don't want it
1118 // folded.
1119 llvm::Value *Poison = llvm::PoisonValue::get(Int32Ty);
1120 AllocaInsertPt = new llvm::BitCastInst(Poison, Int32Ty, "allocapt", EntryBB);
1122 ReturnBlock = getJumpDestInCurrentScope("return");
1124 Builder.SetInsertPoint(EntryBB);
1126 // If we're checking the return value, allocate space for a pointer to a
1127 // precise source location of the checked return statement.
1128 if (requiresReturnValueCheck()) {
1129 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1130 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1131 ReturnLocation);
1134 // Emit subprogram debug descriptor.
1135 if (CGDebugInfo *DI = getDebugInfo()) {
1136 // Reconstruct the type from the argument list so that implicit parameters,
1137 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1138 // convention.
1139 DI->emitFunctionStart(GD, Loc, StartLoc,
1140 DI->getFunctionType(FD, RetTy, Args), CurFn,
1141 CurFuncIsThunk);
1144 if (ShouldInstrumentFunction()) {
1145 if (CGM.getCodeGenOpts().InstrumentFunctions)
1146 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1147 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1148 CurFn->addFnAttr("instrument-function-entry-inlined",
1149 "__cyg_profile_func_enter");
1150 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1151 CurFn->addFnAttr("instrument-function-entry-inlined",
1152 "__cyg_profile_func_enter_bare");
1155 // Since emitting the mcount call here impacts optimizations such as function
1156 // inlining, we just add an attribute to insert a mcount call in backend.
1157 // The attribute "counting-function" is set to mcount function name which is
1158 // architecture dependent.
1159 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1160 // Calls to fentry/mcount should not be generated if function has
1161 // the no_instrument_function attribute.
1162 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1163 if (CGM.getCodeGenOpts().CallFEntry)
1164 Fn->addFnAttr("fentry-call", "true");
1165 else {
1166 Fn->addFnAttr("instrument-function-entry-inlined",
1167 getTarget().getMCountName());
1169 if (CGM.getCodeGenOpts().MNopMCount) {
1170 if (!CGM.getCodeGenOpts().CallFEntry)
1171 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1172 << "-mnop-mcount" << "-mfentry";
1173 Fn->addFnAttr("mnop-mcount");
1176 if (CGM.getCodeGenOpts().RecordMCount) {
1177 if (!CGM.getCodeGenOpts().CallFEntry)
1178 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1179 << "-mrecord-mcount" << "-mfentry";
1180 Fn->addFnAttr("mrecord-mcount");
1185 if (CGM.getCodeGenOpts().PackedStack) {
1186 if (getContext().getTargetInfo().getTriple().getArch() !=
1187 llvm::Triple::systemz)
1188 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1189 << "-mpacked-stack";
1190 Fn->addFnAttr("packed-stack");
1193 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1194 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1195 Fn->addFnAttr("warn-stack-size",
1196 std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1198 if (RetTy->isVoidType()) {
1199 // Void type; nothing to return.
1200 ReturnValue = Address::invalid();
1202 // Count the implicit return.
1203 if (!endsWithReturn(D))
1204 ++NumReturnExprs;
1205 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1206 // Indirect return; emit returned value directly into sret slot.
1207 // This reduces code size, and affects correctness in C++.
1208 auto AI = CurFn->arg_begin();
1209 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1210 ++AI;
1211 ReturnValue = makeNaturalAddressForPointer(
1212 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1213 nullptr, nullptr, KnownNonNull);
1214 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1215 ReturnValuePointer =
1216 CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
1217 Builder.CreateStore(ReturnValue.emitRawPointer(*this),
1218 ReturnValuePointer);
1220 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1221 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1222 // Load the sret pointer from the argument struct and return into that.
1223 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1224 llvm::Function::arg_iterator EI = CurFn->arg_end();
1225 --EI;
1226 llvm::Value *Addr = Builder.CreateStructGEP(
1227 CurFnInfo->getArgStruct(), &*EI, Idx);
1228 llvm::Type *Ty =
1229 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1230 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
1231 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1232 ReturnValue = Address(Addr, ConvertType(RetTy),
1233 CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
1234 } else {
1235 ReturnValue = CreateIRTemp(RetTy, "retval");
1237 // Tell the epilog emitter to autorelease the result. We do this
1238 // now so that various specialized functions can suppress it
1239 // during their IR-generation.
1240 if (getLangOpts().ObjCAutoRefCount &&
1241 !CurFnInfo->isReturnsRetained() &&
1242 RetTy->isObjCRetainableType())
1243 AutoreleaseResult = true;
1246 EmitStartEHSpec(CurCodeDecl);
1248 PrologueCleanupDepth = EHStack.stable_begin();
1250 // Emit OpenMP specific initialization of the device functions.
1251 if (getLangOpts().OpenMP && CurCodeDecl)
1252 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1254 if (FD && getLangOpts().HLSL) {
1255 // Handle emitting HLSL entry functions.
1256 if (FD->hasAttr<HLSLShaderAttr>()) {
1257 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1259 CGM.getHLSLRuntime().setHLSLFunctionAttributes(FD, Fn);
1262 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1264 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1265 MD && !MD->isStatic()) {
1266 bool IsInLambda =
1267 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1268 if (MD->isImplicitObjectMemberFunction())
1269 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1270 if (IsInLambda) {
1271 // We're in a lambda; figure out the captures.
1272 MD->getParent()->getCaptureFields(LambdaCaptureFields,
1273 LambdaThisCaptureField);
1274 if (LambdaThisCaptureField) {
1275 // If the lambda captures the object referred to by '*this' - either by
1276 // value or by reference, make sure CXXThisValue points to the correct
1277 // object.
1279 // Get the lvalue for the field (which is a copy of the enclosing object
1280 // or contains the address of the enclosing object).
1281 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1282 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1283 // If the enclosing object was captured by value, just use its
1284 // address. Sign this pointer.
1285 CXXThisValue = ThisFieldLValue.getPointer(*this);
1286 } else {
1287 // Load the lvalue pointed to by the field, since '*this' was captured
1288 // by reference.
1289 CXXThisValue =
1290 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1293 for (auto *FD : MD->getParent()->fields()) {
1294 if (FD->hasCapturedVLAType()) {
1295 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1296 SourceLocation()).getScalarVal();
1297 auto VAT = FD->getCapturedVLAType();
1298 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1301 } else if (MD->isImplicitObjectMemberFunction()) {
1302 // Not in a lambda; just use 'this' from the method.
1303 // FIXME: Should we generate a new load for each use of 'this'? The
1304 // fast register allocator would be happier...
1305 CXXThisValue = CXXABIThisValue;
1308 // Check the 'this' pointer once per function, if it's available.
1309 if (CXXABIThisValue) {
1310 SanitizerSet SkippedChecks;
1311 SkippedChecks.set(SanitizerKind::ObjectSize, true);
1312 QualType ThisTy = MD->getThisType();
1314 // If this is the call operator of a lambda with no captures, it
1315 // may have a static invoker function, which may call this operator with
1316 // a null 'this' pointer.
1317 if (isLambdaCallOperator(MD) && MD->getParent()->isCapturelessLambda())
1318 SkippedChecks.set(SanitizerKind::Null, true);
1320 EmitTypeCheck(
1321 isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1322 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1326 // If any of the arguments have a variably modified type, make sure to
1327 // emit the type size, but only if the function is not naked. Naked functions
1328 // have no prolog to run this evaluation.
1329 if (!FD || !FD->hasAttr<NakedAttr>()) {
1330 for (const VarDecl *VD : Args) {
1331 // Dig out the type as written from ParmVarDecls; it's unclear whether
1332 // the standard (C99 6.9.1p10) requires this, but we're following the
1333 // precedent set by gcc.
1334 QualType Ty;
1335 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1336 Ty = PVD->getOriginalType();
1337 else
1338 Ty = VD->getType();
1340 if (Ty->isVariablyModifiedType())
1341 EmitVariablyModifiedType(Ty);
1344 // Emit a location at the end of the prologue.
1345 if (CGDebugInfo *DI = getDebugInfo())
1346 DI->EmitLocation(Builder, StartLoc);
1347 // TODO: Do we need to handle this in two places like we do with
1348 // target-features/target-cpu?
1349 if (CurFuncDecl)
1350 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1351 LargestVectorWidth = VecWidth->getVectorWidth();
1353 if (CGM.shouldEmitConvergenceTokens())
1354 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1357 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1358 incrementProfileCounter(Body);
1359 maybeCreateMCDCCondBitmap();
1360 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1361 EmitCompoundStmtWithoutScope(*S);
1362 else
1363 EmitStmt(Body);
1366 /// When instrumenting to collect profile data, the counts for some blocks
1367 /// such as switch cases need to not include the fall-through counts, so
1368 /// emit a branch around the instrumentation code. When not instrumenting,
1369 /// this just calls EmitBlock().
1370 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1371 const Stmt *S) {
1372 llvm::BasicBlock *SkipCountBB = nullptr;
1373 // Do not skip over the instrumentation when single byte coverage mode is
1374 // enabled.
1375 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1376 !llvm::EnableSingleByteCoverage) {
1377 // When instrumenting for profiling, the fallthrough to certain
1378 // statements needs to skip over the instrumentation code so that we
1379 // get an accurate count.
1380 SkipCountBB = createBasicBlock("skipcount");
1381 EmitBranch(SkipCountBB);
1383 EmitBlock(BB);
1384 uint64_t CurrentCount = getCurrentProfileCount();
1385 incrementProfileCounter(S);
1386 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1387 if (SkipCountBB)
1388 EmitBlock(SkipCountBB);
1391 /// Tries to mark the given function nounwind based on the
1392 /// non-existence of any throwing calls within it. We believe this is
1393 /// lightweight enough to do at -O0.
1394 static void TryMarkNoThrow(llvm::Function *F) {
1395 // LLVM treats 'nounwind' on a function as part of the type, so we
1396 // can't do this on functions that can be overwritten.
1397 if (F->isInterposable()) return;
1399 for (llvm::BasicBlock &BB : *F)
1400 for (llvm::Instruction &I : BB)
1401 if (I.mayThrow())
1402 return;
1404 F->setDoesNotThrow();
1407 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1408 FunctionArgList &Args) {
1409 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1410 QualType ResTy = FD->getReturnType();
1412 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1413 if (MD && MD->isImplicitObjectMemberFunction()) {
1414 if (CGM.getCXXABI().HasThisReturn(GD))
1415 ResTy = MD->getThisType();
1416 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1417 ResTy = CGM.getContext().VoidPtrTy;
1418 CGM.getCXXABI().buildThisParam(*this, Args);
1421 // The base version of an inheriting constructor whose constructed base is a
1422 // virtual base is not passed any arguments (because it doesn't actually call
1423 // the inherited constructor).
1424 bool PassedParams = true;
1425 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1426 if (auto Inherited = CD->getInheritedConstructor())
1427 PassedParams =
1428 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1430 if (PassedParams) {
1431 for (auto *Param : FD->parameters()) {
1432 Args.push_back(Param);
1433 if (!Param->hasAttr<PassObjectSizeAttr>())
1434 continue;
1436 auto *Implicit = ImplicitParamDecl::Create(
1437 getContext(), Param->getDeclContext(), Param->getLocation(),
1438 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1439 SizeArguments[Param] = Implicit;
1440 Args.push_back(Implicit);
1444 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1445 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1447 return ResTy;
1450 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1451 const CGFunctionInfo &FnInfo) {
1452 assert(Fn && "generating code for null Function");
1453 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1454 CurGD = GD;
1456 FunctionArgList Args;
1457 QualType ResTy = BuildFunctionArgList(GD, Args);
1459 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
1461 if (FD->isInlineBuiltinDeclaration()) {
1462 // When generating code for a builtin with an inline declaration, use a
1463 // mangled name to hold the actual body, while keeping an external
1464 // definition in case the function pointer is referenced somewhere.
1465 std::string FDInlineName = (Fn->getName() + ".inline").str();
1466 llvm::Module *M = Fn->getParent();
1467 llvm::Function *Clone = M->getFunction(FDInlineName);
1468 if (!Clone) {
1469 Clone = llvm::Function::Create(Fn->getFunctionType(),
1470 llvm::GlobalValue::InternalLinkage,
1471 Fn->getAddressSpace(), FDInlineName, M);
1472 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1474 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1475 Fn = Clone;
1476 } else {
1477 // Detect the unusual situation where an inline version is shadowed by a
1478 // non-inline version. In that case we should pick the external one
1479 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1480 // to detect that situation before we reach codegen, so do some late
1481 // replacement.
1482 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1483 PD = PD->getPreviousDecl()) {
1484 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1485 std::string FDInlineName = (Fn->getName() + ".inline").str();
1486 llvm::Module *M = Fn->getParent();
1487 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1488 Clone->replaceAllUsesWith(Fn);
1489 Clone->eraseFromParent();
1491 break;
1496 // Check if we should generate debug info for this function.
1497 if (FD->hasAttr<NoDebugAttr>()) {
1498 // Clear non-distinct debug info that was possibly attached to the function
1499 // due to an earlier declaration without the nodebug attribute
1500 Fn->setSubprogram(nullptr);
1501 // Disable debug info indefinitely for this function
1502 DebugInfo = nullptr;
1505 // The function might not have a body if we're generating thunks for a
1506 // function declaration.
1507 SourceRange BodyRange;
1508 if (Stmt *Body = FD->getBody())
1509 BodyRange = Body->getSourceRange();
1510 else
1511 BodyRange = FD->getLocation();
1512 CurEHLocation = BodyRange.getEnd();
1514 // Use the location of the start of the function to determine where
1515 // the function definition is located. By default use the location
1516 // of the declaration as the location for the subprogram. A function
1517 // may lack a declaration in the source code if it is created by code
1518 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1519 SourceLocation Loc = FD->getLocation();
1521 // If this is a function specialization then use the pattern body
1522 // as the location for the function.
1523 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1524 if (SpecDecl->hasBody(SpecDecl))
1525 Loc = SpecDecl->getLocation();
1527 Stmt *Body = FD->getBody();
1529 if (Body) {
1530 // Coroutines always emit lifetime markers.
1531 if (isa<CoroutineBodyStmt>(Body))
1532 ShouldEmitLifetimeMarkers = true;
1534 // Initialize helper which will detect jumps which can cause invalid
1535 // lifetime markers.
1536 if (ShouldEmitLifetimeMarkers)
1537 Bypasses.Init(Body);
1540 // Emit the standard function prologue.
1541 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1543 // Save parameters for coroutine function.
1544 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1545 llvm::append_range(FnArgs, FD->parameters());
1547 // Ensure that the function adheres to the forward progress guarantee, which
1548 // is required by certain optimizations.
1549 // In C++11 and up, the attribute will be removed if the body contains a
1550 // trivial empty loop.
1551 if (checkIfFunctionMustProgress())
1552 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1554 // Generate the body of the function.
1555 PGO.assignRegionCounters(GD, CurFn);
1556 if (isa<CXXDestructorDecl>(FD))
1557 EmitDestructorBody(Args);
1558 else if (isa<CXXConstructorDecl>(FD))
1559 EmitConstructorBody(Args);
1560 else if (getLangOpts().CUDA &&
1561 !getLangOpts().CUDAIsDevice &&
1562 FD->hasAttr<CUDAGlobalAttr>())
1563 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1564 else if (isa<CXXMethodDecl>(FD) &&
1565 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1566 // The lambda static invoker function is special, because it forwards or
1567 // clones the body of the function call operator (but is actually static).
1568 EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1569 } else if (isa<CXXMethodDecl>(FD) &&
1570 isLambdaCallOperator(cast<CXXMethodDecl>(FD)) &&
1571 !FnInfo.isDelegateCall() &&
1572 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1573 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1574 // If emitting a lambda with static invoker on X86 Windows, change
1575 // the call operator body.
1576 // Make sure that this is a call operator with an inalloca arg and check
1577 // for delegate call to make sure this is the original call op and not the
1578 // new forwarding function for the static invoker.
1579 EmitLambdaInAllocaCallOpBody(cast<CXXMethodDecl>(FD));
1580 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1581 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1582 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1583 // Implicit copy-assignment gets the same special treatment as implicit
1584 // copy-constructors.
1585 emitImplicitAssignmentOperatorBody(Args);
1586 } else if (Body) {
1587 EmitFunctionBody(Body);
1588 } else
1589 llvm_unreachable("no definition for emitted function");
1591 // C++11 [stmt.return]p2:
1592 // Flowing off the end of a function [...] results in undefined behavior in
1593 // a value-returning function.
1594 // C11 6.9.1p12:
1595 // If the '}' that terminates a function is reached, and the value of the
1596 // function call is used by the caller, the behavior is undefined.
1597 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1598 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1599 bool ShouldEmitUnreachable =
1600 CGM.getCodeGenOpts().StrictReturn ||
1601 !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1602 if (SanOpts.has(SanitizerKind::Return)) {
1603 SanitizerScope SanScope(this);
1604 llvm::Value *IsFalse = Builder.getFalse();
1605 EmitCheck(std::make_pair(IsFalse, SanitizerKind::SO_Return),
1606 SanitizerHandler::MissingReturn,
1607 EmitCheckSourceLocation(FD->getLocation()), {});
1608 } else if (ShouldEmitUnreachable) {
1609 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1610 EmitTrapCall(llvm::Intrinsic::trap);
1612 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1613 Builder.CreateUnreachable();
1614 Builder.ClearInsertionPoint();
1618 // Emit the standard function epilogue.
1619 FinishFunction(BodyRange.getEnd());
1621 PGO.verifyCounterMap();
1623 // If we haven't marked the function nothrow through other means, do
1624 // a quick pass now to see if we can.
1625 if (!CurFn->doesNotThrow())
1626 TryMarkNoThrow(CurFn);
1629 /// ContainsLabel - Return true if the statement contains a label in it. If
1630 /// this statement is not executed normally, it not containing a label means
1631 /// that we can just remove the code.
1632 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1633 // Null statement, not a label!
1634 if (!S) return false;
1636 // If this is a label, we have to emit the code, consider something like:
1637 // if (0) { ... foo: bar(); } goto foo;
1639 // TODO: If anyone cared, we could track __label__'s, since we know that you
1640 // can't jump to one from outside their declared region.
1641 if (isa<LabelStmt>(S))
1642 return true;
1644 // If this is a case/default statement, and we haven't seen a switch, we have
1645 // to emit the code.
1646 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1647 return true;
1649 // If this is a switch statement, we want to ignore cases below it.
1650 if (isa<SwitchStmt>(S))
1651 IgnoreCaseStmts = true;
1653 // Scan subexpressions for verboten labels.
1654 for (const Stmt *SubStmt : S->children())
1655 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1656 return true;
1658 return false;
1661 /// containsBreak - Return true if the statement contains a break out of it.
1662 /// If the statement (recursively) contains a switch or loop with a break
1663 /// inside of it, this is fine.
1664 bool CodeGenFunction::containsBreak(const Stmt *S) {
1665 // Null statement, not a label!
1666 if (!S) return false;
1668 // If this is a switch or loop that defines its own break scope, then we can
1669 // include it and anything inside of it.
1670 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1671 isa<ForStmt>(S))
1672 return false;
1674 if (isa<BreakStmt>(S))
1675 return true;
1677 // Scan subexpressions for verboten breaks.
1678 for (const Stmt *SubStmt : S->children())
1679 if (containsBreak(SubStmt))
1680 return true;
1682 return false;
1685 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1686 if (!S) return false;
1688 // Some statement kinds add a scope and thus never add a decl to the current
1689 // scope. Note, this list is longer than the list of statements that might
1690 // have an unscoped decl nested within them, but this way is conservatively
1691 // correct even if more statement kinds are added.
1692 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1693 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1694 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1695 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1696 return false;
1698 if (isa<DeclStmt>(S))
1699 return true;
1701 for (const Stmt *SubStmt : S->children())
1702 if (mightAddDeclToScope(SubStmt))
1703 return true;
1705 return false;
1708 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1709 /// to a constant, or if it does but contains a label, return false. If it
1710 /// constant folds return true and set the boolean result in Result.
1711 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1712 bool &ResultBool,
1713 bool AllowLabels) {
1714 // If MC/DC is enabled, disable folding so that we can instrument all
1715 // conditions to yield complete test vectors. We still keep track of
1716 // folded conditions during region mapping and visualization.
1717 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1718 CGM.getCodeGenOpts().MCDCCoverage)
1719 return false;
1721 llvm::APSInt ResultInt;
1722 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1723 return false;
1725 ResultBool = ResultInt.getBoolValue();
1726 return true;
1729 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1730 /// to a constant, or if it does but contains a label, return false. If it
1731 /// constant folds return true and set the folded value.
1732 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1733 llvm::APSInt &ResultInt,
1734 bool AllowLabels) {
1735 // FIXME: Rename and handle conversion of other evaluatable things
1736 // to bool.
1737 Expr::EvalResult Result;
1738 if (!Cond->EvaluateAsInt(Result, getContext()))
1739 return false; // Not foldable, not integer or not fully evaluatable.
1741 llvm::APSInt Int = Result.Val.getInt();
1742 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1743 return false; // Contains a label.
1745 PGO.markStmtMaybeUsed(Cond);
1746 ResultInt = Int;
1747 return true;
1750 /// Strip parentheses and simplistic logical-NOT operators.
1751 const Expr *CodeGenFunction::stripCond(const Expr *C) {
1752 while (const UnaryOperator *Op = dyn_cast<UnaryOperator>(C->IgnoreParens())) {
1753 if (Op->getOpcode() != UO_LNot)
1754 break;
1755 C = Op->getSubExpr();
1757 return C->IgnoreParens();
1760 /// Determine whether the given condition is an instrumentable condition
1761 /// (i.e. no "&&" or "||").
1762 bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1763 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1764 return (!BOp || !BOp->isLogicalOp());
1767 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1768 /// increments a profile counter based on the semantics of the given logical
1769 /// operator opcode. This is used to instrument branch condition coverage for
1770 /// logical operators.
1771 void CodeGenFunction::EmitBranchToCounterBlock(
1772 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1773 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1774 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1775 // If not instrumenting, just emit a branch.
1776 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1777 if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1778 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1780 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1782 llvm::BasicBlock *ThenBlock = nullptr;
1783 llvm::BasicBlock *ElseBlock = nullptr;
1784 llvm::BasicBlock *NextBlock = nullptr;
1786 // Create the block we'll use to increment the appropriate counter.
1787 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1789 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1790 // means we need to evaluate the condition and increment the counter on TRUE:
1792 // if (Cond)
1793 // goto CounterIncrBlock;
1794 // else
1795 // goto FalseBlock;
1797 // CounterIncrBlock:
1798 // Counter++;
1799 // goto TrueBlock;
1801 if (LOp == BO_LAnd) {
1802 ThenBlock = CounterIncrBlock;
1803 ElseBlock = FalseBlock;
1804 NextBlock = TrueBlock;
1807 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1808 // we need to evaluate the condition and increment the counter on FALSE:
1810 // if (Cond)
1811 // goto TrueBlock;
1812 // else
1813 // goto CounterIncrBlock;
1815 // CounterIncrBlock:
1816 // Counter++;
1817 // goto FalseBlock;
1819 else if (LOp == BO_LOr) {
1820 ThenBlock = TrueBlock;
1821 ElseBlock = CounterIncrBlock;
1822 NextBlock = FalseBlock;
1823 } else {
1824 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1827 // Emit Branch based on condition.
1828 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1830 // Emit the block containing the counter increment(s).
1831 EmitBlock(CounterIncrBlock);
1833 // Increment corresponding counter; if index not provided, use Cond as index.
1834 incrementProfileCounter(CntrStmt);
1836 // Go to the next block.
1837 EmitBranch(NextBlock);
1840 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1841 /// statement) to the specified blocks. Based on the condition, this might try
1842 /// to simplify the codegen of the conditional based on the branch.
1843 /// \param LH The value of the likelihood attribute on the True branch.
1844 /// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1845 /// ConditionalOperator (ternary) through a recursive call for the operator's
1846 /// LHS and RHS nodes.
1847 void CodeGenFunction::EmitBranchOnBoolExpr(
1848 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1849 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp) {
1850 Cond = Cond->IgnoreParens();
1852 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1853 // Handle X && Y in a condition.
1854 if (CondBOp->getOpcode() == BO_LAnd) {
1855 MCDCLogOpStack.push_back(CondBOp);
1857 // If we have "1 && X", simplify the code. "0 && X" would have constant
1858 // folded if the case was simple enough.
1859 bool ConstantBool = false;
1860 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1861 ConstantBool) {
1862 // br(1 && X) -> br(X).
1863 incrementProfileCounter(CondBOp);
1864 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1865 FalseBlock, TrueCount, LH);
1866 MCDCLogOpStack.pop_back();
1867 return;
1870 // If we have "X && 1", simplify the code to use an uncond branch.
1871 // "X && 0" would have been constant folded to 0.
1872 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1873 ConstantBool) {
1874 // br(X && 1) -> br(X).
1875 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1876 FalseBlock, TrueCount, LH, CondBOp);
1877 MCDCLogOpStack.pop_back();
1878 return;
1881 // Emit the LHS as a conditional. If the LHS conditional is false, we
1882 // want to jump to the FalseBlock.
1883 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1884 // The counter tells us how often we evaluate RHS, and all of TrueCount
1885 // can be propagated to that branch.
1886 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1888 ConditionalEvaluation eval(*this);
1890 ApplyDebugLocation DL(*this, Cond);
1891 // Propagate the likelihood attribute like __builtin_expect
1892 // __builtin_expect(X && Y, 1) -> X and Y are likely
1893 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1894 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1895 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1896 EmitBlock(LHSTrue);
1899 incrementProfileCounter(CondBOp);
1900 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1902 // Any temporaries created here are conditional.
1903 eval.begin(*this);
1904 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1905 FalseBlock, TrueCount, LH);
1906 eval.end(*this);
1907 MCDCLogOpStack.pop_back();
1908 return;
1911 if (CondBOp->getOpcode() == BO_LOr) {
1912 MCDCLogOpStack.push_back(CondBOp);
1914 // If we have "0 || X", simplify the code. "1 || X" would have constant
1915 // folded if the case was simple enough.
1916 bool ConstantBool = false;
1917 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1918 !ConstantBool) {
1919 // br(0 || X) -> br(X).
1920 incrementProfileCounter(CondBOp);
1921 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1922 FalseBlock, TrueCount, LH);
1923 MCDCLogOpStack.pop_back();
1924 return;
1927 // If we have "X || 0", simplify the code to use an uncond branch.
1928 // "X || 1" would have been constant folded to 1.
1929 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1930 !ConstantBool) {
1931 // br(X || 0) -> br(X).
1932 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1933 FalseBlock, TrueCount, LH, CondBOp);
1934 MCDCLogOpStack.pop_back();
1935 return;
1937 // Emit the LHS as a conditional. If the LHS conditional is true, we
1938 // want to jump to the TrueBlock.
1939 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1940 // We have the count for entry to the RHS and for the whole expression
1941 // being true, so we can divy up True count between the short circuit and
1942 // the RHS.
1943 uint64_t LHSCount =
1944 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1945 uint64_t RHSCount = TrueCount - LHSCount;
1947 ConditionalEvaluation eval(*this);
1949 // Propagate the likelihood attribute like __builtin_expect
1950 // __builtin_expect(X || Y, 1) -> only Y is likely
1951 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1952 ApplyDebugLocation DL(*this, Cond);
1953 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1954 LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
1955 EmitBlock(LHSFalse);
1958 incrementProfileCounter(CondBOp);
1959 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1961 // Any temporaries created here are conditional.
1962 eval.begin(*this);
1963 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1964 RHSCount, LH);
1966 eval.end(*this);
1967 MCDCLogOpStack.pop_back();
1968 return;
1972 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1973 // br(!x, t, f) -> br(x, f, t)
1974 // Avoid doing this optimization when instrumenting a condition for MC/DC.
1975 // LNot is taken as part of the condition for simplicity, and changing its
1976 // sense negatively impacts test vector tracking.
1977 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
1978 CGM.getCodeGenOpts().MCDCCoverage &&
1979 isInstrumentedCondition(Cond);
1980 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
1981 // Negate the count.
1982 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1983 // The values of the enum are chosen to make this negation possible.
1984 LH = static_cast<Stmt::Likelihood>(-LH);
1985 // Negate the condition and swap the destination blocks.
1986 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1987 FalseCount, LH);
1991 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1992 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1993 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1994 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1996 // The ConditionalOperator itself has no likelihood information for its
1997 // true and false branches. This matches the behavior of __builtin_expect.
1998 ConditionalEvaluation cond(*this);
1999 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
2000 getProfileCount(CondOp), Stmt::LH_None);
2002 // When computing PGO branch weights, we only know the overall count for
2003 // the true block. This code is essentially doing tail duplication of the
2004 // naive code-gen, introducing new edges for which counts are not
2005 // available. Divide the counts proportionally between the LHS and RHS of
2006 // the conditional operator.
2007 uint64_t LHSScaledTrueCount = 0;
2008 if (TrueCount) {
2009 double LHSRatio =
2010 getProfileCount(CondOp) / (double)getCurrentProfileCount();
2011 LHSScaledTrueCount = TrueCount * LHSRatio;
2014 cond.begin(*this);
2015 EmitBlock(LHSBlock);
2016 incrementProfileCounter(CondOp);
2018 ApplyDebugLocation DL(*this, Cond);
2019 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
2020 LHSScaledTrueCount, LH, CondOp);
2022 cond.end(*this);
2024 cond.begin(*this);
2025 EmitBlock(RHSBlock);
2026 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
2027 TrueCount - LHSScaledTrueCount, LH, CondOp);
2028 cond.end(*this);
2030 return;
2033 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2034 // Conditional operator handling can give us a throw expression as a
2035 // condition for a case like:
2036 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2037 // Fold this to:
2038 // br(c, throw x, br(y, t, f))
2039 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
2040 return;
2043 // Emit the code with the fully general case.
2044 llvm::Value *CondV;
2046 ApplyDebugLocation DL(*this, Cond);
2047 CondV = EvaluateExprAsBool(Cond);
2050 // If not at the top of the logical operator nest, update MCDC temp with the
2051 // boolean result of the evaluated condition.
2052 if (!MCDCLogOpStack.empty()) {
2053 const Expr *MCDCBaseExpr = Cond;
2054 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2055 // expression, MC/DC tracks the result of the ternary, and this is tied to
2056 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2057 // this is the case, the ConditionalOperator expression is passed through
2058 // the ConditionalOp parameter and then used as the MCDC base expression.
2059 if (ConditionalOp)
2060 MCDCBaseExpr = ConditionalOp;
2062 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2065 llvm::MDNode *Weights = nullptr;
2066 llvm::MDNode *Unpredictable = nullptr;
2068 // If the branch has a condition wrapped by __builtin_unpredictable,
2069 // create metadata that specifies that the branch is unpredictable.
2070 // Don't bother if not optimizing because that metadata would not be used.
2071 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2072 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2073 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2074 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2075 llvm::MDBuilder MDHelper(getLLVMContext());
2076 Unpredictable = MDHelper.createUnpredictable();
2080 // If there is a Likelihood knowledge for the cond, lower it.
2081 // Note that if not optimizing this won't emit anything.
2082 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2083 if (CondV != NewCondV)
2084 CondV = NewCondV;
2085 else {
2086 // Otherwise, lower profile counts. Note that we do this even at -O0.
2087 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2088 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2091 llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, FalseBlock,
2092 Weights, Unpredictable);
2093 switch (HLSLControlFlowAttr) {
2094 case HLSLControlFlowHintAttr::Microsoft_branch:
2095 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2096 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2098 llvm::ConstantInt *BranchHintConstant =
2099 HLSLControlFlowAttr ==
2100 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2101 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2102 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2104 SmallVector<llvm::Metadata *, 2> Vals(
2105 {MDHelper.createString("hlsl.controlflow.hint"),
2106 MDHelper.createConstant(BranchHintConstant)});
2107 BrInst->setMetadata("hlsl.controlflow.hint",
2108 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2109 break;
2111 // This is required to avoid warnings during compilation
2112 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2113 break;
2117 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2118 /// specified stmt yet.
2119 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2120 CGM.ErrorUnsupported(S, Type);
2123 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
2124 /// variable-length array whose elements have a non-zero bit-pattern.
2126 /// \param baseType the inner-most element type of the array
2127 /// \param src - a char* pointing to the bit-pattern for a single
2128 /// base element of the array
2129 /// \param sizeInChars - the total size of the VLA, in chars
2130 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
2131 Address dest, Address src,
2132 llvm::Value *sizeInChars) {
2133 CGBuilderTy &Builder = CGF.Builder;
2135 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2136 llvm::Value *baseSizeInChars
2137 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2139 Address begin = dest.withElementType(CGF.Int8Ty);
2140 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2141 begin.emitRawPointer(CGF),
2142 sizeInChars, "vla.end");
2144 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2145 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2146 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2148 // Make a loop over the VLA. C99 guarantees that the VLA element
2149 // count must be nonzero.
2150 CGF.EmitBlock(loopBB);
2152 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2153 cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2155 CharUnits curAlign =
2156 dest.getAlignment().alignmentOfArrayElement(baseSize);
2158 // memcpy the individual element bit-pattern.
2159 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2160 /*volatile*/ false);
2162 // Go to the next element.
2163 llvm::Value *next =
2164 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2166 // Leave if that's the end of the VLA.
2167 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2168 Builder.CreateCondBr(done, contBB, loopBB);
2169 cur->addIncoming(next, loopBB);
2171 CGF.EmitBlock(contBB);
2174 void
2175 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
2176 // Ignore empty classes in C++.
2177 if (getLangOpts().CPlusPlus) {
2178 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2179 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
2180 return;
2184 if (DestPtr.getElementType() != Int8Ty)
2185 DestPtr = DestPtr.withElementType(Int8Ty);
2187 // Get size and alignment info for this aggregate.
2188 CharUnits size = getContext().getTypeSizeInChars(Ty);
2190 llvm::Value *SizeVal;
2191 const VariableArrayType *vla;
2193 // Don't bother emitting a zero-byte memset.
2194 if (size.isZero()) {
2195 // But note that getTypeInfo returns 0 for a VLA.
2196 if (const VariableArrayType *vlaType =
2197 dyn_cast_or_null<VariableArrayType>(
2198 getContext().getAsArrayType(Ty))) {
2199 auto VlaSize = getVLASize(vlaType);
2200 SizeVal = VlaSize.NumElts;
2201 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2202 if (!eltSize.isOne())
2203 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2204 vla = vlaType;
2205 } else {
2206 return;
2208 } else {
2209 SizeVal = CGM.getSize(size);
2210 vla = nullptr;
2213 // If the type contains a pointer to data member we can't memset it to zero.
2214 // Instead, create a null constant and copy it to the destination.
2215 // TODO: there are other patterns besides zero that we can usefully memset,
2216 // like -1, which happens to be the pattern used by member-pointers.
2217 if (!CGM.getTypes().isZeroInitializable(Ty)) {
2218 // For a VLA, emit a single element, then splat that over the VLA.
2219 if (vla) Ty = getContext().getBaseElementType(vla);
2221 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2223 llvm::GlobalVariable *NullVariable =
2224 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2225 /*isConstant=*/true,
2226 llvm::GlobalVariable::PrivateLinkage,
2227 NullConstant, Twine());
2228 CharUnits NullAlign = DestPtr.getAlignment();
2229 NullVariable->setAlignment(NullAlign.getAsAlign());
2230 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2232 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2234 // Get and call the appropriate llvm.memcpy overload.
2235 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2236 return;
2239 // Otherwise, just memset the whole thing to zero. This is legal
2240 // because in LLVM, all default initializers (other than the ones we just
2241 // handled above) are guaranteed to have a bit pattern of all zeros.
2242 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2245 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2246 // Make sure that there is a block for the indirect goto.
2247 if (!IndirectBranch)
2248 GetIndirectGotoBlock();
2250 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2252 // Make sure the indirect branch includes all of the address-taken blocks.
2253 IndirectBranch->addDestination(BB);
2254 return llvm::BlockAddress::get(CurFn, BB);
2257 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2258 // If we already made the indirect branch for indirect goto, return its block.
2259 if (IndirectBranch) return IndirectBranch->getParent();
2261 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2263 // Create the PHI node that indirect gotos will add entries to.
2264 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2265 "indirect.goto.dest");
2267 // Create the indirect branch instruction.
2268 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2269 return IndirectBranch->getParent();
2272 /// Computes the length of an array in elements, as well as the base
2273 /// element type and a properly-typed first element pointer.
2274 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2275 QualType &baseType,
2276 Address &addr) {
2277 const ArrayType *arrayType = origArrayType;
2279 // If it's a VLA, we have to load the stored size. Note that
2280 // this is the size of the VLA in bytes, not its size in elements.
2281 llvm::Value *numVLAElements = nullptr;
2282 if (isa<VariableArrayType>(arrayType)) {
2283 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2285 // Walk into all VLAs. This doesn't require changes to addr,
2286 // which has type T* where T is the first non-VLA element type.
2287 do {
2288 QualType elementType = arrayType->getElementType();
2289 arrayType = getContext().getAsArrayType(elementType);
2291 // If we only have VLA components, 'addr' requires no adjustment.
2292 if (!arrayType) {
2293 baseType = elementType;
2294 return numVLAElements;
2296 } while (isa<VariableArrayType>(arrayType));
2298 // We get out here only if we find a constant array type
2299 // inside the VLA.
2302 // We have some number of constant-length arrays, so addr should
2303 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2304 // down to the first element of addr.
2305 SmallVector<llvm::Value*, 8> gepIndices;
2307 // GEP down to the array type.
2308 llvm::ConstantInt *zero = Builder.getInt32(0);
2309 gepIndices.push_back(zero);
2311 uint64_t countFromCLAs = 1;
2312 QualType eltType;
2314 llvm::ArrayType *llvmArrayType =
2315 dyn_cast<llvm::ArrayType>(addr.getElementType());
2316 while (llvmArrayType) {
2317 assert(isa<ConstantArrayType>(arrayType));
2318 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2319 llvmArrayType->getNumElements());
2321 gepIndices.push_back(zero);
2322 countFromCLAs *= llvmArrayType->getNumElements();
2323 eltType = arrayType->getElementType();
2325 llvmArrayType =
2326 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2327 arrayType = getContext().getAsArrayType(arrayType->getElementType());
2328 assert((!llvmArrayType || arrayType) &&
2329 "LLVM and Clang types are out-of-synch");
2332 if (arrayType) {
2333 // From this point onwards, the Clang array type has been emitted
2334 // as some other type (probably a packed struct). Compute the array
2335 // size, and just emit the 'begin' expression as a bitcast.
2336 while (arrayType) {
2337 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2338 eltType = arrayType->getElementType();
2339 arrayType = getContext().getAsArrayType(eltType);
2342 llvm::Type *baseType = ConvertType(eltType);
2343 addr = addr.withElementType(baseType);
2344 } else {
2345 // Create the actual GEP.
2346 addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
2347 addr.emitRawPointer(*this),
2348 gepIndices, "array.begin"),
2349 ConvertTypeForMem(eltType), addr.getAlignment());
2352 baseType = eltType;
2354 llvm::Value *numElements
2355 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2357 // If we had any VLA dimensions, factor them in.
2358 if (numVLAElements)
2359 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2361 return numElements;
2364 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2365 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2366 assert(vla && "type was not a variable array type!");
2367 return getVLASize(vla);
2370 CodeGenFunction::VlaSizePair
2371 CodeGenFunction::getVLASize(const VariableArrayType *type) {
2372 // The number of elements so far; always size_t.
2373 llvm::Value *numElements = nullptr;
2375 QualType elementType;
2376 do {
2377 elementType = type->getElementType();
2378 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2379 assert(vlaSize && "no size for VLA!");
2380 assert(vlaSize->getType() == SizeTy);
2382 if (!numElements) {
2383 numElements = vlaSize;
2384 } else {
2385 // It's undefined behavior if this wraps around, so mark it that way.
2386 // FIXME: Teach -fsanitize=undefined to trap this.
2387 numElements = Builder.CreateNUWMul(numElements, vlaSize);
2389 } while ((type = getContext().getAsVariableArrayType(elementType)));
2391 return { numElements, elementType };
2394 CodeGenFunction::VlaSizePair
2395 CodeGenFunction::getVLAElements1D(QualType type) {
2396 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2397 assert(vla && "type was not a variable array type!");
2398 return getVLAElements1D(vla);
2401 CodeGenFunction::VlaSizePair
2402 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2403 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2404 assert(VlaSize && "no size for VLA!");
2405 assert(VlaSize->getType() == SizeTy);
2406 return { VlaSize, Vla->getElementType() };
2409 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2410 assert(type->isVariablyModifiedType() &&
2411 "Must pass variably modified type to EmitVLASizes!");
2413 EnsureInsertPoint();
2415 // We're going to walk down into the type and look for VLA
2416 // expressions.
2417 do {
2418 assert(type->isVariablyModifiedType());
2420 const Type *ty = type.getTypePtr();
2421 switch (ty->getTypeClass()) {
2423 #define TYPE(Class, Base)
2424 #define ABSTRACT_TYPE(Class, Base)
2425 #define NON_CANONICAL_TYPE(Class, Base)
2426 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2427 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2428 #include "clang/AST/TypeNodes.inc"
2429 llvm_unreachable("unexpected dependent type!");
2431 // These types are never variably-modified.
2432 case Type::Builtin:
2433 case Type::Complex:
2434 case Type::Vector:
2435 case Type::ExtVector:
2436 case Type::ConstantMatrix:
2437 case Type::Record:
2438 case Type::Enum:
2439 case Type::Using:
2440 case Type::TemplateSpecialization:
2441 case Type::ObjCTypeParam:
2442 case Type::ObjCObject:
2443 case Type::ObjCInterface:
2444 case Type::ObjCObjectPointer:
2445 case Type::BitInt:
2446 llvm_unreachable("type class is never variably-modified!");
2448 case Type::Elaborated:
2449 type = cast<ElaboratedType>(ty)->getNamedType();
2450 break;
2452 case Type::Adjusted:
2453 type = cast<AdjustedType>(ty)->getAdjustedType();
2454 break;
2456 case Type::Decayed:
2457 type = cast<DecayedType>(ty)->getPointeeType();
2458 break;
2460 case Type::Pointer:
2461 type = cast<PointerType>(ty)->getPointeeType();
2462 break;
2464 case Type::BlockPointer:
2465 type = cast<BlockPointerType>(ty)->getPointeeType();
2466 break;
2468 case Type::LValueReference:
2469 case Type::RValueReference:
2470 type = cast<ReferenceType>(ty)->getPointeeType();
2471 break;
2473 case Type::MemberPointer:
2474 type = cast<MemberPointerType>(ty)->getPointeeType();
2475 break;
2477 case Type::ArrayParameter:
2478 case Type::ConstantArray:
2479 case Type::IncompleteArray:
2480 // Losing element qualification here is fine.
2481 type = cast<ArrayType>(ty)->getElementType();
2482 break;
2484 case Type::VariableArray: {
2485 // Losing element qualification here is fine.
2486 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2488 // Unknown size indication requires no size computation.
2489 // Otherwise, evaluate and record it.
2490 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2491 // It's possible that we might have emitted this already,
2492 // e.g. with a typedef and a pointer to it.
2493 llvm::Value *&entry = VLASizeMap[sizeExpr];
2494 if (!entry) {
2495 llvm::Value *size = EmitScalarExpr(sizeExpr);
2497 // C11 6.7.6.2p5:
2498 // If the size is an expression that is not an integer constant
2499 // expression [...] each time it is evaluated it shall have a value
2500 // greater than zero.
2501 if (SanOpts.has(SanitizerKind::VLABound)) {
2502 SanitizerScope SanScope(this);
2503 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2504 clang::QualType SEType = sizeExpr->getType();
2505 llvm::Value *CheckCondition =
2506 SEType->isSignedIntegerType()
2507 ? Builder.CreateICmpSGT(size, Zero)
2508 : Builder.CreateICmpUGT(size, Zero);
2509 llvm::Constant *StaticArgs[] = {
2510 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2511 EmitCheckTypeDescriptor(SEType)};
2512 EmitCheck(
2513 std::make_pair(CheckCondition, SanitizerKind::SO_VLABound),
2514 SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
2517 // Always zexting here would be wrong if it weren't
2518 // undefined behavior to have a negative bound.
2519 // FIXME: What about when size's type is larger than size_t?
2520 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2523 type = vat->getElementType();
2524 break;
2527 case Type::FunctionProto:
2528 case Type::FunctionNoProto:
2529 type = cast<FunctionType>(ty)->getReturnType();
2530 break;
2532 case Type::Paren:
2533 case Type::TypeOf:
2534 case Type::UnaryTransform:
2535 case Type::Attributed:
2536 case Type::BTFTagAttributed:
2537 case Type::HLSLAttributedResource:
2538 case Type::SubstTemplateTypeParm:
2539 case Type::MacroQualified:
2540 case Type::CountAttributed:
2541 // Keep walking after single level desugaring.
2542 type = type.getSingleStepDesugaredType(getContext());
2543 break;
2545 case Type::Typedef:
2546 case Type::Decltype:
2547 case Type::Auto:
2548 case Type::DeducedTemplateSpecialization:
2549 case Type::PackIndexing:
2550 // Stop walking: nothing to do.
2551 return;
2553 case Type::TypeOfExpr:
2554 // Stop walking: emit typeof expression.
2555 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2556 return;
2558 case Type::Atomic:
2559 type = cast<AtomicType>(ty)->getValueType();
2560 break;
2562 case Type::Pipe:
2563 type = cast<PipeType>(ty)->getElementType();
2564 break;
2566 } while (type->isVariablyModifiedType());
2569 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2570 if (getContext().getBuiltinVaListType()->isArrayType())
2571 return EmitPointerWithAlignment(E);
2572 return EmitLValue(E).getAddress();
2575 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2576 return EmitLValue(E).getAddress();
2579 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2580 const APValue &Init) {
2581 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2582 if (CGDebugInfo *Dbg = getDebugInfo())
2583 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2584 Dbg->EmitGlobalVariable(E->getDecl(), Init);
2587 CodeGenFunction::PeepholeProtection
2588 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2589 // At the moment, the only aggressive peephole we do in IR gen
2590 // is trunc(zext) folding, but if we add more, we can easily
2591 // extend this protection.
2593 if (!rvalue.isScalar()) return PeepholeProtection();
2594 llvm::Value *value = rvalue.getScalarVal();
2595 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2597 // Just make an extra bitcast.
2598 assert(HaveInsertPoint());
2599 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2600 Builder.GetInsertBlock());
2602 PeepholeProtection protection;
2603 protection.Inst = inst;
2604 return protection;
2607 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2608 if (!protection.Inst) return;
2610 // In theory, we could try to duplicate the peepholes now, but whatever.
2611 protection.Inst->eraseFromParent();
2614 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2615 QualType Ty, SourceLocation Loc,
2616 SourceLocation AssumptionLoc,
2617 llvm::Value *Alignment,
2618 llvm::Value *OffsetValue) {
2619 if (Alignment->getType() != IntPtrTy)
2620 Alignment =
2621 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2622 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2623 OffsetValue =
2624 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2625 llvm::Value *TheCheck = nullptr;
2626 if (SanOpts.has(SanitizerKind::Alignment)) {
2627 llvm::Value *PtrIntValue =
2628 Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2630 if (OffsetValue) {
2631 bool IsOffsetZero = false;
2632 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2633 IsOffsetZero = CI->isZero();
2635 if (!IsOffsetZero)
2636 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2639 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2640 llvm::Value *Mask =
2641 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2642 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2643 TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2645 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2646 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2648 if (!SanOpts.has(SanitizerKind::Alignment))
2649 return;
2650 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2651 OffsetValue, TheCheck, Assumption);
2654 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2655 const Expr *E,
2656 SourceLocation AssumptionLoc,
2657 llvm::Value *Alignment,
2658 llvm::Value *OffsetValue) {
2659 QualType Ty = E->getType();
2660 SourceLocation Loc = E->getExprLoc();
2662 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2663 OffsetValue);
2666 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2667 llvm::Value *AnnotatedVal,
2668 StringRef AnnotationStr,
2669 SourceLocation Location,
2670 const AnnotateAttr *Attr) {
2671 SmallVector<llvm::Value *, 5> Args = {
2672 AnnotatedVal,
2673 CGM.EmitAnnotationString(AnnotationStr),
2674 CGM.EmitAnnotationUnit(Location),
2675 CGM.EmitAnnotationLineNo(Location),
2677 if (Attr)
2678 Args.push_back(CGM.EmitAnnotationArgs(Attr));
2679 return Builder.CreateCall(AnnotationFn, Args);
2682 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2683 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2684 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2685 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2686 {V->getType(), CGM.ConstGlobalsPtrTy}),
2687 V, I->getAnnotation(), D->getLocation(), I);
2690 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2691 Address Addr) {
2692 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2693 llvm::Value *V = Addr.emitRawPointer(*this);
2694 llvm::Type *VTy = V->getType();
2695 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2696 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2697 llvm::PointerType *IntrinTy =
2698 llvm::PointerType::get(CGM.getLLVMContext(), AS);
2699 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2700 {IntrinTy, CGM.ConstGlobalsPtrTy});
2702 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2703 // FIXME Always emit the cast inst so we can differentiate between
2704 // annotation on the first field of a struct and annotation on the struct
2705 // itself.
2706 if (VTy != IntrinTy)
2707 V = Builder.CreateBitCast(V, IntrinTy);
2708 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2709 V = Builder.CreateBitCast(V, VTy);
2712 return Address(V, Addr.getElementType(), Addr.getAlignment());
2715 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2717 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2718 : CGF(CGF) {
2719 assert(!CGF->IsSanitizerScope);
2720 CGF->IsSanitizerScope = true;
2723 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2724 CGF->IsSanitizerScope = false;
2727 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2728 const llvm::Twine &Name,
2729 llvm::BasicBlock::iterator InsertPt) const {
2730 LoopStack.InsertHelper(I);
2731 if (IsSanitizerScope)
2732 I->setNoSanitizeMetadata();
2735 void CGBuilderInserter::InsertHelper(
2736 llvm::Instruction *I, const llvm::Twine &Name,
2737 llvm::BasicBlock::iterator InsertPt) const {
2738 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2739 if (CGF)
2740 CGF->InsertHelper(I, Name, InsertPt);
2743 // Emits an error if we don't have a valid set of target features for the
2744 // called function.
2745 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2746 const FunctionDecl *TargetDecl) {
2747 // SemaChecking cannot handle below x86 builtins because they have different
2748 // parameter ranges with different TargetAttribute of caller.
2749 if (CGM.getContext().getTargetInfo().getTriple().isX86()) {
2750 unsigned BuiltinID = TargetDecl->getBuiltinID();
2751 if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
2752 BuiltinID == X86::BI__builtin_ia32_cmpss ||
2753 BuiltinID == X86::BI__builtin_ia32_cmppd ||
2754 BuiltinID == X86::BI__builtin_ia32_cmpsd) {
2755 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2756 llvm::StringMap<bool> TargetFetureMap;
2757 CGM.getContext().getFunctionFeatureMap(TargetFetureMap, FD);
2758 llvm::APSInt Result =
2759 *(E->getArg(2)->getIntegerConstantExpr(CGM.getContext()));
2760 if (Result.getSExtValue() > 7 && !TargetFetureMap.lookup("avx"))
2761 CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
2762 << TargetDecl->getDeclName() << "avx";
2765 return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2768 // Emits an error if we don't have a valid set of target features for the
2769 // called function.
2770 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2771 const FunctionDecl *TargetDecl) {
2772 // Early exit if this is an indirect call.
2773 if (!TargetDecl)
2774 return;
2776 // Get the current enclosing function if it exists. If it doesn't
2777 // we can't check the target features anyhow.
2778 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2779 if (!FD)
2780 return;
2782 // Grab the required features for the call. For a builtin this is listed in
2783 // the td file with the default cpu, for an always_inline function this is any
2784 // listed cpu and any listed features.
2785 unsigned BuiltinID = TargetDecl->getBuiltinID();
2786 std::string MissingFeature;
2787 llvm::StringMap<bool> CallerFeatureMap;
2788 CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2789 // When compiling in HipStdPar mode we have to be conservative in rejecting
2790 // target specific features in the FE, and defer the possible error to the
2791 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
2792 // referenced by an accelerator executable function, we emit an error.
2793 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2794 if (BuiltinID) {
2795 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2796 if (!Builtin::evaluateRequiredTargetFeatures(
2797 FeatureList, CallerFeatureMap) && !IsHipStdPar) {
2798 CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2799 << TargetDecl->getDeclName()
2800 << FeatureList;
2802 } else if (!TargetDecl->isMultiVersion() &&
2803 TargetDecl->hasAttr<TargetAttr>()) {
2804 // Get the required features for the callee.
2806 const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2807 ParsedTargetAttr ParsedAttr =
2808 CGM.getContext().filterFunctionTargetAttrs(TD);
2810 SmallVector<StringRef, 1> ReqFeatures;
2811 llvm::StringMap<bool> CalleeFeatureMap;
2812 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2814 for (const auto &F : ParsedAttr.Features) {
2815 if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2816 ReqFeatures.push_back(StringRef(F).substr(1));
2819 for (const auto &F : CalleeFeatureMap) {
2820 // Only positive features are "required".
2821 if (F.getValue())
2822 ReqFeatures.push_back(F.getKey());
2824 if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2825 if (!CallerFeatureMap.lookup(Feature)) {
2826 MissingFeature = Feature.str();
2827 return false;
2829 return true;
2830 }) && !IsHipStdPar)
2831 CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2832 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2833 } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) {
2834 llvm::StringMap<bool> CalleeFeatureMap;
2835 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2837 for (const auto &F : CalleeFeatureMap) {
2838 if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
2839 !CallerFeatureMap.find(F.getKey())->getValue()) &&
2840 !IsHipStdPar)
2841 CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2842 << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
2847 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2848 if (!CGM.getCodeGenOpts().SanitizeStats)
2849 return;
2851 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2852 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2853 CGM.getSanStats().create(IRB, SSK);
2856 void CodeGenFunction::EmitKCFIOperandBundle(
2857 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2858 const FunctionProtoType *FP =
2859 Callee.getAbstractInfo().getCalleeFunctionProtoType();
2860 if (FP)
2861 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar()));
2864 llvm::Value *
2865 CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2866 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(RO.Features);
2869 llvm::Value *
2870 CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2871 llvm::Value *Condition = nullptr;
2873 if (RO.Architecture) {
2874 StringRef Arch = *RO.Architecture;
2875 // If arch= specifies an x86-64 micro-architecture level, test the feature
2876 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2877 if (Arch.starts_with("x86-64"))
2878 Condition = EmitX86CpuSupports({Arch});
2879 else
2880 Condition = EmitX86CpuIs(Arch);
2883 if (!RO.Features.empty()) {
2884 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2885 Condition =
2886 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2888 return Condition;
2891 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2892 llvm::Function *Resolver,
2893 CGBuilderTy &Builder,
2894 llvm::Function *FuncToReturn,
2895 bool SupportsIFunc) {
2896 if (SupportsIFunc) {
2897 Builder.CreateRet(FuncToReturn);
2898 return;
2901 llvm::SmallVector<llvm::Value *, 10> Args(
2902 llvm::make_pointer_range(Resolver->args()));
2904 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2905 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2907 if (Resolver->getReturnType()->isVoidTy())
2908 Builder.CreateRetVoid();
2909 else
2910 Builder.CreateRet(Result);
2913 void CodeGenFunction::EmitMultiVersionResolver(
2914 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2916 llvm::Triple::ArchType ArchType =
2917 getContext().getTargetInfo().getTriple().getArch();
2919 switch (ArchType) {
2920 case llvm::Triple::x86:
2921 case llvm::Triple::x86_64:
2922 EmitX86MultiVersionResolver(Resolver, Options);
2923 return;
2924 case llvm::Triple::aarch64:
2925 EmitAArch64MultiVersionResolver(Resolver, Options);
2926 return;
2927 case llvm::Triple::riscv32:
2928 case llvm::Triple::riscv64:
2929 EmitRISCVMultiVersionResolver(Resolver, Options);
2930 return;
2932 default:
2933 assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
2937 void CodeGenFunction::EmitRISCVMultiVersionResolver(
2938 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2940 if (getContext().getTargetInfo().getTriple().getOS() !=
2941 llvm::Triple::OSType::Linux) {
2942 CGM.getDiags().Report(diag::err_os_unsupport_riscv_fmv);
2943 return;
2946 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2947 Builder.SetInsertPoint(CurBlock);
2948 EmitRISCVCpuInit();
2950 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2951 bool HasDefault = false;
2952 unsigned DefaultIndex = 0;
2954 // Check the each candidate function.
2955 for (unsigned Index = 0; Index < Options.size(); Index++) {
2957 if (Options[Index].Features.empty()) {
2958 HasDefault = true;
2959 DefaultIndex = Index;
2960 continue;
2963 Builder.SetInsertPoint(CurBlock);
2965 // FeaturesCondition: The bitmask of the required extension has been
2966 // enabled by the runtime object.
2967 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
2968 // REQUIRED_BITMASK
2970 // When condition is met, return this version of the function.
2971 // Otherwise, try the next version.
2973 // if (FeaturesConditionVersion1)
2974 // return Version1;
2975 // else if (FeaturesConditionVersion2)
2976 // return Version2;
2977 // else if (FeaturesConditionVersion3)
2978 // return Version3;
2979 // ...
2980 // else
2981 // return DefaultVersion;
2983 // TODO: Add a condition to check the length before accessing elements.
2984 // Without checking the length first, we may access an incorrect memory
2985 // address when using different versions.
2986 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
2987 llvm::SmallVector<std::string, 8> TargetAttrFeats;
2989 for (StringRef Feat : Options[Index].Features) {
2990 std::vector<std::string> FeatStr =
2991 getContext().getTargetInfo().parseTargetAttr(Feat).Features;
2993 assert(FeatStr.size() == 1 && "Feature string not delimited");
2995 std::string &CurrFeat = FeatStr.front();
2996 if (CurrFeat[0] == '+')
2997 TargetAttrFeats.push_back(CurrFeat.substr(1));
3000 if (TargetAttrFeats.empty())
3001 continue;
3003 for (std::string &Feat : TargetAttrFeats)
3004 CurrTargetAttrFeats.push_back(Feat);
3006 Builder.SetInsertPoint(CurBlock);
3007 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(CurrTargetAttrFeats);
3009 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3010 CGBuilderTy RetBuilder(*this, RetBlock);
3011 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder,
3012 Options[Index].Function, SupportsIFunc);
3013 llvm::BasicBlock *ElseBlock = createBasicBlock("resolver_else", Resolver);
3015 Builder.SetInsertPoint(CurBlock);
3016 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
3018 CurBlock = ElseBlock;
3021 // Finally, emit the default one.
3022 if (HasDefault) {
3023 Builder.SetInsertPoint(CurBlock);
3024 CreateMultiVersionResolverReturn(
3025 CGM, Resolver, Builder, Options[DefaultIndex].Function, SupportsIFunc);
3026 return;
3029 // If no generic/default, emit an unreachable.
3030 Builder.SetInsertPoint(CurBlock);
3031 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3032 TrapCall->setDoesNotReturn();
3033 TrapCall->setDoesNotThrow();
3034 Builder.CreateUnreachable();
3035 Builder.ClearInsertionPoint();
3038 void CodeGenFunction::EmitAArch64MultiVersionResolver(
3039 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3040 assert(!Options.empty() && "No multiversion resolver options found");
3041 assert(Options.back().Features.size() == 0 && "Default case must be last");
3042 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3043 assert(SupportsIFunc &&
3044 "Multiversion resolver requires target IFUNC support");
3045 bool AArch64CpuInitialized = false;
3046 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3048 for (const FMVResolverOption &RO : Options) {
3049 Builder.SetInsertPoint(CurBlock);
3050 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3052 // The 'default' or 'all features enabled' case.
3053 if (!Condition) {
3054 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3055 SupportsIFunc);
3056 return;
3059 if (!AArch64CpuInitialized) {
3060 Builder.SetInsertPoint(CurBlock, CurBlock->begin());
3061 EmitAArch64CpuInit();
3062 AArch64CpuInitialized = true;
3063 Builder.SetInsertPoint(CurBlock);
3066 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3067 CGBuilderTy RetBuilder(*this, RetBlock);
3068 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3069 SupportsIFunc);
3070 CurBlock = createBasicBlock("resolver_else", Resolver);
3071 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3074 // If no default, emit an unreachable.
3075 Builder.SetInsertPoint(CurBlock);
3076 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3077 TrapCall->setDoesNotReturn();
3078 TrapCall->setDoesNotThrow();
3079 Builder.CreateUnreachable();
3080 Builder.ClearInsertionPoint();
3083 void CodeGenFunction::EmitX86MultiVersionResolver(
3084 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3086 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3088 // Main function's basic block.
3089 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3090 Builder.SetInsertPoint(CurBlock);
3091 EmitX86CpuInit();
3093 for (const FMVResolverOption &RO : Options) {
3094 Builder.SetInsertPoint(CurBlock);
3095 llvm::Value *Condition = FormX86ResolverCondition(RO);
3097 // The 'default' or 'generic' case.
3098 if (!Condition) {
3099 assert(&RO == Options.end() - 1 &&
3100 "Default or Generic case must be last");
3101 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3102 SupportsIFunc);
3103 return;
3106 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3107 CGBuilderTy RetBuilder(*this, RetBlock);
3108 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3109 SupportsIFunc);
3110 CurBlock = createBasicBlock("resolver_else", Resolver);
3111 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3114 // If no generic/default, emit an unreachable.
3115 Builder.SetInsertPoint(CurBlock);
3116 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3117 TrapCall->setDoesNotReturn();
3118 TrapCall->setDoesNotThrow();
3119 Builder.CreateUnreachable();
3120 Builder.ClearInsertionPoint();
3123 // Loc - where the diagnostic will point, where in the source code this
3124 // alignment has failed.
3125 // SecondaryLoc - if present (will be present if sufficiently different from
3126 // Loc), the diagnostic will additionally point a "Note:" to this location.
3127 // It should be the location where the __attribute__((assume_aligned))
3128 // was written e.g.
3129 void CodeGenFunction::emitAlignmentAssumptionCheck(
3130 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
3131 SourceLocation SecondaryLoc, llvm::Value *Alignment,
3132 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3133 llvm::Instruction *Assumption) {
3134 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3135 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3136 llvm::Intrinsic::getOrInsertDeclaration(
3137 Builder.GetInsertBlock()->getParent()->getParent(),
3138 llvm::Intrinsic::assume) &&
3139 "Assumption should be a call to llvm.assume().");
3140 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
3141 "Assumption should be the last instruction of the basic block, "
3142 "since the basic block is still being generated.");
3144 if (!SanOpts.has(SanitizerKind::Alignment))
3145 return;
3147 // Don't check pointers to volatile data. The behavior here is implementation-
3148 // defined.
3149 if (Ty->getPointeeType().isVolatileQualified())
3150 return;
3152 // We need to temorairly remove the assumption so we can insert the
3153 // sanitizer check before it, else the check will be dropped by optimizations.
3154 Assumption->removeFromParent();
3157 SanitizerScope SanScope(this);
3159 if (!OffsetValue)
3160 OffsetValue = Builder.getInt1(false); // no offset.
3162 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3163 EmitCheckSourceLocation(SecondaryLoc),
3164 EmitCheckTypeDescriptor(Ty)};
3165 llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
3166 EmitCheckValue(Alignment),
3167 EmitCheckValue(OffsetValue)};
3168 EmitCheck({std::make_pair(TheCheck, SanitizerKind::SO_Alignment)},
3169 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
3172 // We are now in the (new, empty) "cont" basic block.
3173 // Reintroduce the assumption.
3174 Builder.Insert(Assumption);
3175 // FIXME: Assumption still has it's original basic block as it's Parent.
3178 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
3179 if (CGDebugInfo *DI = getDebugInfo())
3180 return DI->SourceLocToDebugLoc(Location);
3182 return llvm::DebugLoc();
3185 llvm::Value *
3186 CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3187 Stmt::Likelihood LH) {
3188 switch (LH) {
3189 case Stmt::LH_None:
3190 return Cond;
3191 case Stmt::LH_Likely:
3192 case Stmt::LH_Unlikely:
3193 // Don't generate llvm.expect on -O0 as the backend won't use it for
3194 // anything.
3195 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3196 return Cond;
3197 llvm::Type *CondTy = Cond->getType();
3198 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3199 llvm::Function *FnExpect =
3200 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3201 llvm::Value *ExpectedValueOfCond =
3202 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3203 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3204 Cond->getName() + ".expval");
3206 llvm_unreachable("Unknown Likelihood");
3209 llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3210 unsigned NumElementsDst,
3211 const llvm::Twine &Name) {
3212 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3213 unsigned NumElementsSrc = SrcTy->getNumElements();
3214 if (NumElementsSrc == NumElementsDst)
3215 return SrcVec;
3217 std::vector<int> ShuffleMask(NumElementsDst, -1);
3218 for (unsigned MaskIdx = 0;
3219 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3220 ShuffleMask[MaskIdx] = MaskIdx;
3222 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3225 void CodeGenFunction::EmitPointerAuthOperandBundle(
3226 const CGPointerAuthInfo &PointerAuth,
3227 SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
3228 if (!PointerAuth.isSigned())
3229 return;
3231 auto *Key = Builder.getInt32(PointerAuth.getKey());
3233 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3234 if (!Discriminator)
3235 Discriminator = Builder.getSize(0);
3237 llvm::Value *Args[] = {Key, Discriminator};
3238 Bundles.emplace_back("ptrauth", Args);
3241 static llvm::Value *EmitPointerAuthCommon(CodeGenFunction &CGF,
3242 const CGPointerAuthInfo &PointerAuth,
3243 llvm::Value *Pointer,
3244 unsigned IntrinsicID) {
3245 if (!PointerAuth)
3246 return Pointer;
3248 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3250 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3251 if (!Discriminator) {
3252 Discriminator = CGF.Builder.getSize(0);
3255 // Convert the pointer to intptr_t before signing it.
3256 auto OrigType = Pointer->getType();
3257 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3259 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3260 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3261 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3263 // Convert back to the original type.
3264 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3265 return Pointer;
3268 llvm::Value *
3269 CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo &PointerAuth,
3270 llvm::Value *Pointer) {
3271 if (!PointerAuth.shouldSign())
3272 return Pointer;
3273 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3274 llvm::Intrinsic::ptrauth_sign);
3277 static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3278 const CGPointerAuthInfo &PointerAuth,
3279 llvm::Value *Pointer) {
3280 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3282 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3283 // Convert the pointer to intptr_t before signing it.
3284 auto OrigType = Pointer->getType();
3285 Pointer = CGF.EmitRuntimeCall(
3286 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3287 return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3290 llvm::Value *
3291 CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo &PointerAuth,
3292 llvm::Value *Pointer) {
3293 if (PointerAuth.shouldStrip()) {
3294 return EmitStrip(*this, PointerAuth, Pointer);
3296 if (!PointerAuth.shouldAuth()) {
3297 return Pointer;
3300 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3301 llvm::Intrinsic::ptrauth_auth);