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