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"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/Dominators.h"
45#include "llvm/IR/FPEnv.h"
46#include "llvm/IR/Instruction.h"
47#include "llvm/IR/IntrinsicInst.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/MDBuilder.h"
50#include "llvm/Support/CRC.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/SipHash.h"
53#include "llvm/Support/xxhash.h"
54#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
55#include "llvm/Transforms/Utils/PromoteMemToReg.h"
56#include <optional>
57
58using namespace clang;
59using namespace CodeGen;
60
61CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
62 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
63 Builder(cgm, cgm.getModule().getContext(), CGBuilderInserterTy(this)),
65 DebugInfo(CGM.getModuleDebugInfo()),
66 PGO(std::make_unique<CodeGenPGO>(cgm)),
67 ShouldEmitLifetimeMarkers(CodeGenUtils::shouldEmitLifetimeMarkers(
68 CGM.getCodeGenOpts(), CGM.getLangOpts())) {
69 if (!suppressNewContext)
70 CGM.getCXXABI().getMangleContext().startNewFunction();
71 EHStack.setCGF(this);
72
74}
75
77 const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
78 if (!FD)
79 FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
80 return FD;
81}
82
84 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
85 assert(DeferredDeactivationCleanupStack.empty() &&
86 "missed to deactivate a cleanup");
87
88 if (getLangOpts().OpenMP && CurFn) {
89 CGM.getOpenMPRuntime().functionFinished(*this);
90
91 // Finalizing (incl. outlining etc) once the function codegen is done, as
92 // opposed to the deletion time of the CodeGenModule, ensures the IR has
93 // not yet been "emitted" to the outside, thus, modifications are still
94 // sensible.
95 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
96 if (CGM.getLangOpts().OpenMPIRBuilder ||
97 OMPBuilder.hasPendingOutlines(CurFn))
98 OMPBuilder.finalize(CurFn);
99 }
100}
101
102// Map the LangOption for exception behavior into
103// the corresponding enum in the IR.
104llvm::fp::ExceptionBehavior
106
107 switch (Kind) {
108 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
109 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
110 case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
111 default:
112 llvm_unreachable("Unsupported FP Exception Behavior");
113 }
114}
115
117 llvm::FastMathFlags FMF;
118 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
119 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
120 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
121 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
122 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
123 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
124 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
125 Builder.setFastMathFlags(FMF);
126}
127
129 const Expr *E)
130 : CGF(CGF) {
131 ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
132}
133
135 FPOptions FPFeatures)
136 : CGF(CGF) {
137 ConstructorHelper(FPFeatures);
138}
139
140void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
141 OldFPFeatures = CGF.CurFPFeatures;
142 CGF.CurFPFeatures = FPFeatures;
143
144 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
145 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
146
147 if (OldFPFeatures == FPFeatures)
148 return;
149
150 FMFGuard.emplace(CGF.Builder);
151
152 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
153 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
154 auto NewExceptionBehavior =
156 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
157
158 CGF.SetFastMathFlags(FPFeatures);
159
160 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
161 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
162 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
163 (NewExceptionBehavior == llvm::fp::ebIgnore &&
164 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
165 "FPConstrained should be enabled on entire function");
166
167 auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
168 auto OldValue =
169 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
170 auto NewValue = OldValue & Value;
171 if (OldValue != NewValue)
172 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
173 };
174 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
175}
176
178 CGF.CurFPFeatures = OldFPFeatures;
179 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
180 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
181}
182
183static LValue
184makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType,
185 bool MightBeSigned, CodeGenFunction &CGF,
186 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
187 LValueBaseInfo BaseInfo;
188 TBAAAccessInfo TBAAInfo;
189 CharUnits Alignment =
190 CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType);
191 Address Addr =
192 MightBeSigned
193 ? CGF.makeNaturalAddressForPointer(V, T, Alignment, false, nullptr,
194 nullptr, IsKnownNonNull)
195 : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull);
196 return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
197}
198
199LValue
201 KnownNonNull_t IsKnownNonNull) {
202 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
203 /*MightBeSigned*/ true, *this,
204 IsKnownNonNull);
205}
206
207LValue
209 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
210 /*MightBeSigned*/ true, *this);
211}
212
214 QualType T) {
215 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
216 /*MightBeSigned*/ false, *this);
217}
218
220 QualType T) {
221 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
222 /*MightBeSigned*/ false, *this);
223}
224
226 return CGM.getTypes().ConvertTypeForMem(T);
227}
228
230 return CGM.getTypes().ConvertType(T);
231}
232
234 llvm::Type *LLVMTy) {
235 return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
236}
237
239 type = type.getCanonicalType();
240 while (true) {
241 switch (type->getTypeClass()) {
242#define TYPE(name, parent)
243#define ABSTRACT_TYPE(name, parent)
244#define NON_CANONICAL_TYPE(name, parent) case Type::name:
245#define DEPENDENT_TYPE(name, parent) case Type::name:
246#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
247#include "clang/AST/TypeNodes.inc"
248 llvm_unreachable("non-canonical or dependent type in IR-generation");
249
250 case Type::Auto:
251 case Type::DeducedTemplateSpecialization:
252 llvm_unreachable("undeduced type in IR-generation");
253
254 // Various scalar types.
255 case Type::Builtin:
256 case Type::Pointer:
257 case Type::BlockPointer:
258 case Type::LValueReference:
259 case Type::RValueReference:
260 case Type::MemberPointer:
261 case Type::Vector:
262 case Type::ExtVector:
263 case Type::ConstantMatrix:
264 case Type::CooperativeMatrix:
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 if (SanOpts.has(SanitizerKind::Concurrency)) {
693 Fn->addFnAttr("sanitize_concurrency_no_checking_at_run_time");
694 Fn->removeFnAttr(llvm::Attribute::SanitizeConcurrency);
695 }
696}
697
698/// Check if the return value of this function requires sanitization.
699bool CodeGenFunction::requiresReturnValueCheck() const {
700 return requiresReturnValueNullabilityCheck() ||
701 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
702 CurCodeDecl->getAttr<ReturnsNonNullAttr>()) ||
703 (SanOpts.has(SanitizerKind::Alignment) && CurCodeDecl &&
705 CurCodeDecl->getAttr<AllocAlignAttr>()) ||
706 CurCodeDecl->getAttr<AssumeAlignedAttr>()));
707}
708
709static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
710 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
711 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
712 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
713 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
714 return false;
715
716 if (!Ctx.hasSameType(MD->parameters()[0]->getType(), Ctx.getSizeType()))
717 return false;
718
719 if (MD->getNumParams() == 2) {
720 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
721 if (!PT || !PT->isVoidPointerType() ||
722 !PT->getPointeeType().isConstQualified())
723 return false;
724 }
725
726 return true;
727}
728
729bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
730 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
731 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
732}
733
734bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
735 return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
737 llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) {
738 return isInAllocaArgument(CGM.getCXXABI(), P->getType());
739 });
740}
741
742/// Return the UBSan prologue signature for \p FD if one is available.
743static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
744 const FunctionDecl *FD) {
745 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
746 if (!MD->isStatic())
747 return nullptr;
749}
750
752 llvm::Function *Fn,
753 const CGFunctionInfo &FnInfo,
754 const FunctionArgList &Args,
755 SourceLocation Loc,
756 SourceLocation StartLoc) {
757 assert(!CurFn &&
758 "Do not use a CodeGenFunction object for more than one function");
759
760 const Decl *D = GD.getDecl();
761
762 DidCallStackSave = false;
763 CurCodeDecl = D;
764 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
765 if (FD && FD->usesSEHTry())
766 CurSEHParent = GD;
767 if (const Stmt *Body = D ? D->getBody() : nullptr) {
768 // Coroutines always emit lifetime markers.
769 if (isa<CoroutineBodyStmt>(Body))
770 ShouldEmitLifetimeMarkers = true;
771
772 // Detect jumps that invalidate lifetime markers or bypass auto-var-init.
773 bool NeedsBypassDetection =
774 ShouldEmitLifetimeMarkers ||
775 (CGM.getLangOpts().getTrivialAutoVarInit() !=
777 if (NeedsBypassDetection)
778 Bypasses.Init(CGM, Body);
779 }
780 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
781 FnRetTy = RetTy;
782 CurFn = Fn;
783 CurFnInfo = &FnInfo;
784 assert(CurFn->isDeclaration() && "Function already has body?");
785
786 // If this function is ignored for any of the enabled sanitizers,
787 // disable the sanitizer for the function.
788 do {
789#define SANITIZER(NAME, ID) \
790 if (SanOpts.empty()) \
791 break; \
792 if (SanOpts.has(SanitizerKind::ID)) \
793 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
794 SanOpts.set(SanitizerKind::ID, false);
795
796#include "clang/Basic/Sanitizers.def"
797#undef SANITIZER
798 } while (false);
799
800 if (D) {
801 const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
802 SanitizerMask no_sanitize_mask;
803 bool NoSanitizeCoverage = false;
804
805 for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
806 no_sanitize_mask |= Attr->getMask();
807 // SanitizeCoverage is not handled by SanOpts.
808 if (Attr->hasCoverage())
809 NoSanitizeCoverage = true;
810 }
811
812 // Apply the no_sanitize* attributes to SanOpts.
813 SanOpts.Mask &= ~no_sanitize_mask;
814 if (no_sanitize_mask & SanitizerKind::Address)
815 SanOpts.set(SanitizerKind::KernelAddress, false);
816 if (no_sanitize_mask & SanitizerKind::KernelAddress)
817 SanOpts.set(SanitizerKind::Address, false);
818 if (no_sanitize_mask & SanitizerKind::HWAddress)
819 SanOpts.set(SanitizerKind::KernelHWAddress, false);
820 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
821 SanOpts.set(SanitizerKind::HWAddress, false);
822
823 if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
824 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
825
826 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
827 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
828
829 // Some passes need the non-negated no_sanitize attribute. Pass them on.
830 if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
831 if (no_sanitize_mask & SanitizerKind::Thread)
832 Fn->addFnAttr("no_sanitize_thread");
833 }
834 }
835
837 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
838 } else {
839 // Apply sanitizer attributes to the function.
840 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
841 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
842 if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
843 SanitizerKind::KernelHWAddress))
844 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
845 if (SanOpts.has(SanitizerKind::MemtagStack))
846 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
847 if (SanOpts.has(SanitizerKind::Thread))
848 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
849 if (SanOpts.has(SanitizerKind::Concurrency))
850 Fn->addFnAttr(llvm::Attribute::SanitizeConcurrency);
851 if (SanOpts.has(SanitizerKind::Type))
852 Fn->addFnAttr(llvm::Attribute::SanitizeType);
853 if (SanOpts.has(SanitizerKind::NumericalStability))
854 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
855 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
856 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
857 if (SanOpts.has(SanitizerKind::AllocToken))
858 Fn->addFnAttr(llvm::Attribute::SanitizeAllocToken);
859 }
860 if (SanOpts.has(SanitizerKind::SafeStack))
861 Fn->addFnAttr(llvm::Attribute::SafeStack);
862 if (SanOpts.has(SanitizerKind::ShadowCallStack))
863 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
864
865 if (SanOpts.has(SanitizerKind::Realtime))
866 if (FD && FD->getASTContext().hasAnyFunctionEffects())
867 for (const FunctionEffectWithCondition &Fe : FD->getFunctionEffects()) {
868 if (Fe.Effect.kind() == FunctionEffect::Kind::NonBlocking)
869 Fn->addFnAttr(llvm::Attribute::SanitizeRealtime);
870 else if (Fe.Effect.kind() == FunctionEffect::Kind::Blocking)
871 Fn->addFnAttr(llvm::Attribute::SanitizeRealtimeBlocking);
872 }
873
874 // Apply fuzzing attribute to the function.
875 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
876 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
877
878 // Ignore TSan/CSan memory accesses from within ObjC/ObjC++ dealloc,
879 // initialize, .cxx_destruct, __destroy_helper_block_ and all of their callees
880 // at run time.
881 if (SanOpts.hasOneOf(SanitizerKind::Thread | SanitizerKind::Concurrency)) {
882 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
883 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
884 if (OMD->getMethodFamily() == OMF_dealloc ||
885 OMD->getMethodFamily() == OMF_initialize ||
886 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
888 }
889 }
890 }
891
892 // Ignore unrelated casts in STL allocate() since the allocator must cast
893 // from void* to T* before object initialization completes. Don't match on the
894 // namespace because not all allocators are in std::
895 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
897 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
898 }
899
900 // Ignore null checks in coroutine functions since the coroutines passes
901 // are not aware of how to move the extra UBSan instructions across the split
902 // coroutine boundaries.
903 if (D && SanOpts.has(SanitizerKind::Null))
904 if (FD && FD->getBody() &&
905 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
907
908 // Apply xray attributes to the function (as a string, for now)
909 bool AlwaysXRayAttr = false;
910 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
911 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
913 CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
915 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
916 Fn->addFnAttr("function-instrument", "xray-always");
917 AlwaysXRayAttr = true;
918 }
919 if (XRayAttr->neverXRayInstrument())
920 Fn->addFnAttr("function-instrument", "xray-never");
921 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
923 Fn->addFnAttr("xray-log-args",
924 llvm::utostr(LogArgs->getArgumentCount()));
925 }
926 } else {
927 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
928 Fn->addFnAttr(
929 "xray-instruction-threshold",
930 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
931 }
932
934 if (CGM.getCodeGenOpts().XRayIgnoreLoops)
935 Fn->addFnAttr("xray-ignore-loops");
936
937 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
939 Fn->addFnAttr("xray-skip-exit");
940
941 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
943 Fn->addFnAttr("xray-skip-entry");
944
945 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
946 if (FuncGroups > 1) {
947 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
948 CurFn->getName().bytes_end());
949 auto Group = crc32(FuncName) % FuncGroups;
950 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
951 !AlwaysXRayAttr)
952 Fn->addFnAttr("function-instrument", "xray-never");
953 }
954 }
955
956 if (CGM.getCodeGenOpts().getProfileInstr() !=
957 llvm::driver::ProfileInstrKind::ProfileNone) {
958 switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
960 Fn->addFnAttr(llvm::Attribute::SkipProfile);
961 break;
963 Fn->addFnAttr(llvm::Attribute::NoProfile);
964 break;
966 break;
967 }
968 }
969
970 unsigned Count, Offset;
971 StringRef Section;
972 if (const auto *Attr =
973 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
974 Count = Attr->getCount();
975 Offset = Attr->getOffset();
976 Section = Attr->getSection();
977 } else {
978 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
979 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
980 }
981 if (Section.empty())
982 Section = CGM.getCodeGenOpts().PatchableFunctionEntrySection;
983 if (Count && Offset <= Count) {
984 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
985 if (Offset)
986 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
987 if (!Section.empty())
988 Fn->addFnAttr("patchable-function-entry-section", Section);
989 }
990 // Instruct that functions for COFF/CodeView targets should start with a
991 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
992 // backends as they don't need it -- instructions on these architectures are
993 // always atomically patchable at runtime.
994 if (CGM.getCodeGenOpts().HotPatch &&
995 getContext().getTargetInfo().getTriple().isX86() &&
996 getContext().getTargetInfo().getTriple().getEnvironment() !=
997 llvm::Triple::CODE16)
998 Fn->addFnAttr("patchable-function", "prologue-short-redirect");
999
1000 // Add no-jump-tables value.
1001 if (CGM.getCodeGenOpts().NoUseJumpTables)
1002 Fn->addFnAttr("no-jump-tables", "true");
1003
1004 // Add no-inline-line-tables value.
1005 if (CGM.getCodeGenOpts().NoInlineLineTables)
1006 Fn->addFnAttr("no-inline-line-tables");
1007
1008 // Add profile-sample-accurate value.
1009 if (CGM.getCodeGenOpts().ProfileSampleAccurate)
1010 Fn->addFnAttr("profile-sample-accurate");
1011
1012 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
1013 Fn->addFnAttr("use-sample-profile");
1014
1015 if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
1016 Fn->addFnAttr("cfi-canonical-jump-table");
1017
1018 if (D && D->hasAttr<NoProfileFunctionAttr>())
1019 Fn->addFnAttr(llvm::Attribute::NoProfile);
1020
1021 if (D && D->hasAttr<HybridPatchableAttr>())
1022 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
1023
1024 if (D) {
1025 // Function attributes take precedence over command line flags.
1026 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1027 switch (A->getThunkType()) {
1028 case FunctionReturnThunksAttr::Kind::Keep:
1029 break;
1030 case FunctionReturnThunksAttr::Kind::Extern:
1031 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1032 break;
1033 }
1034 } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1035 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1036 }
1037
1038 if (FD && (getLangOpts().OpenCL ||
1039 (getLangOpts().CUDA &&
1040 getContext().getTargetInfo().getTriple().isSPIRV()) ||
1041 ((getLangOpts().HIP || getLangOpts().OffloadViaLLVM) &&
1042 getLangOpts().CUDAIsDevice))) {
1043 // Add metadata for a kernel function.
1044 EmitKernelMetadata(FD, Fn);
1045 }
1046
1047 if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
1048 Fn->setMetadata("clspv_libclc_builtin",
1049 llvm::MDNode::get(getLLVMContext(), {}));
1050 }
1051
1052 // If we are checking function types, emit a function type signature as
1053 // prologue data. Kernel functions have strict alignment requirements and
1054 // cannot be call indirectly so we do not instrument them.
1055 if (FD && SanOpts.has(SanitizerKind::Function) &&
1057 llvm::isCallableCC(Fn->getCallingConv())) {
1058 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1059 llvm::LLVMContext &Ctx = Fn->getContext();
1060 llvm::MDBuilder MDB(Ctx);
1061 Fn->setMetadata(
1062 llvm::LLVMContext::MD_func_sanitize,
1063 MDB.createRTTIPointerPrologue(
1064 PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
1065 }
1066 }
1067
1068 // If we're checking nullability, we need to know whether we can check the
1069 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1070 if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1071 auto Nullability = FnRetTy->getNullability();
1072 if (Nullability && *Nullability == NullabilityKind::NonNull &&
1073 !FnRetTy->isRecordType()) {
1074 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1075 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1076 RetValNullabilityPrecondition =
1077 llvm::ConstantInt::getTrue(getLLVMContext());
1078 }
1079 }
1080
1081 // Annotate C++ special member functions so that CopyProfPass can instrument
1082 // them, provided the object is at least as large as the size threshold.
1083 if (CGM.getCodeGenOpts().CopyProf) {
1084 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1085 StringRef Attr;
1086 if (const auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
1087 if (!CD->isMoveConstructor())
1088 Attr =
1089 CD->isCopyConstructor() ? "copyprof-copy-ctor" : "copyprof-ctor";
1090 } else if (isa<CXXDestructorDecl>(MD)) {
1091 Attr = "copyprof-dtor";
1092 } else if (MD->isCopyAssignmentOperator()) {
1093 Attr = "copyprof-copy-assign-op";
1094 }
1095 if (!Attr.empty()) {
1096 // Finally, add the object size in bytes to the annotation.
1097 // A special member function always has an implicit object parameter, so
1098 // its type is guaranteed to be complete here.
1101 if (ObjSize.getQuantity() >=
1102 CGM.getCodeGenOpts().CopyProfStaticSizeThreshold)
1103 Fn->addFnAttr(Attr, llvm::utostr(ObjSize.getQuantity()));
1104 }
1105 }
1106 }
1107
1108 // If we're in C++ mode and the function name is "main", it is guaranteed
1109 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1110 // used within a program").
1111 //
1112 // OpenCL C 2.0 v2.2-11 s6.9.i:
1113 // Recursion is not supported.
1114 //
1115 // HLSL
1116 // Recursion is not supported.
1117 //
1118 // SYCL v1.2.1 s3.10:
1119 // kernels cannot include RTTI information, exception classes,
1120 // recursive code, virtual functions or make use of C++ libraries that
1121 // are not compiled for the device.
1122 if (FD &&
1123 ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
1124 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
1125 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1126 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1127
1128 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1129 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1130 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1131 Builder.setDefaultConstrainedRounding(RM);
1132 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1133 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1134 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1135 RM != llvm::RoundingMode::NearestTiesToEven))) {
1136 Builder.setIsFPConstrained(true);
1137 Fn->addFnAttr(llvm::Attribute::StrictFP);
1138 }
1139
1140 // If a custom alignment is used, force realigning to this alignment on
1141 // any main function which certainly will need it.
1142 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1143 CGM.getCodeGenOpts().StackAlignment))
1144 Fn->addFnAttr("stackrealign");
1145
1146 // Add vscale_range attribute if appropriate.
1147 auto IsArmStreaming = TargetInfo::ArmStreamingKind::NotStreaming;
1148 if (FD) {
1149 if (const auto *T = FD->getType()->getAs<FunctionProtoType>())
1150 if (T->getAArch64SMEAttributes() &
1153
1154 if (IsArmStreamingFunction(FD, true))
1156 }
1157 const auto *FeatureMap =
1158 FD ? &getContext().getFunctionFeatureMap(FD) : nullptr;
1159 if (auto VScaleRange = getContext().getTargetInfo().getVScaleRange(
1160 getLangOpts(), IsArmStreaming, FeatureMap))
1161 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1162 getLLVMContext(), VScaleRange->first, VScaleRange->second));
1163
1164 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1165
1166 // Create a marker to make it easy to insert allocas into the entryblock
1167 // later. Don't create this with the builder, because we don't want it
1168 // folded.
1169 llvm::Value *Poison = llvm::PoisonValue::get(Int32Ty);
1170 AllocaInsertPt = new llvm::BitCastInst(Poison, Int32Ty, "allocapt", EntryBB);
1171
1173
1174 Builder.SetInsertPoint(EntryBB);
1175
1176 // If we're checking the return value, allocate space for a pointer to a
1177 // precise source location of the checked return statement.
1178 if (requiresReturnValueCheck()) {
1179 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1180 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1181 ReturnLocation);
1182 }
1183
1184 // Emit subprogram debug descriptor.
1185 if (CGDebugInfo *DI = getDebugInfo()) {
1186 // Reconstruct the type from the argument list so that implicit parameters,
1187 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1188 // convention.
1189 DI->emitFunctionStart(GD, Loc, StartLoc,
1190 DI->getFunctionType(FD, RetTy, Args), CurFn,
1192 }
1193
1195 if (CGM.getCodeGenOpts().InstrumentFunctions)
1196 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1197 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1198 CurFn->addFnAttr("instrument-function-entry-inlined",
1199 "__cyg_profile_func_enter");
1200 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1201 CurFn->addFnAttr("instrument-function-entry-inlined",
1202 "__cyg_profile_func_enter_bare");
1203 }
1204
1205 // Since emitting the mcount call here impacts optimizations such as function
1206 // inlining, we just add an attribute to insert a mcount call in backend.
1207 // The attribute "counting-function" is set to mcount function name which is
1208 // architecture dependent.
1209 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1210 // Calls to fentry/mcount should not be generated if function has
1211 // the no_instrument_function attribute.
1212 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1213 if (CGM.getCodeGenOpts().CallFEntry)
1214 Fn->addFnAttr("fentry-call", "true");
1215 else {
1216 Fn->addFnAttr("instrument-function-entry-inlined",
1217 getTarget().getMCountName());
1218 }
1219 if (CGM.getCodeGenOpts().MNopMCount) {
1220 if (!CGM.getCodeGenOpts().CallFEntry)
1221 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1222 << "-mnop-mcount" << "-mfentry";
1223 Fn->addFnAttr("mnop-mcount");
1224 }
1225
1226 if (CGM.getCodeGenOpts().RecordMCount) {
1227 if (!CGM.getCodeGenOpts().CallFEntry)
1228 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1229 << "-mrecord-mcount" << "-mfentry";
1230 Fn->addFnAttr("mrecord-mcount");
1231 }
1232 }
1233 }
1234
1235 if (CGM.getCodeGenOpts().PackedStack) {
1236 if (getContext().getTargetInfo().getTriple().getArch() !=
1237 llvm::Triple::systemz)
1238 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1239 << "-mpacked-stack";
1240 Fn->addFnAttr("packed-stack");
1241 }
1242
1243 if (!CGM.getCodeGenOpts().ZOSPPA1Name)
1244 Fn->addFnAttr("zos-ppa1-name", "");
1245 else if (getContext().getTargetInfo().getTriple().isOSzOS() && FD &&
1246 FD->hasAttr<AsmLabelAttr>()) {
1247 std::string SrcName = CGM.getMangledNameIgnoringAsmLabel(GD, FD);
1248 Fn->addFnAttr("zos-ppa1-name", SrcName);
1249 }
1250
1251 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1252 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1253 Fn->addFnAttr("warn-stack-size",
1254 std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1255
1256 if (RetTy->isVoidType()) {
1257 // Void type; nothing to return.
1259
1260 // Count the implicit return.
1261 if (!endsWithReturn(D))
1262 ++NumReturnExprs;
1263 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1264 // Indirect return; emit returned value directly into sret slot.
1265 // This reduces code size, and affects correctness in C++.
1266 auto AI = CurFn->arg_begin();
1267 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1268 ++AI;
1270 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1271 nullptr, nullptr, KnownNonNull);
1272 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1274 CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
1275 Builder.CreateStore(ReturnValue.emitRawPointer(*this),
1277 }
1278 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1279 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1280 // Load the sret pointer from the argument struct and return into that.
1281 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1282 llvm::Function::arg_iterator EI = CurFn->arg_end();
1283 --EI;
1284 llvm::Value *Addr = Builder.CreateStructGEP(
1285 CurFnInfo->getArgStruct(), &*EI, Idx);
1286 llvm::Type *Ty =
1287 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1289 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1291 CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
1292 } else {
1293 ReturnValue = CreateIRTempWithoutCast(RetTy, "retval");
1294
1295 // Tell the epilog emitter to autorelease the result. We do this
1296 // now so that various specialized functions can suppress it
1297 // during their IR-generation.
1298 if (getLangOpts().ObjCAutoRefCount &&
1299 !CurFnInfo->isReturnsRetained() &&
1300 RetTy->isObjCRetainableType())
1301 AutoreleaseResult = true;
1302 }
1303
1305
1306 PrologueCleanupDepth = EHStack.stable_begin();
1307
1308 // Emit OpenMP specific initialization of the device functions.
1309 if (getLangOpts().OpenMP && CurCodeDecl)
1310 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1311
1312 if (FD && getLangOpts().HLSL) {
1313 // Handle emitting HLSL entry functions.
1314 if (FD->hasAttr<HLSLShaderAttr>()) {
1315 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1316 }
1317 }
1318
1320
1321 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1322 MD && !MD->isStatic()) {
1323 bool IsInLambda =
1324 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1326 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1327 if (IsInLambda) {
1328 // We're in a lambda; figure out the captures.
1332 // If the lambda captures the object referred to by '*this' - either by
1333 // value or by reference, make sure CXXThisValue points to the correct
1334 // object.
1335
1336 // Get the lvalue for the field (which is a copy of the enclosing object
1337 // or contains the address of the enclosing object).
1339 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1340 // If the enclosing object was captured by value, just use its
1341 // address. Sign this pointer.
1342 CXXThisValue = ThisFieldLValue.getPointer(*this);
1343 } else {
1344 // Load the lvalue pointed to by the field, since '*this' was captured
1345 // by reference.
1346 CXXThisValue =
1347 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1348 }
1349 }
1350 for (auto *FD : MD->getParent()->fields()) {
1351 if (FD->hasCapturedVLAType()) {
1352 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1354 auto VAT = FD->getCapturedVLAType();
1355 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1356 }
1357 }
1358 } else if (MD->isImplicitObjectMemberFunction()) {
1359 // Not in a lambda; just use 'this' from the method.
1360 // FIXME: Should we generate a new load for each use of 'this'? The
1361 // fast register allocator would be happier...
1362 CXXThisValue = CXXABIThisValue;
1363 }
1364
1365 // Check the 'this' pointer once per function, if it's available.
1366 if (CXXABIThisValue) {
1367 SanitizerSet SkippedChecks;
1368 SkippedChecks.set(SanitizerKind::ObjectSize, true);
1369 QualType ThisTy = MD->getThisType();
1370
1371 // If this is the call operator of a lambda with no captures, it
1372 // may have a static invoker function, which may call this operator with
1373 // a null 'this' pointer.
1375 SkippedChecks.set(SanitizerKind::Null, true);
1376
1379 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1380 }
1381 }
1382
1383 // If any of the arguments have a variably modified type, make sure to
1384 // emit the type size, but only if the function is not naked. Naked functions
1385 // have no prolog to run this evaluation.
1386 if (!FD || !FD->hasAttr<NakedAttr>()) {
1387 for (const VarDecl *VD : Args) {
1388 // Dig out the type as written from ParmVarDecls; it's unclear whether
1389 // the standard (C99 6.9.1p10) requires this, but we're following the
1390 // precedent set by gcc.
1391 QualType Ty;
1392 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1393 Ty = PVD->getOriginalType();
1394 else
1395 Ty = VD->getType();
1396
1397 if (Ty->isVariablyModifiedType())
1399 }
1400 }
1401 // Emit a location at the end of the prologue.
1402 if (CGDebugInfo *DI = getDebugInfo())
1403 DI->EmitLocation(Builder, StartLoc);
1404 // TODO: Do we need to handle this in two places like we do with
1405 // target-features/target-cpu?
1406 if (CurFuncDecl)
1407 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1408 LargestVectorWidth = VecWidth->getVectorWidth();
1409
1410 if (CGM.shouldEmitConvergenceTokens())
1411 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1412}
1413
1417 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1419 else
1420 EmitStmt(Body);
1421}
1422
1423/// When instrumenting to collect profile data, the counts for some blocks
1424/// such as switch cases need to not include the fall-through counts, so
1425/// emit a branch around the instrumentation code. When not instrumenting,
1426/// this just calls EmitBlock().
1428 const Stmt *S) {
1429 llvm::BasicBlock *SkipCountBB = nullptr;
1430 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1431 // When instrumenting for profiling, the fallthrough to certain
1432 // statements needs to skip over the instrumentation code so that we
1433 // get an accurate count.
1434 SkipCountBB = createBasicBlock("skipcount");
1435 EmitBranch(SkipCountBB);
1436 }
1437 EmitBlock(BB);
1438 uint64_t CurrentCount = getCurrentProfileCount();
1441 if (SkipCountBB)
1442 EmitBlock(SkipCountBB);
1443}
1444
1445/// Tries to mark the given function nounwind based on the
1446/// non-existence of any throwing calls within it. We believe this is
1447/// lightweight enough to do at -O0.
1448static void TryMarkNoThrow(llvm::Function *F) {
1449 // LLVM treats 'nounwind' on a function as part of the type, so we
1450 // can't do this on functions that can be overwritten.
1451 if (F->isInterposable()) return;
1452
1453 for (llvm::BasicBlock &BB : *F)
1454 for (llvm::Instruction &I : BB)
1455 if (I.mayThrow())
1456 return;
1457
1458 F->setDoesNotThrow();
1459}
1460
1462 FunctionArgList &Args) {
1463 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1464 QualType ResTy = FD->getReturnType();
1465
1466 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1467 if (MD && MD->isImplicitObjectMemberFunction()) {
1468 if (CGM.getCXXABI().HasThisReturn(GD))
1469 ResTy = MD->getThisType();
1470 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1471 ResTy = CGM.getContext().VoidPtrTy;
1472 CGM.getCXXABI().buildThisParam(*this, Args);
1473 }
1474
1475 // The base version of an inheriting constructor whose constructed base is a
1476 // virtual base is not passed any arguments (because it doesn't actually call
1477 // the inherited constructor).
1478 bool PassedParams = true;
1479 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1480 if (auto Inherited = CD->getInheritedConstructor())
1481 PassedParams =
1482 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1483
1484 if (PassedParams) {
1485 for (auto *Param : FD->parameters()) {
1486 Args.push_back(Param);
1487 if (!Param->hasAttr<PassObjectSizeAttr>())
1488 continue;
1489
1491 getContext(), Param->getDeclContext(), Param->getLocation(),
1492 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1493 SizeArguments[Param] = Implicit;
1494 Args.push_back(Implicit);
1495 }
1496 }
1497
1498 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1499 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1500
1501 return ResTy;
1502}
1503
1504void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1505 const CGFunctionInfo &FnInfo) {
1506 assert(Fn && "generating code for null Function");
1507 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1508 CurGD = GD;
1509
1510 FunctionArgList Args;
1511 QualType ResTy = BuildFunctionArgList(GD, Args);
1512
1513 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
1514
1515 if (FD->isInlineBuiltinDeclaration()) {
1516 // When generating code for a builtin with an inline declaration, use a
1517 // mangled name to hold the actual body, while keeping an external
1518 // definition in case the function pointer is referenced somewhere.
1519 std::string FDInlineName = (Fn->getName() + ".inline").str();
1520 llvm::Module *M = Fn->getParent();
1521 llvm::Function *Clone = M->getFunction(FDInlineName);
1522 if (!Clone) {
1523 Clone = llvm::Function::Create(Fn->getFunctionType(),
1524 llvm::GlobalValue::InternalLinkage,
1525 Fn->getAddressSpace(), FDInlineName, M);
1526 Clone->setCallingConv(Fn->getCallingConv());
1527 Clone->setAttributes(Fn->getAttributes());
1528 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1529 }
1530 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1531 Fn = Clone;
1532 } else {
1533 // Detect the unusual situation where an inline version is shadowed by a
1534 // non-inline version. In that case we should pick the external one
1535 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1536 // to detect that situation before we reach codegen, so do some late
1537 // replacement.
1538 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1539 PD = PD->getPreviousDecl()) {
1540 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1541 std::string FDInlineName = (Fn->getName() + ".inline").str();
1542 llvm::Module *M = Fn->getParent();
1543 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1544 Clone->replaceAllUsesWith(Fn);
1545 Clone->eraseFromParent();
1546 }
1547 break;
1548 }
1549 }
1550 }
1551
1552 // Check if we should generate debug info for this function.
1553 if (FD->hasAttr<NoDebugAttr>()) {
1554 // Clear non-distinct debug info that was possibly attached to the function
1555 // due to an earlier declaration without the nodebug attribute
1556 Fn->setSubprogram(nullptr);
1557 // Disable debug info indefinitely for this function
1558 DebugInfo = nullptr;
1559 }
1560 // Finalize function debug info on exit.
1561 llvm::scope_exit Cleanup([this] {
1562 if (CGDebugInfo *DI = getDebugInfo())
1563 DI->completeFunction();
1564 });
1565
1566 // The function might not have a body if we're generating thunks for a
1567 // function declaration.
1568 SourceRange BodyRange;
1569 if (Stmt *Body = FD->getBody())
1570 BodyRange = Body->getSourceRange();
1571 else
1572 BodyRange = FD->getLocation();
1573 CurEHLocation = BodyRange.getEnd();
1574
1575 // Use the location of the start of the function to determine where
1576 // the function definition is located. By default use the location
1577 // of the declaration as the location for the subprogram. A function
1578 // may lack a declaration in the source code if it is created by code
1579 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1580 SourceLocation Loc = FD->getLocation();
1581
1582 // If this is a function specialization then use the pattern body
1583 // as the location for the function.
1584 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1585 if (SpecDecl->hasBody(SpecDecl))
1586 Loc = SpecDecl->getLocation();
1587
1588 Stmt *Body = FD->getBody();
1589
1590 // Emit the standard function prologue.
1591 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1592
1593 // Save parameters for coroutine function.
1594 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1595 llvm::append_range(FnArgs, FD->parameters());
1596
1597 // Ensure that the function adheres to the forward progress guarantee, which
1598 // is required by certain optimizations.
1599 // In C++11 and up, the attribute will be removed if the body contains a
1600 // trivial empty loop.
1602 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1603
1604 // Generate the body of the function.
1605 PGO->assignRegionCounters(GD, CurFn);
1606 if (isa<CXXDestructorDecl>(FD))
1607 EmitDestructorBody(Args);
1608 else if (isa<CXXConstructorDecl>(FD))
1609 EmitConstructorBody(Args);
1610 else if (getLangOpts().CUDA &&
1611 !getLangOpts().CUDAIsDevice &&
1612 FD->hasAttr<CUDAGlobalAttr>())
1613 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1614 else if (isa<CXXMethodDecl>(FD) &&
1615 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1616 // The lambda static invoker function is special, because it forwards or
1617 // clones the body of the function call operator (but is actually static).
1619 } else if (isa<CXXMethodDecl>(FD) &&
1621 !FnInfo.isDelegateCall() &&
1622 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1623 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1624 // If emitting a lambda with static invoker on X86 Windows, change
1625 // the call operator body.
1626 // Make sure that this is a call operator with an inalloca arg and check
1627 // for delegate call to make sure this is the original call op and not the
1628 // new forwarding function for the static invoker.
1630 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1631 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1632 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1633 // Implicit copy-assignment gets the same special treatment as implicit
1634 // copy-constructors.
1636 } else if (DeviceKernelAttr::isOpenCLSpelling(
1637 FD->getAttr<DeviceKernelAttr>()) &&
1639 CallArgList CallArgs;
1640 for (unsigned i = 0; i < Args.size(); ++i) {
1641 Address ArgAddr = GetAddrOfLocalVar(Args[i]);
1642 QualType ArgQualType = Args[i]->getType();
1643 RValue ArgRValue = convertTempToRValue(ArgAddr, ArgQualType, Loc);
1644 CallArgs.add(ArgRValue, ArgQualType);
1645 }
1647 const FunctionType *FT = cast<FunctionType>(FD->getType());
1648 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1649 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
1650 CallArgs, FT, /*ChainCall=*/false, getCurrentFunctionDecl());
1651 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FnInfo);
1652 llvm::Constant *GDStubFunctionPointer =
1653 CGM.getRawFunctionPointer(GDStub, FTy);
1654 CGCallee GDStubCallee = CGCallee::forDirect(GDStubFunctionPointer, GDStub);
1655 EmitCall(FnInfo, GDStubCallee, ReturnValueSlot(), CallArgs, nullptr, false,
1656 Loc);
1657 } else if (Body) {
1658 EmitFunctionBody(Body);
1659 } else
1660 llvm_unreachable("no definition for emitted function");
1661
1662 // C++11 [stmt.return]p2:
1663 // Flowing off the end of a function [...] results in undefined behavior in
1664 // a value-returning function.
1665 // C11 6.9.1p12:
1666 // If the '}' that terminates a function is reached, and the value of the
1667 // function call is used by the caller, the behavior is undefined.
1669 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1670 bool ShouldEmitUnreachable =
1671 CGM.getCodeGenOpts().StrictReturn ||
1672 !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1673 if (SanOpts.has(SanitizerKind::Return)) {
1674 auto CheckOrdinal = SanitizerKind::SO_Return;
1675 auto CheckHandler = SanitizerHandler::MissingReturn;
1676 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
1677 llvm::Value *IsFalse = Builder.getFalse();
1678 EmitCheck(std::make_pair(IsFalse, CheckOrdinal), CheckHandler,
1680 } else if (ShouldEmitUnreachable) {
1681 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1682 EmitTrapCall(llvm::Intrinsic::trap);
1683 }
1684 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1685 Builder.CreateUnreachable();
1686 Builder.ClearInsertionPoint();
1687 }
1688 }
1689
1690 // Emit the standard function epilogue.
1691 FinishFunction(BodyRange.getEnd());
1692
1693 PGO->verifyCounterMap();
1694
1695 if (CurCodeDecl->hasAttr<PersonalityAttr>()) {
1696 StringRef Identifier =
1697 CurCodeDecl->getAttr<PersonalityAttr>()->getRoutine()->getName();
1698 llvm::FunctionCallee PersonalityRoutine =
1699 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
1700 Identifier, {}, /*local=*/true);
1701 Fn->setPersonalityFn(cast<llvm::Constant>(PersonalityRoutine.getCallee()));
1702 }
1703
1704 // If we haven't marked the function nothrow through other means, do
1705 // a quick pass now to see if we can.
1706 if (!CurFn->doesNotThrow())
1708}
1709
1710/// ContainsLabel - Return true if the statement contains a label in it. If
1711/// this statement is not executed normally, it not containing a label means
1712/// that we can just remove the code.
1713bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1714 // Null statement, not a label!
1715 if (!S) return false;
1716
1717 // If this is a label, we have to emit the code, consider something like:
1718 // if (0) { ... foo: bar(); } goto foo;
1719 //
1720 // TODO: If anyone cared, we could track __label__'s, since we know that you
1721 // can't jump to one from outside their declared region.
1722 if (isa<LabelStmt>(S))
1723 return true;
1724
1725 // If this is a case/default statement, and we haven't seen a switch, we have
1726 // to emit the code.
1727 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1728 return true;
1729
1730 // If this is a switch statement, we want to ignore cases below it.
1731 if (isa<SwitchStmt>(S))
1732 IgnoreCaseStmts = true;
1733
1734 // Scan subexpressions for verboten labels.
1735 for (const Stmt *SubStmt : S->children())
1736 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1737 return true;
1738
1739 return false;
1740}
1741
1742/// containsBreak - Return true if the statement contains a break out of it.
1743/// If the statement (recursively) contains a switch or loop with a break
1744/// inside of it, this is fine.
1746 // Null statement, not a label!
1747 if (!S) return false;
1748
1749 // If this is a switch or loop that defines its own break scope, then we can
1750 // include it and anything inside of it.
1751 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1752 isa<ForStmt>(S))
1753 return false;
1754
1755 if (isa<BreakStmt>(S))
1756 return true;
1757
1758 // Scan subexpressions for verboten breaks.
1759 for (const Stmt *SubStmt : S->children())
1760 if (containsBreak(SubStmt))
1761 return true;
1762
1763 return false;
1764}
1765
1767 if (!S) return false;
1768
1769 // Some statement kinds add a scope and thus never add a decl to the current
1770 // scope. Note, this list is longer than the list of statements that might
1771 // have an unscoped decl nested within them, but this way is conservatively
1772 // correct even if more statement kinds are added.
1773 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1777 return false;
1778
1779 if (isa<DeclStmt>(S))
1780 return true;
1781
1782 for (const Stmt *SubStmt : S->children())
1783 if (mightAddDeclToScope(SubStmt))
1784 return true;
1785
1786 return false;
1787}
1788
1789/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1790/// to a constant, or if it does but contains a label, return false. If it
1791/// constant folds return true and set the boolean result in Result.
1793 bool &ResultBool,
1794 bool AllowLabels) {
1795 // If MC/DC is enabled, disable folding so that we can instrument all
1796 // conditions to yield complete test vectors. We still keep track of
1797 // folded conditions during region mapping and visualization.
1798 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1799 CGM.getCodeGenOpts().MCDCCoverage)
1800 return false;
1801
1802 llvm::APSInt ResultInt;
1803 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1804 return false;
1805
1806 ResultBool = ResultInt.getBoolValue();
1807 return true;
1808}
1809
1810/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1811/// to a constant, or if it does but contains a label, return false. If it
1812/// constant folds return true and set the folded value.
1814 llvm::APSInt &ResultInt,
1815 bool AllowLabels) {
1816 // FIXME: Rename and handle conversion of other evaluatable things
1817 // to bool.
1819 if (!Cond->EvaluateAsInt(Result, getContext()))
1820 return false; // Not foldable, not integer or not fully evaluatable.
1821
1822 llvm::APSInt Int = Result.Val.getInt();
1823 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1824 return false; // Contains a label.
1825
1826 PGO->markStmtMaybeUsed(Cond);
1827 ResultInt = std::move(Int);
1828 return true;
1829}
1830
1831/// Strip parentheses and simplistic logical-NOT operators.
1833 while (true) {
1834 const Expr *SC = IgnoreExprNodes(
1837 if (C == SC)
1838 return SC;
1839 C = SC;
1840 }
1841}
1842
1843/// Determine whether the given condition is an instrumentable condition
1844/// (i.e. no "&&" or "||").
1846 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1847 return (!BOp || !BOp->isLogicalOp());
1848}
1849
1850/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1851/// increments a profile counter based on the semantics of the given logical
1852/// operator opcode. This is used to instrument branch condition coverage for
1853/// logical operators.
1855 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1856 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1857 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1858 // If not instrumenting, just emit a branch.
1859 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1860 if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1861 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1862
1863 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1864
1865 llvm::BasicBlock *ThenBlock = nullptr;
1866 llvm::BasicBlock *ElseBlock = nullptr;
1867 llvm::BasicBlock *NextBlock = nullptr;
1868
1869 // Create the block we'll use to increment the appropriate counter.
1870 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1871
1872 llvm::BasicBlock *SkipIncrBlock =
1873 (hasSkipCounter(CntrStmt) ? createBasicBlock("lop.rhsskip") : nullptr);
1874 llvm::BasicBlock *SkipNextBlock = nullptr;
1875
1876 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1877 // means we need to evaluate the condition and increment the counter on TRUE:
1878 //
1879 // if (Cond)
1880 // goto CounterIncrBlock;
1881 // else
1882 // goto FalseBlock;
1883 //
1884 // CounterIncrBlock:
1885 // Counter++;
1886 // goto TrueBlock;
1887
1888 if (LOp == BO_LAnd) {
1889 SkipNextBlock = FalseBlock;
1890 ThenBlock = CounterIncrBlock;
1891 ElseBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1892 NextBlock = TrueBlock;
1893 }
1894
1895 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1896 // we need to evaluate the condition and increment the counter on FALSE:
1897 //
1898 // if (Cond)
1899 // goto TrueBlock;
1900 // else
1901 // goto CounterIncrBlock;
1902 //
1903 // CounterIncrBlock:
1904 // Counter++;
1905 // goto FalseBlock;
1906
1907 else if (LOp == BO_LOr) {
1908 SkipNextBlock = TrueBlock;
1909 ThenBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1910 ElseBlock = CounterIncrBlock;
1911 NextBlock = FalseBlock;
1912 } else {
1913 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1914 }
1915
1916 // Emit Branch based on condition.
1917 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1918
1919 if (SkipIncrBlock) {
1920 EmitBlock(SkipIncrBlock);
1922 EmitBranch(SkipNextBlock);
1923 }
1924
1925 // Emit the block containing the counter increment(s).
1926 EmitBlock(CounterIncrBlock);
1927
1928 // Increment corresponding counter; if index not provided, use Cond as index.
1930
1931 // Go to the next block.
1932 EmitBranch(NextBlock);
1933}
1934
1935/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1936/// statement) to the specified blocks. Based on the condition, this might try
1937/// to simplify the codegen of the conditional based on the branch.
1938/// \param LH The value of the likelihood attribute on the True branch.
1939/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1940/// ConditionalOperator (ternary) through a recursive call for the operator's
1941/// LHS and RHS nodes.
1943 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1944 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp,
1945 const VarDecl *ConditionalDecl) {
1946 Cond = Cond->IgnoreParens();
1947
1948 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1949 bool HasSkip = hasSkipCounter(CondBOp);
1950
1951 // Handle X && Y in a condition.
1952 if (CondBOp->getOpcode() == BO_LAnd) {
1953 // If we have "1 && X", simplify the code. "0 && X" would have constant
1954 // folded if the case was simple enough.
1955 bool ConstantBool = false;
1956 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1957 ConstantBool) {
1958 // br(1 && X) -> br(X).
1959 incrementProfileCounter(CondBOp);
1960 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1961 FalseBlock, TrueCount, LH);
1962 return;
1963 }
1964
1965 // If we have "X && 1", simplify the code to use an uncond branch.
1966 // "X && 0" would have been constant folded to 0.
1967 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1968 ConstantBool) {
1969 // br(X && 1) -> br(X).
1970 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1971 FalseBlock, TrueCount, LH, CondBOp);
1972 return;
1973 }
1974
1975 // Emit the LHS as a conditional. If the LHS conditional is false, we
1976 // want to jump to the FalseBlock.
1977 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1978 llvm::BasicBlock *LHSFalse =
1979 (HasSkip ? createBasicBlock("land.lhsskip") : FalseBlock);
1980 // The counter tells us how often we evaluate RHS, and all of TrueCount
1981 // can be propagated to that branch.
1982 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1983
1984 ConditionalEvaluation eval(*this);
1985 {
1986 ApplyDebugLocation DL(*this, Cond);
1987 // Propagate the likelihood attribute like __builtin_expect
1988 // __builtin_expect(X && Y, 1) -> X and Y are likely
1989 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1990 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, LHSFalse, RHSCount,
1991 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1992 if (HasSkip) {
1993 EmitBlock(LHSFalse);
1995 EmitBranch(FalseBlock);
1996 }
1997 EmitBlock(LHSTrue);
1998 }
1999
2001 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
2002
2003 // Any temporaries created here are conditional.
2004 eval.begin(*this);
2005 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
2006 FalseBlock, TrueCount, LH);
2007 eval.end(*this);
2008 return;
2009 }
2010
2011 if (CondBOp->getOpcode() == BO_LOr) {
2012 // If we have "0 || X", simplify the code. "1 || X" would have constant
2013 // folded if the case was simple enough.
2014 bool ConstantBool = false;
2015 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
2016 !ConstantBool) {
2017 // br(0 || X) -> br(X).
2018 incrementProfileCounter(CondBOp);
2019 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
2020 FalseBlock, TrueCount, LH);
2021 return;
2022 }
2023
2024 // If we have "X || 0", simplify the code to use an uncond branch.
2025 // "X || 1" would have been constant folded to 1.
2026 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
2027 !ConstantBool) {
2028 // br(X || 0) -> br(X).
2029 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
2030 FalseBlock, TrueCount, LH, CondBOp);
2031 return;
2032 }
2033 // Emit the LHS as a conditional. If the LHS conditional is true, we
2034 // want to jump to the TrueBlock.
2035 llvm::BasicBlock *LHSTrue =
2036 (HasSkip ? createBasicBlock("lor.lhsskip") : TrueBlock);
2037 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
2038 // We have the count for entry to the RHS and for the whole expression
2039 // being true, so we can divy up True count between the short circuit and
2040 // the RHS.
2041 uint64_t LHSCount =
2042 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
2043 uint64_t RHSCount = TrueCount - LHSCount;
2044
2045 ConditionalEvaluation eval(*this);
2046 {
2047 // Propagate the likelihood attribute like __builtin_expect
2048 // __builtin_expect(X || Y, 1) -> only Y is likely
2049 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
2050 ApplyDebugLocation DL(*this, Cond);
2051 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, LHSFalse, LHSCount,
2052 LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
2053 if (HasSkip) {
2054 EmitBlock(LHSTrue);
2056 EmitBranch(TrueBlock);
2057 }
2058 EmitBlock(LHSFalse);
2059 }
2060
2062 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
2063
2064 // Any temporaries created here are conditional.
2065 eval.begin(*this);
2066 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
2067 RHSCount, LH);
2068
2069 eval.end(*this);
2070 return;
2071 }
2072 }
2073
2074 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
2075 // br(!x, t, f) -> br(x, f, t)
2076 // Avoid doing this optimization when instrumenting a condition for MC/DC.
2077 // LNot is taken as part of the condition for simplicity, and changing its
2078 // sense negatively impacts test vector tracking.
2079 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
2080 CGM.getCodeGenOpts().MCDCCoverage &&
2082 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2083 // Negate the count.
2084 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
2085 // The values of the enum are chosen to make this negation possible.
2086 LH = static_cast<Stmt::Likelihood>(-LH);
2087 // Negate the condition and swap the destination blocks.
2088 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
2089 FalseCount, LH);
2090 }
2091 }
2092
2093 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
2094 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
2095 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
2096 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
2097
2098 // The ConditionalOperator itself has no likelihood information for its
2099 // true and false branches. This matches the behavior of __builtin_expect.
2100 ConditionalEvaluation cond(*this);
2101 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
2103
2104 // When computing PGO branch weights, we only know the overall count for
2105 // the true block. This code is essentially doing tail duplication of the
2106 // naive code-gen, introducing new edges for which counts are not
2107 // available. Divide the counts proportionally between the LHS and RHS of
2108 // the conditional operator.
2109 uint64_t LHSScaledTrueCount = 0;
2110 if (TrueCount) {
2111 double LHSRatio =
2112 getProfileCount(CondOp) / (double)getCurrentProfileCount();
2113 LHSScaledTrueCount = TrueCount * LHSRatio;
2114 }
2115
2116 cond.begin(*this);
2117 EmitBlock(LHSBlock);
2119 {
2120 ApplyDebugLocation DL(*this, Cond);
2121 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
2122 LHSScaledTrueCount, LH, CondOp);
2123 }
2124 cond.end(*this);
2125
2126 cond.begin(*this);
2127 EmitBlock(RHSBlock);
2129 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
2130 TrueCount - LHSScaledTrueCount, LH, CondOp);
2131 cond.end(*this);
2132
2133 return;
2134 }
2135
2136 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2137 // Conditional operator handling can give us a throw expression as a
2138 // condition for a case like:
2139 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2140 // Fold this to:
2141 // br(c, throw x, br(y, t, f))
2142 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
2143 return;
2144 }
2145
2146 // Emit the code with the fully general case.
2147 llvm::Value *CondV;
2148 {
2149 ApplyDebugLocation DL(*this, Cond);
2150 CondV = EvaluateExprAsBool(Cond);
2151 }
2152
2153 MaybeEmitDeferredVarDeclInit(ConditionalDecl);
2154
2155 // If not at the top of the logical operator nest, update MCDC temp with the
2156 // boolean result of the evaluated condition.
2157 {
2158 const Expr *MCDCBaseExpr = Cond;
2159 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2160 // expression, MC/DC tracks the result of the ternary, and this is tied to
2161 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2162 // this is the case, the ConditionalOperator expression is passed through
2163 // the ConditionalOp parameter and then used as the MCDC base expression.
2164 if (ConditionalOp)
2165 MCDCBaseExpr = ConditionalOp;
2166
2167 if (isMCDCBranchExpr(stripCond(MCDCBaseExpr)) &&
2169 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2170 }
2171
2172 llvm::MDNode *Weights = nullptr;
2173 llvm::MDNode *Unpredictable = nullptr;
2174
2175 // If the branch has a condition wrapped by __builtin_unpredictable,
2176 // create metadata that specifies that the branch is unpredictable.
2177 // Don't bother if not optimizing because that metadata would not be used.
2178 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2179 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2180 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2181 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2182 llvm::MDBuilder MDHelper(getLLVMContext());
2183 Unpredictable = MDHelper.createUnpredictable();
2184 }
2185 }
2186
2187 // If there is a Likelihood knowledge for the cond, lower it.
2188 // Note that if not optimizing this won't emit anything.
2189 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2190 if (CondV != NewCondV)
2191 CondV = NewCondV;
2192 else {
2193 // Otherwise, lower profile counts. Note that we do this even at -O0.
2194 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2195 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2196 }
2197
2198 llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, FalseBlock,
2199 Weights, Unpredictable);
2200 addInstToNewSourceAtom(BrInst, CondV);
2201
2202 switch (HLSLControlFlowAttr) {
2203 case HLSLControlFlowHintAttr::Microsoft_branch:
2204 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2205 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2206
2207 llvm::ConstantInt *BranchHintConstant =
2209 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2210 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2211 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2212
2214 {MDHelper.createString("hlsl.controlflow.hint"),
2215 MDHelper.createConstant(BranchHintConstant)});
2216 BrInst->setMetadata("hlsl.controlflow.hint",
2217 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2218 break;
2219 }
2220 // This is required to avoid warnings during compilation
2221 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2222 break;
2223 }
2224}
2225
2226llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
2227 unsigned Idx,
2228 const CallExpr *E) {
2229 llvm::Value *Arg = nullptr;
2230 if ((ICEArguments & (1 << Idx)) == 0) {
2231 Arg = EmitScalarExpr(E->getArg(Idx));
2232 } else {
2233 // If this is required to be a constant, constant fold it so that we
2234 // know that the generated intrinsic gets a ConstantInt.
2235 std::optional<llvm::APSInt> Result =
2237 assert(Result && "Expected argument to be a constant");
2238 Arg = llvm::ConstantInt::get(getLLVMContext(), *Result);
2239 }
2240 return Arg;
2241}
2242
2243/// ErrorUnsupported - Print out an error that codegen doesn't support the
2244/// specified stmt yet.
2245void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2246 CGM.ErrorUnsupported(S, Type);
2247}
2248
2249/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2250/// variable-length array whose elements have a non-zero bit-pattern.
2251///
2252/// \param baseType the inner-most element type of the array
2253/// \param src - a char* pointing to the bit-pattern for a single
2254/// base element of the array
2255/// \param sizeInChars - the total size of the VLA, in chars
2257 Address dest, Address src,
2258 llvm::Value *sizeInChars) {
2259 CGBuilderTy &Builder = CGF.Builder;
2260
2261 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2262 llvm::Value *baseSizeInChars
2263 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2264
2265 Address begin = dest.withElementType(CGF.Int8Ty);
2266 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2267 begin.emitRawPointer(CGF),
2268 sizeInChars, "vla.end");
2269
2270 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2271 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2272 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2273
2274 // Make a loop over the VLA. C99 guarantees that the VLA element
2275 // count must be nonzero.
2276 CGF.EmitBlock(loopBB);
2277
2278 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2279 cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2280
2281 CharUnits curAlign =
2282 dest.getAlignment().alignmentOfArrayElement(baseSize);
2283
2284 // memcpy the individual element bit-pattern.
2285 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2286 /*volatile*/ false);
2287
2288 // Go to the next element.
2289 llvm::Value *next =
2290 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2291
2292 // Leave if that's the end of the VLA.
2293 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2294 Builder.CreateCondBr(done, contBB, loopBB);
2295 cur->addIncoming(next, loopBB);
2296
2297 CGF.EmitBlock(contBB);
2298}
2299
2301 const PFPField &Field) {
2302 return EmitAddressOfPFPField(
2303 RecordPtr,
2304 Builder.CreateConstInBoundsByteGEP(RecordPtr.withElementType(Int8Ty),
2305 Field.Offset),
2306 Field.Field);
2307}
2308
2310 Address PtrPtr,
2311 const FieldDecl *Field) {
2312 llvm::Value *Disc;
2313 if (CGM.getContext().arePFPFieldsTriviallyCopyable(Field->getParent())) {
2314 uint64_t FieldSignature =
2315 llvm::getPointerAuthStableSipHash(CGM.getPFPFieldName(Field));
2316 Disc = llvm::ConstantInt::get(CGM.Int64Ty, FieldSignature);
2317 } else
2318 Disc = Builder.CreatePtrToInt(RecordPtr.getBasePointer(), CGM.Int64Ty);
2319
2320 llvm::GlobalValue *DS = CGM.getPFPDeactivationSymbol(Field);
2321 llvm::OperandBundleDef DSBundle("deactivation-symbol", DS);
2322 llvm::Value *Args[] = {PtrPtr.getBasePointer(), Disc, Builder.getTrue()};
2323 return Address(
2324 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::protected_field_ptr,
2325 PtrPtr.getType()),
2326 Args, DSBundle),
2327 VoidPtrTy, PtrPtr.getAlignment());
2328}
2329
2330void
2332 // Ignore empty classes in C++.
2333 if (getLangOpts().CPlusPlus)
2334 if (const auto *RD = Ty->getAsCXXRecordDecl(); RD && RD->isEmpty())
2335 return;
2336
2337 if (DestPtr.getElementType() != Int8Ty)
2338 DestPtr = DestPtr.withElementType(Int8Ty);
2339
2340 // Get size and alignment info for this aggregate.
2342
2343 llvm::Value *SizeVal;
2344 const VariableArrayType *vla;
2345
2346 // Don't bother emitting a zero-byte memset.
2347 if (size.isZero()) {
2348 // But note that getTypeInfo returns 0 for a VLA.
2349 if (const VariableArrayType *vlaType =
2350 dyn_cast_or_null<VariableArrayType>(
2351 getContext().getAsArrayType(Ty))) {
2352 auto VlaSize = getVLASize(vlaType);
2353 SizeVal = VlaSize.NumElts;
2354 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2355 if (!eltSize.isOne())
2356 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2357 vla = vlaType;
2358 } else {
2359 return;
2360 }
2361 } else {
2362 SizeVal = CGM.getSize(size);
2363 vla = nullptr;
2364 }
2365
2366 // If the type contains a pointer to data member we can't memset it to zero.
2367 // Instead, create a null constant and copy it to the destination.
2368 // TODO: there are other patterns besides zero that we can usefully memset,
2369 // like -1, which happens to be the pattern used by member-pointers.
2370 if (!CGM.getTypes().isZeroInitializable(Ty)) {
2371 // For a VLA, emit a single element, then splat that over the VLA.
2372 if (vla) Ty = getContext().getBaseElementType(vla);
2373
2374 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2375
2376 llvm::GlobalVariable *NullVariable =
2377 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2378 /*isConstant=*/true,
2379 llvm::GlobalVariable::PrivateLinkage,
2380 NullConstant, Twine());
2381 CharUnits NullAlign = DestPtr.getAlignment();
2382 NullVariable->setAlignment(NullAlign.getAsAlign());
2383 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2384
2385 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2386
2387 // Get and call the appropriate llvm.memcpy overload.
2388 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2389 } else {
2390 // Otherwise, just memset the whole thing to zero. This is legal
2391 // because in LLVM, all default initializers (other than the ones we just
2392 // handled above, and the case handled below) are guaranteed to have a bit
2393 // pattern of all zeros.
2394 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2395 }
2396
2397 // With the pointer field protection feature, null pointers do not have a bit
2398 // pattern of zero in memory, so we must initialize them separately.
2399 for (auto &Field : getContext().findPFPFields(Ty)) {
2400 auto addr = EmitAddressOfPFPField(DestPtr, Field);
2401 Builder.CreateStore(llvm::ConstantPointerNull::get(VoidPtrTy), addr);
2402 }
2403}
2404
2405llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2406 // Make sure that there is a block for the indirect goto.
2407 if (!IndirectBranch)
2409
2410 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2411
2412 // Make sure the indirect branch includes all of the address-taken blocks.
2413 IndirectBranch->addDestination(BB);
2414 return llvm::BlockAddress::get(CurFn->getType(), BB);
2415}
2416
2418 // If we already made the indirect branch for indirect goto, return its block.
2419 if (IndirectBranch) return IndirectBranch->getParent();
2420
2421 CGBuilderTy TmpBuilder(CGM, createBasicBlock("indirectgoto"));
2422
2423 // Create the PHI node that indirect gotos will add entries to.
2424 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2425 "indirect.goto.dest");
2426
2427 // Create the indirect branch instruction.
2428 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2429 return IndirectBranch->getParent();
2430}
2431
2432/// Computes the length of an array in elements, as well as the base
2433/// element type and a properly-typed first element pointer.
2434llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2435 QualType &baseType,
2436 Address &addr) {
2437 const ArrayType *arrayType = origArrayType;
2438
2439 // If it's a VLA, we have to load the stored size. Note that
2440 // this is the size of the VLA in bytes, not its size in elements.
2441 llvm::Value *numVLAElements = nullptr;
2444
2445 // Walk into all VLAs. This doesn't require changes to addr,
2446 // which has type T* where T is the first non-VLA element type.
2447 do {
2448 QualType elementType = arrayType->getElementType();
2449 arrayType = getContext().getAsArrayType(elementType);
2450
2451 // If we only have VLA components, 'addr' requires no adjustment.
2452 if (!arrayType) {
2453 baseType = elementType;
2454 return numVLAElements;
2455 }
2457
2458 // We get out here only if we find a constant array type
2459 // inside the VLA.
2460 }
2461
2462 // We have some number of constant-length arrays, so addr should
2463 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2464 // down to the first element of addr.
2466
2467 // GEP down to the array type.
2468 llvm::ConstantInt *zero = Builder.getInt32(0);
2469 gepIndices.push_back(zero);
2470
2471 uint64_t countFromCLAs = 1;
2472 QualType eltType;
2473
2474 llvm::ArrayType *llvmArrayType =
2475 dyn_cast<llvm::ArrayType>(addr.getElementType());
2476 while (llvmArrayType) {
2478 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2479 llvmArrayType->getNumElements());
2480
2481 gepIndices.push_back(zero);
2482 countFromCLAs *= llvmArrayType->getNumElements();
2483 eltType = arrayType->getElementType();
2484
2485 llvmArrayType =
2486 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2487 arrayType = getContext().getAsArrayType(arrayType->getElementType());
2488 assert((!llvmArrayType || arrayType) &&
2489 "LLVM and Clang types are out-of-synch");
2490 }
2491
2492 if (arrayType) {
2493 // From this point onwards, the Clang array type has been emitted
2494 // as some other type (probably a packed struct). Compute the array
2495 // size, and just emit the 'begin' expression as a bitcast.
2496 while (arrayType) {
2497 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2498 eltType = arrayType->getElementType();
2499 arrayType = getContext().getAsArrayType(eltType);
2500 }
2501
2502 llvm::Type *baseType = ConvertType(eltType);
2503 addr = addr.withElementType(baseType);
2504 } else {
2505 // Create the actual GEP.
2506 addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
2507 addr.emitRawPointer(*this),
2508 gepIndices, "array.begin"),
2509 ConvertTypeForMem(eltType), addr.getAlignment());
2510 }
2511
2512 baseType = eltType;
2513
2514 llvm::Value *numElements
2515 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2516
2517 // If we had any VLA dimensions, factor them in.
2518 if (numVLAElements)
2519 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2520
2521 return numElements;
2522}
2523
2526 assert(vla && "type was not a variable array type!");
2527 return getVLASize(vla);
2528}
2529
2532 // The number of elements so far; always size_t.
2533 llvm::Value *numElements = nullptr;
2534
2535 QualType elementType;
2536 do {
2537 elementType = type->getElementType();
2538 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2539 assert(vlaSize && "no size for VLA!");
2540 assert(vlaSize->getType() == SizeTy);
2541
2542 if (!numElements) {
2543 numElements = vlaSize;
2544 } else {
2545 // It's undefined behavior if this wraps around, so mark it that way.
2546 // FIXME: Teach -fsanitize=undefined to trap this.
2547 numElements = Builder.CreateNUWMul(numElements, vlaSize);
2548 }
2549 } while ((type = getContext().getAsVariableArrayType(elementType)));
2550
2551 return { numElements, elementType };
2552}
2553
2557 assert(vla && "type was not a variable array type!");
2558 return getVLAElements1D(vla);
2559}
2560
2563 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2564 assert(VlaSize && "no size for VLA!");
2565 assert(VlaSize->getType() == SizeTy);
2566 return { VlaSize, Vla->getElementType() };
2567}
2568
2570 assert(type->isVariablyModifiedType() &&
2571 "Must pass variably modified type to EmitVLASizes!");
2572
2574
2575 // We're going to walk down into the type and look for VLA
2576 // expressions.
2577 do {
2578 assert(type->isVariablyModifiedType());
2579
2580 const Type *ty = type.getTypePtr();
2581 switch (ty->getTypeClass()) {
2582
2583#define TYPE(Class, Base)
2584#define ABSTRACT_TYPE(Class, Base)
2585#define NON_CANONICAL_TYPE(Class, Base)
2586#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2587#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2588#include "clang/AST/TypeNodes.inc"
2589 llvm_unreachable("unexpected dependent type!");
2590
2591 // These types are never variably-modified.
2592 case Type::Builtin:
2593 case Type::Complex:
2594 case Type::Vector:
2595 case Type::ExtVector:
2596 case Type::ConstantMatrix:
2597 case Type::CooperativeMatrix:
2598 case Type::Record:
2599 case Type::Enum:
2600 case Type::Using:
2601 case Type::TemplateSpecialization:
2602 case Type::ObjCTypeParam:
2603 case Type::ObjCObject:
2604 case Type::ObjCInterface:
2605 case Type::ObjCObjectPointer:
2606 case Type::BitInt:
2607 case Type::HLSLInlineSpirv:
2608 case Type::PredefinedSugar:
2609 llvm_unreachable("type class is never variably-modified!");
2610
2611 case Type::Adjusted:
2612 type = cast<AdjustedType>(ty)->getAdjustedType();
2613 break;
2614
2615 case Type::Decayed:
2616 type = cast<DecayedType>(ty)->getPointeeType();
2617 break;
2618
2619 case Type::Pointer:
2620 type = cast<PointerType>(ty)->getPointeeType();
2621 break;
2622
2623 case Type::BlockPointer:
2624 type = cast<BlockPointerType>(ty)->getPointeeType();
2625 break;
2626
2627 case Type::LValueReference:
2628 case Type::RValueReference:
2629 type = cast<ReferenceType>(ty)->getPointeeType();
2630 break;
2631
2632 case Type::MemberPointer:
2633 type = cast<MemberPointerType>(ty)->getPointeeType();
2634 break;
2635
2636 case Type::ArrayParameter:
2637 case Type::ConstantArray:
2638 case Type::IncompleteArray:
2639 // Losing element qualification here is fine.
2640 type = cast<ArrayType>(ty)->getElementType();
2641 break;
2642
2643 case Type::VariableArray: {
2644 // Losing element qualification here is fine.
2646
2647 // Unknown size indication requires no size computation.
2648 // Otherwise, evaluate and record it.
2649 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2650 // It's possible that we might have emitted this already,
2651 // e.g. with a typedef and a pointer to it.
2652 llvm::Value *&entry = VLASizeMap[sizeExpr];
2653 if (!entry) {
2654 llvm::Value *size = EmitScalarExpr(sizeExpr);
2655
2656 // C11 6.7.6.2p5:
2657 // If the size is an expression that is not an integer constant
2658 // expression [...] each time it is evaluated it shall have a value
2659 // greater than zero.
2660 if (SanOpts.has(SanitizerKind::VLABound)) {
2661 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2662 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2663 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2664 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2665 clang::QualType SEType = sizeExpr->getType();
2666 llvm::Value *CheckCondition =
2667 SEType->isSignedIntegerType()
2668 ? Builder.CreateICmpSGT(size, Zero)
2669 : Builder.CreateICmpUGT(size, Zero);
2670 llvm::Constant *StaticArgs[] = {
2671 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2672 EmitCheckTypeDescriptor(SEType)};
2673 EmitCheck(std::make_pair(CheckCondition, CheckOrdinal),
2674 CheckHandler, StaticArgs, size);
2675 }
2676
2677 // Always zexting here would be wrong if it weren't
2678 // undefined behavior to have a negative bound.
2679 // FIXME: What about when size's type is larger than size_t?
2680 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2681 }
2682 }
2683 type = vat->getElementType();
2684 break;
2685 }
2686
2687 case Type::FunctionProto:
2688 case Type::FunctionNoProto:
2689 type = cast<FunctionType>(ty)->getReturnType();
2690 break;
2691
2692 case Type::Paren:
2693 case Type::TypeOf:
2694 case Type::UnaryTransform:
2695 case Type::Attributed:
2696 case Type::BTFTagAttributed:
2697 case Type::OverflowBehavior:
2698 case Type::HLSLAttributedResource:
2699 case Type::SubstTemplateTypeParm:
2700 case Type::MacroQualified:
2701 case Type::CountAttributed:
2702 case Type::LateParsedAttr:
2703 // Keep walking after single level desugaring.
2704 type = type.getSingleStepDesugaredType(getContext());
2705 break;
2706
2707 case Type::Typedef:
2708 case Type::Decltype:
2709 case Type::Auto:
2710 case Type::DeducedTemplateSpecialization:
2711 case Type::PackIndexing:
2712 // Stop walking: nothing to do.
2713 return;
2714
2715 case Type::TypeOfExpr:
2716 // Stop walking: emit typeof expression.
2717 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2718 return;
2719
2720 case Type::Atomic:
2721 type = cast<AtomicType>(ty)->getValueType();
2722 break;
2723
2724 case Type::Pipe:
2725 type = cast<PipeType>(ty)->getElementType();
2726 break;
2727 }
2728 } while (type->isVariablyModifiedType());
2729}
2730
2732 if (getContext().getBuiltinVaListType()->isArrayType())
2733 return EmitPointerWithAlignment(E);
2734 return EmitLValue(E).getAddress();
2735}
2736
2740
2744
2746 const APValue &Init) {
2747 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2748 if (CGDebugInfo *Dbg = getDebugInfo())
2749 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2750 Dbg->EmitGlobalVariable(E->getDecl(), Init);
2751}
2752
2755 // At the moment, the only aggressive peephole we do in IR gen
2756 // is trunc(zext) folding, but if we add more, we can easily
2757 // extend this protection.
2758
2759 if (!rvalue.isScalar()) return PeepholeProtection();
2760 llvm::Value *value = rvalue.getScalarVal();
2761 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2762
2763 // Just make an extra bitcast.
2764 assert(HaveInsertPoint());
2765 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2766 Builder.GetInsertBlock());
2767
2768 PeepholeProtection protection;
2769 protection.Inst = inst;
2770 return protection;
2771}
2772
2774 if (!protection.Inst) return;
2775
2776 // In theory, we could try to duplicate the peepholes now, but whatever.
2777 protection.Inst->eraseFromParent();
2778}
2779
2781 QualType Ty, SourceLocation Loc,
2782 SourceLocation AssumptionLoc,
2783 llvm::Value *Alignment,
2784 llvm::Value *OffsetValue) {
2785 if (Alignment->getType() != IntPtrTy)
2786 Alignment =
2787 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2788 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2789 OffsetValue =
2790 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2791 if (SanOpts.has(SanitizerKind::Alignment))
2792 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2793 OffsetValue);
2794 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2795 OffsetValue);
2796}
2797
2799 const Expr *E,
2800 SourceLocation AssumptionLoc,
2801 llvm::Value *Alignment,
2802 llvm::Value *OffsetValue) {
2803 QualType Ty = E->getType();
2804 SourceLocation Loc = E->getExprLoc();
2805
2806 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2807 OffsetValue);
2808}
2809
2810llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2811 llvm::Value *AnnotatedVal,
2812 StringRef AnnotationStr,
2813 SourceLocation Location,
2814 const AnnotateAttr *Attr) {
2816 AnnotatedVal,
2817 CGM.EmitAnnotationString(AnnotationStr),
2818 CGM.EmitAnnotationUnit(Location),
2819 CGM.EmitAnnotationLineNo(Location),
2820 };
2821 if (Attr)
2822 Args.push_back(CGM.EmitAnnotationArgs(Attr));
2823 return Builder.CreateCall(AnnotationFn, Args);
2824}
2825
2826void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2827 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2828 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2829 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2830 {V->getType(), CGM.ConstGlobalsPtrTy}),
2831 V, I->getAnnotation(), D->getLocation(), I);
2832}
2833
2835 Address Addr) {
2836 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2837 llvm::Value *V = Addr.emitRawPointer(*this);
2838 llvm::Type *VTy = V->getType();
2839 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2840 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2841 llvm::PointerType *IntrinTy =
2842 llvm::PointerType::get(CGM.getLLVMContext(), AS);
2843 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2844 {IntrinTy, CGM.ConstGlobalsPtrTy});
2845
2846 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2847 // FIXME Always emit the cast inst so we can differentiate between
2848 // annotation on the first field of a struct and annotation on the struct
2849 // itself.
2850 if (VTy != IntrinTy)
2851 V = Builder.CreateBitCast(V, IntrinTy);
2852 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2853 V = Builder.CreateBitCast(V, VTy);
2854 }
2855
2856 return Address(V, Addr.getElementType(), Addr.getAlignment());
2857}
2858
2860
2862 : CGF(CGF) {
2863 assert(!CGF->IsSanitizerScope);
2864 CGF->IsSanitizerScope = true;
2865}
2866
2868 CGF->IsSanitizerScope = false;
2869}
2870
2871void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2872 const llvm::Twine &Name,
2873 llvm::BasicBlock::iterator InsertPt) const {
2874 LoopStack.InsertHelper(I);
2875 if (IsSanitizerScope)
2876 I->setNoSanitizeMetadata();
2877}
2878
2880 llvm::Instruction *I, const llvm::Twine &Name,
2881 llvm::BasicBlock::iterator InsertPt) const {
2882 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2883 if (CGF)
2884 CGF->InsertHelper(I, Name, InsertPt);
2885}
2886
2887// Emits an error if we don't have a valid set of target features for the
2888// called function.
2890 const FunctionDecl *TargetDecl) {
2891 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2892 CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
2893 getLangOpts(), E, FD, TargetDecl);
2894}
2895
2896// Emits an error if we don't have a valid set of target features for the
2897// called function.
2899 const FunctionDecl *TargetDecl) {
2900 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2901 CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
2902 getLangOpts(), Loc, FD, TargetDecl);
2903}
2904
2905void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2906 if (!CGM.getCodeGenOpts().SanitizeStats)
2907 return;
2908
2909 llvm::IRBuilder<> IRB(Builder.GetInsertPoint());
2910 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2911 CGM.getSanStats().create(IRB, SSK);
2912}
2913
2915 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2916 const CGCalleeInfo &CI = Callee.getAbstractInfo();
2918 if (!FP)
2919 return;
2920
2921 StringRef Salt;
2922 if (const auto &Info = FP->getExtraAttributeInfo())
2923 Salt = Info.CFISalt;
2924
2925 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar(), Salt));
2926}
2927
2928llvm::Value *
2929CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2930 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(RO.Features);
2931}
2932
2933llvm::Value *
2934CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2935 llvm::Value *Condition = nullptr;
2936
2937 if (RO.Architecture) {
2938 StringRef Arch = *RO.Architecture;
2939 // If arch= specifies an x86-64 micro-architecture level, test the feature
2940 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2941 if (Arch.starts_with("x86-64"))
2942 Condition = EmitX86CpuSupports({Arch});
2943 else
2944 Condition = EmitX86CpuIs(Arch);
2945 }
2946
2947 if (!RO.Features.empty()) {
2948 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2949 Condition =
2950 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2951 }
2952 return Condition;
2953}
2954
2956 llvm::Function *Resolver,
2957 CGBuilderTy &Builder,
2958 llvm::Function *FuncToReturn,
2959 bool SupportsIFunc) {
2960 if (SupportsIFunc) {
2961 Builder.CreateRet(FuncToReturn);
2962 return;
2963 }
2964
2966 llvm::make_pointer_range(Resolver->args()));
2967
2968 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2969 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2970
2971 if (Resolver->getReturnType()->isVoidTy())
2972 Builder.CreateRetVoid();
2973 else
2974 Builder.CreateRet(Result);
2975}
2976
2978 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2979 llvm::SaveAndRestore<llvm::Function *> savedCurFn(CurFn, Resolver);
2980 llvm::Triple::ArchType ArchType =
2981 getContext().getTargetInfo().getTriple().getArch();
2982
2983 switch (ArchType) {
2984 case llvm::Triple::x86:
2985 case llvm::Triple::x86_64:
2986 EmitX86MultiVersionResolver(Resolver, Options);
2987 return;
2988 case llvm::Triple::aarch64:
2989 EmitAArch64MultiVersionResolver(Resolver, Options);
2990 return;
2991 case llvm::Triple::riscv32:
2992 case llvm::Triple::riscv64:
2993 case llvm::Triple::riscv32be:
2994 case llvm::Triple::riscv64be:
2995 EmitRISCVMultiVersionResolver(Resolver, Options);
2996 return;
2997 case llvm::Triple::ppc:
2998 case llvm::Triple::ppc64:
2999 if (getContext().getTargetInfo().getTriple().isOSAIX()) {
3000 EmitPPCAIXMultiVersionResolver(Resolver, Options);
3001 return;
3002 }
3003 [[fallthrough]];
3004 default:
3005 assert(false &&
3006 "Only implemented for x86, AArch64, RISC-V, and PowerPC AIX");
3007 }
3008}
3009
3010/**
3011 * define internal ptr @foo.resolver() {
3012 * entry:
3013 * %is_version_1 = __builtin_cpu_supports(version_1)
3014 * br i1 %1, label %if.version_1, label %if.else_2
3015 *
3016 * if.version_1:
3017 * ret ptr @foo.version_1
3018 *
3019 * if.else_2:
3020 * %is_version_2 = __builtin_cpu_supports(version_2)
3021 * ...
3022 * if.else: ; preds = %entry
3023 * ret ptr @foo.default
3024 * }
3025 */
3027 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3028
3029 // entry:
3030 llvm::BasicBlock *CurBlock = createBasicBlock("entry", Resolver);
3031
3032 for (const FMVResolverOption &RO : Options) {
3033 Builder.SetInsertPoint(CurBlock);
3034 // The 'default' or 'generic' case.
3035 if (!RO.Architecture && RO.Features.empty()) {
3036 // if.else:
3037 // ret ptr @foo.default
3038 assert(&RO == Options.end() - 1 &&
3039 "Default or Generic case must be last");
3040 Builder.CreateRet(RO.Function);
3041 return;
3042 }
3043 // if.else_n:
3044 // %is_version_n = __builtin_cpu_supports(version_n)
3045 // br i1 %is_version_n, label %if.version_n, label %if.else_n+1
3046 //
3047 // if.version_n:
3048 // ret ptr @foo_version_n
3049 assert(RO.Features.size() == 1 &&
3050 "for now one feature requirement per version");
3051
3052 StringRef FeatureStr = RO.Features[0];
3053 StringRef BuiltinCpuSupportsArg;
3054 bool IsNegated = false;
3055
3056 if (FeatureStr.starts_with("cpu=")) {
3057 // CPU specification - map to ISA level
3058 StringRef CPU = FeatureStr.split("=").second.trim();
3059 BuiltinCpuSupportsArg = llvm::StringSwitch<StringRef>(CPU)
3060#define PPC_AIX_CLONES_CPU(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _) \
3061 .Case(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3062#include "llvm/TargetParser/PPCTargetParser.def"
3063 .Default("error");
3064 } else {
3065 // Feature strings arrive here already normalized:
3066 // - Positive features: just the name (e.g., "altivec")
3067 // - Negated features: "no-" prefix (e.g., "no-altivec")
3068 if (FeatureStr.starts_with("no-")) {
3069 IsNegated = true;
3070 FeatureStr = FeatureStr.drop_front(3);
3071 }
3072
3073 // Map feature names to __builtin_cpu_supports() strings
3074 BuiltinCpuSupportsArg =
3075 llvm::StringSwitch<StringRef>(FeatureStr)
3076#define PPC_AIX_CLONES_FEATURE(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _, \
3077 __) \
3078 .Case(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3079#include "llvm/TargetParser/PPCTargetParser.def"
3080 // Features without runtime checks return empty string
3081 .Default("");
3082
3083 // All features in target_clones must have runtime detection
3084 assert(!BuiltinCpuSupportsArg.empty() &&
3085 "Feature without runtime detection should have been rejected in "
3086 "Sema");
3087 }
3088
3089 assert(getContext().getTargetInfo().validateCpuSupports(
3090 BuiltinCpuSupportsArg));
3091
3092 llvm::Value *Condition =
3093 EmitPPCBuiltinCpu(Builtin::BI__builtin_cpu_supports,
3094 Builder.getInt1Ty(), BuiltinCpuSupportsArg);
3095
3096 // Negate the condition if this is a negated feature
3097 if (IsNegated) {
3098 Condition = Builder.CreateNot(Condition, "neg");
3099 }
3100
3101 llvm::BasicBlock *ThenBlock = createBasicBlock("if.version", Resolver);
3102 CurBlock = createBasicBlock("if.else", Resolver);
3103 Builder.CreateCondBr(Condition, ThenBlock, CurBlock);
3104
3105 Builder.SetInsertPoint(ThenBlock);
3106 Builder.CreateRet(RO.Function);
3107 }
3108
3109 llvm_unreachable("Default case missing");
3110}
3111
3113 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3114
3115 if (getContext().getTargetInfo().getTriple().getOS() !=
3116 llvm::Triple::OSType::Linux) {
3117 CGM.getDiags().Report(diag::err_os_unsupport_riscv_fmv);
3118 return;
3119 }
3120
3121 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3122 Builder.SetInsertPoint(CurBlock);
3124
3125 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3126 bool HasDefault = false;
3127 unsigned DefaultIndex = 0;
3128
3129 // Check the each candidate function.
3130 for (unsigned Index = 0; Index < Options.size(); Index++) {
3131
3132 if (Options[Index].Features.empty()) {
3133 HasDefault = true;
3134 DefaultIndex = Index;
3135 continue;
3136 }
3137
3138 Builder.SetInsertPoint(CurBlock);
3139
3140 // FeaturesCondition: The bitmask of the required extension has been
3141 // enabled by the runtime object.
3142 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
3143 // REQUIRED_BITMASK
3144 //
3145 // When condition is met, return this version of the function.
3146 // Otherwise, try the next version.
3147 //
3148 // if (FeaturesConditionVersion1)
3149 // return Version1;
3150 // else if (FeaturesConditionVersion2)
3151 // return Version2;
3152 // else if (FeaturesConditionVersion3)
3153 // return Version3;
3154 // ...
3155 // else
3156 // return DefaultVersion;
3157
3158 // TODO: Add a condition to check the length before accessing elements.
3159 // Without checking the length first, we may access an incorrect memory
3160 // address when using different versions.
3161 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
3162 llvm::SmallVector<std::string, 8> TargetAttrFeats;
3163
3164 for (StringRef Feat : Options[Index].Features) {
3165 std::vector<std::string> FeatStr =
3167
3168 assert(FeatStr.size() == 1 && "Feature string not delimited");
3169
3170 std::string &CurrFeat = FeatStr.front();
3171 if (CurrFeat[0] == '+')
3172 TargetAttrFeats.push_back(CurrFeat.substr(1));
3173 }
3174
3175 if (TargetAttrFeats.empty())
3176 continue;
3177
3178 for (std::string &Feat : TargetAttrFeats)
3179 CurrTargetAttrFeats.push_back(Feat);
3180
3181 Builder.SetInsertPoint(CurBlock);
3182 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(CurrTargetAttrFeats);
3183
3184 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3185 CGBuilderTy RetBuilder(CGM, RetBlock);
3186 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder,
3187 Options[Index].Function, SupportsIFunc);
3188 llvm::BasicBlock *ElseBlock = createBasicBlock("resolver_else", Resolver);
3189
3190 Builder.SetInsertPoint(CurBlock);
3191 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
3192
3193 CurBlock = ElseBlock;
3194 }
3195
3196 // Finally, emit the default one.
3197 if (HasDefault) {
3198 Builder.SetInsertPoint(CurBlock);
3200 CGM, Resolver, Builder, Options[DefaultIndex].Function, SupportsIFunc);
3201 return;
3202 }
3203
3204 // If no generic/default, emit an unreachable.
3205 Builder.SetInsertPoint(CurBlock);
3207}
3208
3210 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3211 assert(!Options.empty() && "No multiversion resolver options found");
3212 assert(Options.back().Features.size() == 0 && "Default case must be last");
3213 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3214 assert(SupportsIFunc &&
3215 "Multiversion resolver requires target IFUNC support");
3216 bool AArch64CpuInitialized = false;
3217 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3218
3219 for (const FMVResolverOption &RO : Options) {
3220 // Skip unreachable versions.
3221 if (RO.Function == nullptr)
3222 continue;
3223
3224 Builder.SetInsertPoint(CurBlock);
3225 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3226
3227 // The 'default' or 'all features enabled' case.
3228 if (!Condition) {
3229 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3230 SupportsIFunc);
3231 return;
3232 }
3233
3234 if (!AArch64CpuInitialized) {
3235 Builder.SetInsertPoint(CurBlock->begin());
3236 EmitAArch64CpuInit();
3237 AArch64CpuInitialized = true;
3238 Builder.SetInsertPoint(CurBlock);
3239 }
3240
3241 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3242 CGBuilderTy RetBuilder(CGM, RetBlock);
3243 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3244 SupportsIFunc);
3245 CurBlock = createBasicBlock("resolver_else", Resolver);
3246 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3247 }
3248
3249 // If no default, emit an unreachable.
3250 Builder.SetInsertPoint(CurBlock);
3252}
3253
3255 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3256
3257 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3258
3259 // Main function's basic block.
3260 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3261 Builder.SetInsertPoint(CurBlock);
3262 EmitX86CpuInit();
3263
3264 for (const FMVResolverOption &RO : Options) {
3265 Builder.SetInsertPoint(CurBlock);
3266 llvm::Value *Condition = FormX86ResolverCondition(RO);
3267
3268 // The 'default' or 'generic' case.
3269 if (!Condition) {
3270 assert(&RO == Options.end() - 1 &&
3271 "Default or Generic case must be last");
3272 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3273 SupportsIFunc);
3274 return;
3275 }
3276
3277 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3278 CGBuilderTy RetBuilder(CGM, RetBlock);
3279 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3280 SupportsIFunc);
3281 CurBlock = createBasicBlock("resolver_else", Resolver);
3282 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3283 }
3284
3285 // If no generic/default, emit an unreachable.
3286 Builder.SetInsertPoint(CurBlock);
3288}
3289
3290// Loc / DynamicLoc - where the diagnostic will point, where in the source code
3291// this alignment has failed.
3292// AssumptionLoc - if present (will be present if sufficiently different from
3293// Loc), the diagnostic will additionally point a "Note:" to this location.
3294// It should be the location where the __attribute__((assume_aligned))
3295// was written e.g.
3296static void emitAlignmentAssumptionCheck(CodeGenFunction &CGF, llvm::Value *Ptr,
3297 QualType Ty, SourceLocation Loc,
3298 llvm::Value *DynamicLoc,
3299 SourceLocation AssumptionLoc,
3300 llvm::Value *Alignment,
3301 llvm::Value *OffsetValue) {
3302 if (!CGF.SanOpts.has(SanitizerKind::Alignment))
3303 return;
3304
3305 CGBuilderTy &Builder = CGF.Builder;
3306 llvm::IntegerType *IntPtrTy = CGF.IntPtrTy;
3307 if (Alignment->getType() != IntPtrTy)
3308 Alignment =
3309 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
3310 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
3311 OffsetValue =
3312 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
3313
3314 llvm::Value *PtrIntValue = Builder.CreatePtrToInt(Ptr, IntPtrTy, "ptrint");
3315
3316 if (OffsetValue) {
3317 bool IsOffsetZero = false;
3318 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
3319 IsOffsetZero = CI->isZero();
3320
3321 if (!IsOffsetZero)
3322 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
3323 }
3324
3325 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
3326 llvm::Value *Mask =
3327 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
3328 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
3329 llvm::Value *TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
3330
3331 // Don't check pointers to volatile data. The behavior here is implementation-
3332 // defined.
3334 return;
3335
3336 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3337 auto CheckHandler = !DynamicLoc ? SanitizerHandler::AlignmentAssumption
3338 : SanitizerHandler::ReturnAlignmentAssumption;
3339 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
3340
3341 if (!OffsetValue)
3342 OffsetValue = Builder.getInt1(false); // no offset.
3343
3344 if (!DynamicLoc) {
3345 llvm::Constant *StaticData[] = {CGF.EmitCheckSourceLocation(Loc),
3346 CGF.EmitCheckSourceLocation(AssumptionLoc),
3347 CGF.EmitCheckTypeDescriptor(Ty)};
3348 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3349 CGF.EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3350 StaticData, DynamicData);
3351 } else {
3352 llvm::Constant *StaticData[] = {CGF.EmitCheckSourceLocation(AssumptionLoc),
3353 CGF.EmitCheckTypeDescriptor(Ty)};
3354 llvm::Value *DynamicData[] = {DynamicLoc, Ptr, Alignment, OffsetValue};
3355 CGF.EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3356 StaticData, DynamicData);
3357 }
3358}
3359
3361 QualType Ty,
3362 SourceLocation Loc,
3363 SourceLocation AssumptionLoc,
3364 llvm::Value *Alignment,
3365 llvm::Value *OffsetValue) {
3366 ::emitAlignmentAssumptionCheck(*this, Ptr, Ty, Loc, nullptr, AssumptionLoc,
3367 Alignment, OffsetValue);
3368}
3369
3371 llvm::Value *Ptr, QualType Ty, SourceLocation AssumptionLoc,
3372 llvm::Value *Alignment, llvm::Value *OffsetValue) {
3373 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3374 ::emitAlignmentAssumptionCheck(*this, Ptr, Ty, SourceLocation(), SLocPtr,
3375 AssumptionLoc, Alignment, OffsetValue);
3376}
3377
3379 if (CGDebugInfo *DI = getDebugInfo())
3380 return DI->SourceLocToDebugLoc(Location);
3381
3382 return llvm::DebugLoc();
3383}
3384
3385llvm::Value *
3386CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3387 Stmt::Likelihood LH) {
3388 switch (LH) {
3389 case Stmt::LH_None:
3390 return Cond;
3391 case Stmt::LH_Likely:
3392 case Stmt::LH_Unlikely:
3393 // Don't generate llvm.expect on -O0 as the backend won't use it for
3394 // anything.
3395 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3396 return Cond;
3397 llvm::Type *CondTy = Cond->getType();
3398 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3399 llvm::Function *FnExpect =
3400 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3401 llvm::Value *ExpectedValueOfCond =
3402 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3403 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3404 Cond->getName() + ".expval");
3405 }
3406 llvm_unreachable("Unknown Likelihood");
3407}
3408
3409llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3410 unsigned NumElementsDst,
3411 const llvm::Twine &Name) {
3412 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3413 unsigned NumElementsSrc = SrcTy->getNumElements();
3414 if (NumElementsSrc == NumElementsDst)
3415 return SrcVec;
3416
3417 std::vector<int> ShuffleMask(NumElementsDst, -1);
3418 for (unsigned MaskIdx = 0;
3419 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3420 ShuffleMask[MaskIdx] = MaskIdx;
3421
3422 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3423}
3424
3426 const CGPointerAuthInfo &PointerAuth,
3428 if (!PointerAuth.isSigned())
3429 return;
3430
3431 auto *Key = Builder.getInt32(PointerAuth.getKey());
3432
3433 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3434 if (!Discriminator)
3435 Discriminator = Builder.getSize(0);
3436
3437 llvm::Value *Args[] = {Key, Discriminator};
3438 Bundles.emplace_back("ptrauth", Args);
3439}
3440
3442 const CGPointerAuthInfo &PointerAuth,
3443 llvm::Value *Pointer,
3444 unsigned IntrinsicID) {
3445 if (!PointerAuth)
3446 return Pointer;
3447
3448 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3449
3450 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3451 if (!Discriminator) {
3452 Discriminator = CGF.Builder.getSize(0);
3453 }
3454
3455 // Convert the pointer to intptr_t before signing it.
3456 auto OrigType = Pointer->getType();
3457 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3458
3459 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3460 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3461 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3462
3463 // Convert back to the original type.
3464 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3465 return Pointer;
3466}
3467
3468llvm::Value *
3470 llvm::Value *Pointer) {
3471 if (!PointerAuth.shouldSign())
3472 return Pointer;
3473 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3474 llvm::Intrinsic::ptrauth_sign);
3475}
3476
3477static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3478 const CGPointerAuthInfo &PointerAuth,
3479 llvm::Value *Pointer) {
3480 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3481
3482 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3483 // Convert the pointer to intptr_t before signing it.
3484 auto OrigType = Pointer->getType();
3486 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3487 return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3488}
3489
3490llvm::Value *
3492 llvm::Value *Pointer) {
3493 if (PointerAuth.shouldStrip()) {
3494 return EmitStrip(*this, PointerAuth, Pointer);
3495 }
3496 if (!PointerAuth.shouldAuth()) {
3497 return Pointer;
3498 }
3499
3500 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3501 llvm::Intrinsic::ptrauth_auth);
3502}
3503
3505 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3506 if (CGDebugInfo *DI = getDebugInfo())
3507 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3508}
3509
3511 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3512 if (CGDebugInfo *DI = getDebugInfo())
3513 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3514}
3515
3516void CodeGenFunction::addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
3517 llvm::Value *Backup) {
3518 if (CGDebugInfo *DI = getDebugInfo()) {
3520 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3521 }
3522}
3523
3525 QualType Ty) {
3526 for (auto &Field : getContext().findPFPFields(Ty)) {
3527 if (getContext().arePFPFieldsTriviallyCopyable(Field.Field->getParent()))
3528 continue;
3529 auto DestFieldPtr = EmitAddressOfPFPField(DestPtr, Field);
3530 auto SrcFieldPtr = EmitAddressOfPFPField(SrcPtr, Field);
3531 Builder.CreateStore(Builder.CreateLoad(SrcFieldPtr), DestFieldPtr);
3532 }
3533}
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.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
const llvm::StringMap< bool > & getFunctionFeatureMap(const FunctionDecl *FD) const
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:981
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
QualType getElementType() const
Definition TypeBase.h:3833
Attr - This represents one attribute.
Definition Attr.h:47
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
BinaryOperatorKind Opcode
Definition Expr.h:4112
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
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:2296
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2859
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2320
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1792
bool isCapturelessLambda() const
Definition DeclCXX.h:1074
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1213
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:184
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
This forwards to CodeGenFunction::InsertHelper.
llvm::ConstantInt * getSize(CharUnits N)
Definition CGBuilder.h:119
@ 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:60
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:4738
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:3107
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:713
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
SmallVector< llvm::ConvergenceControlInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void unprotectFromPeepholes(PeepholeProtection protection)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:7394
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4162
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:4043
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:179
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:588
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 emitReturnAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:255
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2541
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:186
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:236
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:4325
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:1419
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.
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:5796
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...
void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
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:3546
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:3164
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:60
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:5893
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:1538
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:4448
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:1653
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:679
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:1769
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:2161
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:659
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:435
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:1751
ConditionalOperator - The ?
Definition Expr.h:4460
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:583
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1106
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:569
SourceLocation getLocation() const
Definition DeclBase.h:449
bool hasAttr() const
Definition DeclBase.h:587
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4032
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3126
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:3110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
ExtVectorType - Extended vector type.
Definition TypeBase.h:4498
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3346
Represents a function declaration or definition.
Definition Decl.h:2082
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3287
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3848
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:3091
bool usesSEHTry() const
Indicates the function uses __try.
Definition Decl.h:2687
QualType getReturnType() const
Definition Decl.h:3027
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2952
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:4352
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3320
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3451
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition Decl.cpp:3602
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2597
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3444
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4218
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:5650
QualType desugar() const
Definition TypeBase.h:6231
FunctionTypeExtraAttributeInfo getExtraAttributeInfo() const
Return the extra attribute information.
Definition TypeBase.h:6139
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4846
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:5723
Represents the declaration of a label.
Definition Decl.h:526
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
@ FPE_MayTrap
Transformations do not cause new exceptions but may hide some.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
RoundingMode getDefaultRoundingMode() const
Represents a parameter to a function.
Definition Decl.h:1832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3404
@ 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:8764
field_range fields() const
Definition Decl.h:4715
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:1504
Likelihood
The likelihood of a branch being taken.
Definition Stmt.h:1447
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
Definition Stmt.h:1448
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
Definition Stmt.h:1449
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1451
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
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:9306
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2410
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2882
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
bool isObjCRetainableType() const
Definition Type.cpp:5638
bool isFunctionNoProtoType() const
Definition TypeBase.h:2664
bool isCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8963
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4065
Expr * getSizeExpr() const
Definition TypeBase.h:4079
QualType getElementType() const
Definition TypeBase.h:4413
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
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:6227
@ Other
Other implicit parameter.
Definition Decl.h:1787
@ EST_None
no exception specification
@ Implicit
An implicit conversion.
Definition Sema.h:434
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
This structure provides a set of types that are commonly used during IR emission.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5387
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