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